kconfiglib.py 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799
  1. #
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Author: Ulf Magnusson
  5. # https://github.com/ulfalizer/Kconfiglib
  6. # This is Kconfiglib, a Python library for scripting, debugging, and extracting
  7. # information from Kconfig-based configuration systems. To view the
  8. # documentation, run
  9. #
  10. # $ pydoc kconfiglib
  11. #
  12. # or, if you prefer HTML,
  13. #
  14. # $ pydoc -w kconfiglib
  15. #
  16. # The examples/ subdirectory contains examples, to be run with e.g.
  17. #
  18. # $ make scriptconfig SCRIPT=Kconfiglib/examples/print_tree.py
  19. #
  20. # Look in testsuite.py for the test suite.
  21. """
  22. Kconfiglib is a Python library for scripting and extracting information from
  23. Kconfig-based configuration systems. Features include the following:
  24. - Symbol values and properties can be looked up and values assigned
  25. programmatically.
  26. - .config files can be read and written.
  27. - Expressions can be evaluated in the context of a Kconfig configuration.
  28. - Relations between symbols can be quickly determined, such as finding all
  29. symbols that reference a particular symbol.
  30. - Highly compatible with the scripts/kconfig/*conf utilities. The test suite
  31. automatically compares outputs between Kconfiglib and the C implementation
  32. for a large number of cases.
  33. For the Linux kernel, scripts are run using
  34. $ make scriptconfig SCRIPT=<path to script> [SCRIPT_ARG=<arg>]
  35. Running scripts via the 'scriptconfig' target ensures that required environment
  36. variables (SRCARCH, ARCH, srctree, KERNELVERSION, etc.) are set up correctly.
  37. Alternative architectures can be specified like for other 'make *config'
  38. targets:
  39. $ make scriptconfig ARCH=mips SCRIPT=<path to script> [SCRIPT_ARG=<arg>]
  40. The script will receive the name of the Kconfig file to load in sys.argv[1].
  41. (As of Linux 3.7.0-rc8 this is always "Kconfig" from the kernel top-level
  42. directory.) If an argument is provided with SCRIPT_ARG, it will appear in
  43. sys.argv[2].
  44. To get an interactive Python prompt with Kconfiglib preloaded and a Config
  45. object 'c' created, use
  46. $ make iscriptconfig [ARCH=<architecture>]
  47. Kconfiglib requires Python 2. For (i)scriptconfig the command to run the Python
  48. interpreter can be passed in the environment variable PYTHONCMD (defaults to
  49. 'python'; PyPy works too and is a bit faster).
  50. Look in the examples/ subdirectory for examples, which can be run with e.g.
  51. $ make scriptconfig SCRIPT=Kconfiglib/examples/print_tree.py
  52. or
  53. $ make scriptconfig SCRIPT=Kconfiglib/examples/help_grep.py SCRIPT_ARG="kernel"
  54. Look in testsuite.py for the test suite.
  55. Credits: Written by Ulf "Ulfalizer" Magnusson
  56. Send bug reports, suggestions and other feedback to kconfiglib@gmail.com .
  57. Don't wrestle with internal APIs. Tell me what you need and I might add it in a
  58. safe way as a client API instead."""
  59. # If you have Psyco installed (32-bit installations, Python <= 2.6 only),
  60. # setting this to True (right here, not at runtime) might give a nice speedup.
  61. # (22% faster for parsing arch/x86/Kconfig and 58% faster for evaluating all
  62. # symbols in it without a .config on my Core Duo.)
  63. use_psyco = False
  64. import os
  65. import re
  66. import string
  67. import sys
  68. class Config():
  69. """Represents a Kconfig configuration, e.g. for i386 or ARM. This is the
  70. set of symbols and other items appearing in the configuration together with
  71. their values. Creating any number of Config objects -- including for
  72. different architectures -- is safe; Kconfiglib has no global state."""
  73. #
  74. # Public interface
  75. #
  76. def __init__(self,
  77. filename = "Kconfig",
  78. base_dir = "$srctree",
  79. print_warnings = True,
  80. print_undef_assign = False):
  81. """Creates a new Config object, representing a Kconfig configuration.
  82. Raises Kconfig_Syntax_Error on syntax errors.
  83. filename (default: "Kconfig") -- The base Kconfig file of the
  84. configuration. For the Linux kernel, this should usually be be
  85. "Kconfig" from the top-level directory, as environment
  86. variables will make sure the right Kconfig is included from
  87. there (usually arch/<architecture>/Kconfig). If you are using
  88. kconfiglib via 'make scriptconfig' the filename of the
  89. correct Kconfig will be in sys.argv[1].
  90. base_dir (default: "$srctree") -- The base directory relative to which
  91. 'source' statements within Kconfig files will work. For the
  92. Linux kernel this should be the top-level directory of the
  93. kernel tree. $-references to environment variables will be
  94. expanded.
  95. The environment variable 'srctree' is set by the Linux makefiles
  96. to the top-level kernel directory. A default of "." would not
  97. work if an alternative build directory is used.
  98. print_warnings (default: True) -- Set to True if warnings related to
  99. this configuration should be printed to stderr. This can
  100. be changed later with Config.set_print_warnings(). It is
  101. provided as a constructor argument since warnings might
  102. be generated during parsing.
  103. print_undef_assign (default: False) -- Set to True if informational
  104. messages related to assignments to undefined symbols
  105. should be printed to stderr for this configuration.
  106. Can be changed later with
  107. Config.set_print_undef_assign()."""
  108. # The set of all symbols, indexed by name (a string)
  109. self.syms = {}
  110. # The set of all defined symbols in the configuration in the order they
  111. # appear in the Kconfig files. This excludes the special symbols n, m,
  112. # and y as well as symbols that are referenced but never defined.
  113. self.kconfig_syms = []
  114. # The set of all named choices (yes, choices can have names), indexed
  115. # by name (a string)
  116. self.named_choices = {}
  117. def register_special_symbol(type, name, value):
  118. sym = Symbol()
  119. sym.is_special_ = True
  120. sym.is_defined_ = True
  121. sym.config = self
  122. sym.name = name
  123. sym.type = type
  124. sym.cached_value = value
  125. self.syms[name] = sym
  126. return sym
  127. # The special symbols n, m and y, used as shorthand for "n", "m" and
  128. # "y"
  129. self.n = register_special_symbol(TRISTATE, "n", "n")
  130. self.m = register_special_symbol(TRISTATE, "m", "m")
  131. self.y = register_special_symbol(TRISTATE, "y", "y")
  132. # DEFCONFIG_LIST uses this
  133. register_special_symbol(STRING, "UNAME_RELEASE", os.uname()[2])
  134. # The symbol with "option defconfig_list" set, containing a list of
  135. # default .config files
  136. self.defconfig_sym = None
  137. # See Symbol.get_(src)arch()
  138. self.arch = os.environ.get("ARCH")
  139. self.srcarch = os.environ.get("SRCARCH")
  140. # See Config.__init__(). We need this for get_defconfig_filename().
  141. self.srctree = os.environ.get("srctree")
  142. if self.srctree is None:
  143. self.srctree = "."
  144. self.filename = filename
  145. self.base_dir = _strip_trailing_slash(os.path.expandvars(base_dir))
  146. # The 'mainmenu' text
  147. self.mainmenu_text = None
  148. # The filename of the most recently loaded .config file
  149. self.config_filename = None
  150. # The textual header of the most recently loaded .config, uncommented
  151. self.config_header = None
  152. self.print_warnings = print_warnings
  153. self.print_undef_assign = print_undef_assign
  154. # Lists containing all choices, menus and comments in the configuration
  155. self.choices = []
  156. self.menus = []
  157. self.comments = []
  158. # For parsing routines that stop when finding a line belonging to a
  159. # different construct, these holds that line and the tokenized version
  160. # of that line. The purpose is to avoid having to re-tokenize the line,
  161. # which is inefficient and causes problems when recording references to
  162. # symbols.
  163. self.end_line = None
  164. self.end_line_tokens = None
  165. # See the comment in _parse_expr().
  166. self.parse_expr_cur_sym_or_choice = None
  167. self.parse_expr_line = None
  168. self.parse_expr_filename = None
  169. self.parse_expr_linenr = None
  170. self.parse_expr_transform_m = None
  171. # Parse the Kconfig files
  172. self.top_block = self._parse_file(filename, None, None, None)
  173. # Build Symbol.dep for all symbols
  174. self._build_dep()
  175. def load_config(self, filename, replace = True):
  176. """Loads symbol values from a file in the familiar .config format.
  177. Equivalent to calling Symbol.set_user_value() to set each of the
  178. values.
  179. filename -- The .config file to load. $-references to environment
  180. variables will be expanded. For scripts to work even
  181. when an alternative build directory is used with the
  182. Linux kernel, you need to refer to the top-level kernel
  183. directory with "$srctree".
  184. replace (default: True) -- True if the configuration should replace
  185. the old configuration; False if it should add to it."""
  186. def warn_override(filename, linenr, name, old_user_val, new_user_val):
  187. self._warn("overriding the value of {0}. "
  188. 'Old value: "{1}", new value: "{2}".'
  189. .format(name, old_user_val, new_user_val),
  190. filename,
  191. linenr)
  192. filename = os.path.expandvars(filename)
  193. # Put this first so that a missing file doesn't screw up our state
  194. line_feeder = _FileFeed(_get_lines(filename), filename)
  195. self.config_filename = filename
  196. # Invalidate everything. This is usually faster than finding the
  197. # minimal set of symbols that needs to be invalidated, as nearly all
  198. # symbols will tend to be affected anyway.
  199. if replace:
  200. self.unset_user_values()
  201. else:
  202. self._invalidate_all()
  203. # Read header
  204. self.config_header = None
  205. def is_header_line(line):
  206. return line.startswith("#") and \
  207. not unset_re.match(line)
  208. first_line = line_feeder.get_next()
  209. if first_line is None:
  210. return
  211. if not is_header_line(first_line):
  212. line_feeder.go_back()
  213. else:
  214. self.config_header = first_line[1:]
  215. # Read remaining header lines
  216. while 1:
  217. line = line_feeder.get_next()
  218. if line is None:
  219. break
  220. if not is_header_line(line):
  221. line_feeder.go_back()
  222. break
  223. self.config_header += line[1:]
  224. # Remove trailing newline
  225. if self.config_header.endswith("\n"):
  226. self.config_header = self.config_header[:-1]
  227. # Read assignments
  228. filename = line_feeder.get_filename()
  229. while 1:
  230. line = line_feeder.get_next()
  231. if line is None:
  232. return
  233. linenr = line_feeder.get_linenr()
  234. line = line.strip()
  235. set_re_match = set_re.match(line)
  236. if set_re_match:
  237. name, val = set_re_match.groups()
  238. # The unescaping producedure below should be safe since " can
  239. # only appear as \" inside the string
  240. val = _strip_quotes(val, line, filename, linenr)\
  241. .replace('\\"', '"').replace("\\\\", "\\")
  242. if name in self.syms:
  243. sym = self.syms[name]
  244. old_user_val = sym.user_val
  245. if old_user_val is not None:
  246. warn_override(filename, linenr, name, old_user_val, val)
  247. if sym.is_choice_symbol_:
  248. user_mode = sym.parent.user_mode
  249. if user_mode is not None and user_mode != val:
  250. self._warn("assignment to {0} changes mode of containing "
  251. 'choice from "{1}" to "{2}".'
  252. .format(name, val, user_mode),
  253. filename,
  254. linenr)
  255. sym._set_user_value_no_invalidate(val, True)
  256. else:
  257. self._undef_assign('attempt to assign the value "{0}" to the '
  258. "undefined symbol {1}."
  259. .format(val, name),
  260. filename,
  261. linenr)
  262. else:
  263. unset_re_match = unset_re.match(line)
  264. if unset_re_match:
  265. name = unset_re_match.group(1)
  266. if name in self.syms:
  267. sym = self.syms[name]
  268. old_user_val = sym.user_val
  269. if old_user_val is not None:
  270. warn_override(filename, linenr, name, old_user_val, "n")
  271. sym._set_user_value_no_invalidate("n", True)
  272. def write_config(self, filename, header = None):
  273. """Writes out symbol values in the familiar .config format.
  274. filename -- The filename under which to save the configuration.
  275. header (default: None) -- A textual header that will appear at the
  276. beginning of the file, with each line commented out
  277. automatically. None means no header."""
  278. # already_written is set when _make_conf() is called on a symbol, so
  279. # that symbols defined in multiple locations only get one entry in the
  280. # .config. We need to reset it prior to writing out a new .config.
  281. for sym in self.syms.itervalues():
  282. sym.already_written = False
  283. with open(filename, "w") as f:
  284. # Write header
  285. if header is not None:
  286. f.write(_comment(header))
  287. f.write("\n")
  288. # Write configuration.
  289. # (You'd think passing a list around to all the nodes and appending
  290. # to it to avoid copying would be faster, but it's actually a lot
  291. # slower with PyPy, and about as fast with Python. Passing the file
  292. # around is slower too.)
  293. f.write("\n".join(self.top_block._make_conf()))
  294. f.write("\n")
  295. def get_kconfig_filename(self):
  296. """Returns the name of the (base) kconfig file this configuration was
  297. loaded from."""
  298. return self.filename
  299. def get_arch(self):
  300. """Returns the value the environment variable ARCH had at the time the
  301. Config instance was created, or None if ARCH was not set. For the
  302. kernel, this corresponds to the architecture being built for, with
  303. values such as "i386" or "mips"."""
  304. return self.arch
  305. def get_srcarch(self):
  306. """Returns the value the environment variable SRCARCH had at the time
  307. the Config instance was created, or None if SRCARCH was not set. For
  308. the kernel, this corresponds to the arch/ subdirectory containing
  309. architecture-specific source code."""
  310. return self.srcarch
  311. def get_srctree(self):
  312. """Returns the value the environment variable srctree had at the time
  313. the Config instance was created, or None if srctree was not defined.
  314. This variable points to the source directory and is used when building
  315. in a separate directory."""
  316. return self.srctree
  317. def get_config_filename(self):
  318. """Returns the name of the most recently loaded configuration file, or
  319. None if no configuration has been loaded."""
  320. return self.config_filename
  321. def get_mainmenu_text(self):
  322. """Returns the text of the 'mainmenu' statement (with $-references to
  323. symbols replaced by symbol values), or None if the configuration has no
  324. 'mainmenu' statement."""
  325. return None if self.mainmenu_text is None else \
  326. self._expand_sym_refs(self.mainmenu_text)
  327. def get_defconfig_filename(self):
  328. """Returns the name of the defconfig file, which is the first existing
  329. file in the list given in a symbol having 'option defconfig_list' set.
  330. $-references to symbols will be expanded ("$FOO bar" -> "foo bar" if
  331. FOO has the value "foo"). Returns None in case of no defconfig file.
  332. Setting 'option defconfig_list' on multiple symbols currently results
  333. in undefined behavior.
  334. If the environment variable 'srctree' was set when the Config was
  335. created, get_defconfig_filename() will first look relative to that
  336. directory before looking in the current directory; see
  337. Config.__init__()."""
  338. if self.defconfig_sym is None:
  339. return None
  340. for (filename, cond_expr) in self.defconfig_sym.def_exprs:
  341. if self._eval_expr(cond_expr) == "y":
  342. filename = self._expand_sym_refs(filename)
  343. # We first look in $srctree. os.path.join() won't work here as
  344. # an absolute path in filename would override $srctree.
  345. srctree_filename = os.path.normpath(self.srctree + "/" + filename)
  346. if os.path.exists(srctree_filename):
  347. return srctree_filename
  348. if os.path.exists(filename):
  349. return filename
  350. return None
  351. def get_symbol(self, name):
  352. """Returns the symbol with name 'name', or None if no such symbol
  353. appears in the configuration. An alternative shorthand is conf[name],
  354. where conf is a Config instance, though that will instead raise
  355. KeyError if the symbol does not exist."""
  356. return self.syms.get(name)
  357. def get_top_level_items(self):
  358. """Returns a list containing the items (symbols, menus, choice
  359. statements and comments) at the top level of the configuration -- that
  360. is, all items that do not appear within a menu or choice. The items
  361. appear in the same order as within the configuration."""
  362. return self.top_block.get_items()
  363. def get_symbols(self, all_symbols = True):
  364. """Returns a list of symbols from the configuration. An alternative for
  365. iterating over all defined symbols (in the order of definition) is
  366. for sym in config:
  367. ...
  368. which relies on Config implementing __iter__() and is equivalent to
  369. for sym in config.get_symbols(False):
  370. ...
  371. all_symbols (default: True) -- If True, all symbols - including special
  372. and undefined symbols - will be included in the result, in
  373. an undefined order. If False, only symbols actually defined
  374. and not merely referred to in the configuration will be
  375. included in the result, and will appear in the order that
  376. they are defined within the Kconfig configuration files."""
  377. return self.syms.values() if all_symbols else self.kconfig_syms
  378. def get_choices(self):
  379. """Returns a list containing all choice statements in the
  380. configuration, in the order they appear in the Kconfig files."""
  381. return self.choices
  382. def get_menus(self):
  383. """Returns a list containing all menus in the configuration, in the
  384. order they appear in the Kconfig files."""
  385. return self.menus
  386. def get_comments(self):
  387. """Returns a list containing all comments in the configuration, in the
  388. order they appear in the Kconfig files."""
  389. return self.comments
  390. def eval(self, s):
  391. """Returns the value of the expression 's' -- where 's' is represented
  392. as a string -- in the context of the configuration. Raises
  393. Kconfig_Syntax_Error if syntax errors are detected in 's'.
  394. For example, if FOO and BAR are tristate symbols at least one of which
  395. has the value "y", then config.eval("y && (FOO || BAR)") => "y"
  396. This functions always yields a tristate value. To get the value of
  397. non-bool, non-tristate symbols, use Symbol.get_value().
  398. The result of this function is consistent with how evaluation works for
  399. conditional expressions in the configuration as well as in the C
  400. implementation. "m" and m are rewritten as '"m" && MODULES' and 'm &&
  401. MODULES', respectively, and a result of "m" will get promoted to "y" if
  402. we're running without modules."""
  403. return self._eval_expr(self._parse_expr(self._tokenize(s, True), # Feed
  404. None, # Current symbol or choice
  405. s)) # line
  406. def get_config_header(self):
  407. """Returns the (uncommented) textual header of the .config file most
  408. recently loaded with load_config(). Returns None if no .config file has
  409. been loaded or if the most recently loaded .config file has no header.
  410. The header comprises all lines up to but not including the first line
  411. that either
  412. 1. Does not start with "#"
  413. 2. Has the form "# CONFIG_FOO is not set."
  414. """
  415. return self.config_header
  416. def get_base_dir(self):
  417. """Returns the base directory relative to which 'source' statements
  418. will work, passed as an argument to Config.__init__()."""
  419. return self.base_dir
  420. def set_print_warnings(self, print_warnings):
  421. """Determines whether warnings related to this configuration (for
  422. things like attempting to assign illegal values to symbols with
  423. Symbol.set_user_value()) should be printed to stderr.
  424. print_warnings -- True if warnings should be
  425. printed, otherwise False."""
  426. self.print_warnings = print_warnings
  427. def set_print_undef_assign(self, print_undef_assign):
  428. """Determines whether informational messages related to assignments to
  429. undefined symbols should be printed to stderr for this configuration.
  430. print_undef_assign -- If True, such messages will be printed."""
  431. self.print_undef_assign = print_undef_assign
  432. def __getitem__(self, key):
  433. """Returns the symbol with name 'name'. Raises KeyError if the symbol
  434. does not appear in the configuration."""
  435. return self.syms[key]
  436. def __iter__(self):
  437. """Convenience function for iterating over the set of all defined
  438. symbols in the configuration, used like
  439. for sym in conf:
  440. ...
  441. The iteration happens in the order of definition within the Kconfig
  442. configuration files. Symbols only referred to but not defined will not
  443. be included, nor will the special symbols n, m, and y. If you want to
  444. include such symbols as well, see config.get_symbols()."""
  445. return iter(self.kconfig_syms)
  446. def unset_user_values(self):
  447. """Resets the values of all symbols, as if Config.load_config() or
  448. Symbol.set_user_value() had never been called."""
  449. for sym in self.syms.itervalues():
  450. sym._unset_user_value_no_recursive_invalidate()
  451. def __str__(self):
  452. """Returns a string containing various information about the Config."""
  453. return _sep_lines("Configuration",
  454. "File : " + self.filename,
  455. "Base directory : " + self.base_dir,
  456. "Value of $ARCH at creation time : " +
  457. ("(not set)" if self.arch is None else self.arch),
  458. "Value of $SRCARCH at creation time : " +
  459. ("(not set)" if self.srcarch is None else self.srcarch),
  460. "Source tree (derived from $srctree;",
  461. "defaults to '.' if $srctree isn't set) : " + self.srctree,
  462. "Most recently loaded .config : " +
  463. ("(no .config loaded)" if self.config_filename is None else
  464. self.config_filename),
  465. "Print warnings : " +
  466. bool_str[self.print_warnings],
  467. "Print assignments to undefined symbols : " +
  468. bool_str[self.print_undef_assign])
  469. #
  470. # Private methods
  471. #
  472. def _invalidate_all(self):
  473. for sym in self.syms.itervalues():
  474. sym._invalidate()
  475. def _tokenize(self,
  476. s,
  477. for_eval = False,
  478. filename = None,
  479. linenr = None):
  480. """Returns a _Feed instance containing tokens derived from the string
  481. 's'. Registers any new symbols encountered (via _sym_lookup()).
  482. (I experimented with a pure regular expression implementation, but it
  483. came out slower, less readable, and wouldn't have been as flexible.)
  484. for_eval -- True when parsing an expression for a call to
  485. Config.eval(), in which case we should not treat the first
  486. token specially nor register new symbols."""
  487. s = s.lstrip()
  488. if s == "" or s[0] == "#":
  489. return _Feed([])
  490. if for_eval:
  491. i = 0 # The current index in the string being tokenized
  492. previous = None # The previous token seen
  493. tokens = []
  494. else:
  495. # The initial word on a line is parsed specially. Let
  496. # command_chars = [A-Za-z0-9_]. Then
  497. # - leading non-command_chars characters on the line are ignored, and
  498. # - the first token consists the following one or more command_chars
  499. # characters.
  500. # This is why things like "----help--" are accepted.
  501. initial_token_match = initial_token_re.match(s)
  502. if initial_token_match is None:
  503. return _Feed([])
  504. # The current index in the string being tokenized
  505. i = initial_token_match.end()
  506. keyword = keywords.get(initial_token_match.group(1))
  507. if keyword is None:
  508. # We expect a keyword as the first token
  509. _tokenization_error(s, len(s), filename, linenr)
  510. if keyword == T_HELP:
  511. # Avoid junk after "help", e.g. "---", being registered as a
  512. # symbol
  513. return _Feed([T_HELP])
  514. tokens = [keyword]
  515. previous = keyword
  516. # _tokenize() is a hotspot during parsing, and this speeds things up a
  517. # bit
  518. strlen = len(s)
  519. append = tokens.append
  520. # Main tokenization loop. (Handles tokens past the first one.)
  521. while i < strlen:
  522. # Test for an identifier/keyword preceded by whitespace first; this
  523. # is the most common case.
  524. id_keyword_match = id_keyword_re.match(s, i)
  525. if id_keyword_match:
  526. # We have an identifier or keyword. The above also stripped any
  527. # whitespace for us.
  528. name = id_keyword_match.group(1)
  529. # Jump past it
  530. i = id_keyword_match.end()
  531. # Keyword?
  532. keyword = keywords.get(name)
  533. if keyword is not None:
  534. append(keyword)
  535. # What would ordinarily be considered a name is treated as a
  536. # string after certain tokens.
  537. elif previous in string_lex:
  538. append(name)
  539. else:
  540. # We're dealing with a symbol. _sym_lookup() will take care
  541. # of allocating a new Symbol instance if it's the first
  542. # time we see it.
  543. sym = self._sym_lookup(name, not for_eval)
  544. if previous == T_CONFIG or previous == T_MENUCONFIG:
  545. # If the previous token is T_(MENU)CONFIG
  546. # ("(menu)config"), we're tokenizing the first line of
  547. # a symbol definition, and should remember this as a
  548. # location where the symbol is defined.
  549. sym.def_locations.append((filename, linenr))
  550. else:
  551. # Otherwise, it's a reference to the symbol
  552. sym.ref_locations.append((filename, linenr))
  553. append(sym)
  554. else:
  555. # This restrips whitespace that could have been stripped in the
  556. # regex above, but it's worth it since identifiers/keywords are
  557. # more common
  558. s = s[i:].lstrip()
  559. if s == "":
  560. break
  561. strlen = len(s)
  562. i = 0
  563. c = s[0]
  564. # String literal (constant symbol)
  565. if c == '"' or c == "'":
  566. i += 1
  567. if "\\" in s:
  568. # Slow path: This could probably be sped up, but it's a
  569. # very unusual case anyway.
  570. quote = c
  571. value = ""
  572. while 1:
  573. if i >= strlen:
  574. _tokenization_error(s, strlen, filename,
  575. linenr)
  576. c = s[i]
  577. if c == quote:
  578. break
  579. if c == "\\":
  580. if i + 1 >= strlen:
  581. _tokenization_error(s, strlen, filename,
  582. linenr)
  583. value += s[i + 1]
  584. i += 2
  585. else:
  586. value += c
  587. i += 1
  588. i += 1
  589. append(value)
  590. else:
  591. # Fast path: If the string contains no backslashes (almost
  592. # always) we can simply look for the matching quote.
  593. end = s.find(c, i)
  594. if end == -1:
  595. _tokenization_error(s, strlen, filename, linenr)
  596. append(s[i:end])
  597. i = end + 1
  598. elif c == "&":
  599. if i + 1 >= strlen:
  600. # Invalid characters are ignored
  601. continue
  602. if s[i + 1] != "&":
  603. # Invalid characters are ignored
  604. i += 1
  605. continue
  606. append(T_AND)
  607. i += 2
  608. elif c == "|":
  609. if i + 1 >= strlen:
  610. # Invalid characters are ignored
  611. continue
  612. if s[i + 1] != "|":
  613. # Invalid characters are ignored
  614. i += 1
  615. continue
  616. append(T_OR)
  617. i += 2
  618. elif c == "!":
  619. if i + 1 >= strlen:
  620. _tokenization_error(s, strlen, filename, linenr)
  621. if s[i + 1] == "=":
  622. append(T_UNEQUAL)
  623. i += 2
  624. else:
  625. append(T_NOT)
  626. i += 1
  627. elif c == "=":
  628. append(T_EQUAL)
  629. i += 1
  630. elif c == "(":
  631. append(T_OPEN_PAREN)
  632. i += 1
  633. elif c == ")":
  634. append(T_CLOSE_PAREN)
  635. i += 1
  636. elif c == "#":
  637. break
  638. else:
  639. # Invalid characters are ignored
  640. i += 1
  641. continue
  642. previous = tokens[-1]
  643. return _Feed(tokens)
  644. #
  645. # Parsing
  646. #
  647. # Expression grammar:
  648. #
  649. # <expr> -> <symbol>
  650. # <symbol> '=' <symbol>
  651. # <symbol> '!=' <symbol>
  652. # '(' <expr> ')'
  653. # '!' <expr>
  654. # <expr> '&&' <expr>
  655. # <expr> '||' <expr>
  656. def _parse_expr(self,
  657. feed,
  658. cur_sym_or_choice,
  659. line,
  660. filename = None,
  661. linenr = None,
  662. transform_m = True):
  663. """Parse an expression from the tokens in 'feed' using a simple
  664. top-down approach. The result has the form (<operator>, <list
  665. containing parsed operands>).
  666. feed -- _Feed instance containing the tokens for the expression.
  667. cur_sym_or_choice -- The symbol or choice currently being parsed, or
  668. None if we're not parsing a symbol or choice.
  669. Used for recording references to symbols.
  670. line -- The line containing the expression being parsed.
  671. filename (default: None) -- The file containing the expression.
  672. linenr (default: None) -- The line number containing the expression.
  673. transform_m (default: False) -- Determines if 'm' should be rewritten to
  674. 'm && MODULES' -- see
  675. parse_val_and_cond()."""
  676. # Use instance variables to avoid having to pass these as arguments
  677. # through the top-down parser in _parse_expr_2(), which is tedious and
  678. # obfuscates the code. A profiler run shows no noticeable performance
  679. # difference.
  680. self.parse_expr_cur_sym_or_choice = cur_sym_or_choice
  681. self.parse_expr_line = line
  682. self.parse_expr_filename = filename
  683. self.parse_expr_linenr = linenr
  684. self.parse_expr_transform_m = transform_m
  685. return self._parse_expr_2(feed)
  686. def _parse_expr_2(self, feed):
  687. or_terms = [self._parse_or_term(feed)]
  688. # Keep parsing additional terms while the lookahead is '||'
  689. while feed.check(T_OR):
  690. or_terms.append(self._parse_or_term(feed))
  691. return or_terms[0] if len(or_terms) == 1 else (OR, or_terms)
  692. def _parse_or_term(self, feed):
  693. and_terms = [self._parse_factor(feed)]
  694. # Keep parsing additional terms while the lookahead is '&&'
  695. while feed.check(T_AND):
  696. and_terms.append(self._parse_factor(feed))
  697. return and_terms[0] if len(and_terms) == 1 else (AND, and_terms)
  698. def _parse_factor(self, feed):
  699. if feed.check(T_OPEN_PAREN):
  700. expr_parse = self._parse_expr_2(feed)
  701. if not feed.check(T_CLOSE_PAREN):
  702. _parse_error(self.parse_expr_line,
  703. "missing end parenthesis.",
  704. self.parse_expr_filename,
  705. self.parse_expr_linenr)
  706. return expr_parse
  707. if feed.check(T_NOT):
  708. return (NOT, self._parse_factor(feed))
  709. sym_or_string = feed.get_next()
  710. if not isinstance(sym_or_string, (Symbol, str)):
  711. _parse_error(self.parse_expr_line,
  712. "malformed expression.",
  713. self.parse_expr_filename,
  714. self.parse_expr_linenr)
  715. if self.parse_expr_cur_sym_or_choice is not None and \
  716. isinstance(sym_or_string, Symbol):
  717. self.parse_expr_cur_sym_or_choice.referenced_syms.add(sym_or_string)
  718. next_token = feed.peek_next()
  719. # For conditional expressions ('depends on <expr>', '... if <expr>',
  720. # etc.), "m" and m are rewritten to "m" && MODULES.
  721. if next_token != T_EQUAL and next_token != T_UNEQUAL:
  722. if self.parse_expr_transform_m and (sym_or_string is self.m or
  723. sym_or_string == "m"):
  724. return (AND, ["m", self._sym_lookup("MODULES")])
  725. return sym_or_string
  726. relation = EQUAL if (feed.get_next() == T_EQUAL) else UNEQUAL
  727. sym_or_string_2 = feed.get_next()
  728. if self.parse_expr_cur_sym_or_choice is not None and \
  729. isinstance(sym_or_string_2, Symbol):
  730. self.parse_expr_cur_sym_or_choice.referenced_syms.add(sym_or_string_2)
  731. if sym_or_string is self.m:
  732. sym_or_string = "m"
  733. if sym_or_string_2 is self.m:
  734. sym_or_string_2 = "m"
  735. return (relation, sym_or_string, sym_or_string_2)
  736. def _parse_file(self, filename, parent, deps, visible_if_deps, res = None):
  737. """Parse the Kconfig file 'filename'. The result is a _Block with all
  738. items from the file. See _parse_block() for the meaning of the
  739. parameters."""
  740. line_feeder = _FileFeed(_get_lines(filename), filename)
  741. return self._parse_block(line_feeder, None, parent, deps, visible_if_deps, res)
  742. def _parse_block(self, line_feeder, end_marker, parent, deps,
  743. visible_if_deps = None, res = None):
  744. """Parses a block, which is the contents of either a file or an if,
  745. menu, or choice statement. The result is a _Block with the items from
  746. the block.
  747. end_marker -- The token that ends the block, e.g. T_ENDIF ("endif") for
  748. if's. None for files.
  749. parent -- The enclosing menu, choice or if, or None if we're at the top
  750. level.
  751. deps -- Dependencies from enclosing menus, choices and if's.
  752. visible_if_deps (default: None) -- 'visible if' dependencies from
  753. enclosing menus.
  754. res (default: None) -- The _Block to add items to. If None, a new
  755. _Block is created to hold the items."""
  756. block = _Block() if res is None else res
  757. filename = line_feeder.get_filename()
  758. while 1:
  759. # Do we already have a tokenized line that we determined wasn't
  760. # part of whatever we were parsing earlier? See comment in
  761. # Config.__init__().
  762. if self.end_line is not None:
  763. assert self.end_line_tokens is not None
  764. tokens = self.end_line_tokens
  765. tokens.go_to_start()
  766. line = self.end_line
  767. linenr = line_feeder.get_linenr()
  768. self.end_line = None
  769. self.end_line_tokens = None
  770. else:
  771. line = line_feeder.get_next()
  772. if line is None:
  773. if end_marker is not None:
  774. raise Kconfig_Syntax_Error, (
  775. "Unexpected end of file {0}."
  776. .format(line_feeder.get_filename()))
  777. return block
  778. linenr = line_feeder.get_linenr()
  779. tokens = self._tokenize(line, False, filename, linenr)
  780. if tokens.is_empty():
  781. continue
  782. t0 = tokens.get_next()
  783. # Have we reached the end of the block?
  784. if t0 == end_marker:
  785. return block
  786. if t0 == T_CONFIG or t0 == T_MENUCONFIG:
  787. # The tokenizer will automatically allocate a new Symbol object
  788. # for any new names it encounters, so we don't need to worry
  789. # about that here.
  790. sym = tokens.get_next()
  791. # Symbols defined in multiple places get the parent of their
  792. # first definition. However, for symbols whose parents are choice
  793. # statements, the choice statement takes precedence.
  794. if not sym.is_defined_ or isinstance(parent, Choice):
  795. sym.parent = parent
  796. sym.is_defined_ = True
  797. self.kconfig_syms.append(sym)
  798. block.add_item(sym)
  799. self._parse_properties(line_feeder, sym, deps, visible_if_deps)
  800. elif t0 == T_MENU:
  801. menu = Menu()
  802. self.menus.append(menu)
  803. menu.config = self
  804. menu.parent = parent
  805. menu.title = tokens.get_next()
  806. menu.filename = filename
  807. menu.linenr = linenr
  808. # Parse properties and contents
  809. self._parse_properties(line_feeder, menu, deps, visible_if_deps)
  810. menu.block = self._parse_block(line_feeder,
  811. T_ENDMENU,
  812. menu,
  813. menu.dep_expr,
  814. _make_and(visible_if_deps,
  815. menu.visible_if_expr))
  816. block.add_item(menu)
  817. elif t0 == T_IF:
  818. # If statements are treated as syntactic sugar for adding
  819. # dependencies to enclosed items and do not have an explicit
  820. # object representation.
  821. dep_expr = self._parse_expr(tokens, None, line, filename, linenr)
  822. self._parse_block(line_feeder,
  823. T_ENDIF,
  824. parent,
  825. _make_and(dep_expr, deps),
  826. visible_if_deps,
  827. block) # Add items to the same block
  828. elif t0 == T_CHOICE:
  829. # We support named choices
  830. already_defined = False
  831. name = None
  832. if len(tokens) > 1 and isinstance(tokens[1], str):
  833. name = tokens[1]
  834. already_defined = name in self.named_choices
  835. if already_defined:
  836. choice = self.named_choices[name]
  837. else:
  838. choice = Choice()
  839. self.choices.append(choice)
  840. if name is not None:
  841. choice.name = name
  842. self.named_choices[name] = choice
  843. choice.config = self
  844. choice.parent = parent
  845. choice.def_locations.append((filename, linenr))
  846. # Parse properties and contents
  847. self._parse_properties(line_feeder, choice, deps, visible_if_deps)
  848. choice.block = self._parse_block(line_feeder,
  849. T_ENDCHOICE,
  850. choice,
  851. None,
  852. visible_if_deps)
  853. choice._determine_actual_symbols()
  854. # If no type is set for the choice, its type is that of the first
  855. # choice item
  856. if choice.type == UNKNOWN:
  857. for item in choice.get_symbols():
  858. if item.type != UNKNOWN:
  859. choice.type = item.type
  860. break
  861. # Each choice item of UNKNOWN type gets the type of the choice
  862. for item in choice.get_symbols():
  863. if item.type == UNKNOWN:
  864. item.type = choice.type
  865. # For named choices defined in multiple locations, only record
  866. # at the first definition
  867. if not already_defined:
  868. block.add_item(choice)
  869. elif t0 == T_COMMENT:
  870. comment = Comment()
  871. comment.config = self
  872. comment.parent = parent
  873. comment.filename = filename
  874. comment.linenr = linenr
  875. comment.text = tokens.get_next()
  876. self._parse_properties(line_feeder, comment, deps, visible_if_deps)
  877. block.add_item(comment)
  878. self.comments.append(comment)
  879. elif t0 == T_SOURCE:
  880. kconfig_file = tokens.get_next()
  881. exp_kconfig_file = self._expand_sym_refs(kconfig_file)
  882. f = os.path.join(self.base_dir, exp_kconfig_file)
  883. if not os.path.exists(f):
  884. raise IOError, ('{0}:{1}: sourced file "{2}" (expands to\n'
  885. '"{3}") not found. Perhaps base_dir\n'
  886. '(argument to Config.__init__(), currently\n'
  887. '"{4}") is set to the wrong value.'
  888. .format(filename,
  889. linenr,
  890. kconfig_file,
  891. exp_kconfig_file,
  892. self.base_dir))
  893. # Add items to the same block
  894. self._parse_file(f, parent, deps, visible_if_deps, block)
  895. elif t0 == T_MAINMENU:
  896. text = tokens.get_next()
  897. if self.mainmenu_text is not None:
  898. self._warn("overriding 'mainmenu' text. "
  899. 'Old value: "{0}", new value: "{1}".'
  900. .format(self.mainmenu_text, text),
  901. filename,
  902. linenr)
  903. self.mainmenu_text = text
  904. else:
  905. _parse_error(line, "unrecognized construct.", filename, linenr)
  906. def _parse_properties(self, line_feeder, stmt, deps, visible_if_deps):
  907. """Parsing of properties for symbols, menus, choices, and comments."""
  908. def parse_val_and_cond(tokens, line, filename, linenr):
  909. """Parses '<expr1> if <expr2>' constructs, where the 'if' part is
  910. optional. Returns a tuple containing the parsed expressions, with
  911. None as the second element if the 'if' part is missing."""
  912. val = self._parse_expr(tokens, stmt, line, filename, linenr, False)
  913. if tokens.check(T_IF):
  914. return (val, self._parse_expr(tokens, stmt, line, filename, linenr))
  915. return (val, None)
  916. # In case the symbol is defined in multiple locations, we need to
  917. # remember what prompts, defaults, and selects are new for this
  918. # definition, as "depends on" should only apply to the local
  919. # definition.
  920. new_prompt = None
  921. new_def_exprs = []
  922. new_selects = []
  923. # Dependencies from 'depends on' statements
  924. depends_on_expr = None
  925. while 1:
  926. line = line_feeder.get_next()
  927. if line is None:
  928. break
  929. filename = line_feeder.get_filename()
  930. linenr = line_feeder.get_linenr()
  931. tokens = self._tokenize(line, False, filename, linenr)
  932. if tokens.is_empty():
  933. continue
  934. t0 = tokens.get_next()
  935. if t0 == T_HELP:
  936. # Find first non-empty line and get its indentation
  937. line_feeder.remove_while(str.isspace)
  938. line = line_feeder.get_next()
  939. if line is None:
  940. stmt.help = ""
  941. break
  942. indent = _indentation(line)
  943. # If the first non-empty lines has zero indent, there is no
  944. # help text
  945. if indent == 0:
  946. stmt.help = ""
  947. line_feeder.go_back()
  948. break
  949. help_lines = [_deindent(line, indent)]
  950. # The help text goes on till the first non-empty line with less
  951. # indent
  952. while 1:
  953. line = line_feeder.get_next()
  954. if (line is None) or \
  955. (not line.isspace() and _indentation(line) < indent):
  956. stmt.help = "".join(help_lines)
  957. break
  958. help_lines.append(_deindent(line, indent))
  959. if line is None:
  960. break
  961. line_feeder.go_back()
  962. elif t0 == T_PROMPT:
  963. # 'prompt' properties override each other within a single
  964. # definition of a symbol, but additional prompts can be added
  965. # by defining the symbol multiple times; hence 'new_prompt'
  966. # instead of 'prompt'.
  967. new_prompt = parse_val_and_cond(tokens, line, filename, linenr)
  968. elif t0 == T_DEFAULT:
  969. new_def_exprs.append(parse_val_and_cond(tokens, line, filename, linenr))
  970. elif t0 == T_DEPENDS:
  971. if not tokens.check(T_ON):
  972. _parse_error(line, 'expected "on" after "depends".', filename, linenr)
  973. parsed_deps = self._parse_expr(tokens, stmt, line, filename, linenr)
  974. if isinstance(stmt, (Menu, Comment)):
  975. stmt.dep_expr = _make_and(stmt.dep_expr, parsed_deps)
  976. else:
  977. depends_on_expr = _make_and(depends_on_expr, parsed_deps)
  978. elif t0 == T_VISIBLE:
  979. if not tokens.check(T_IF):
  980. _parse_error(line, 'expected "if" after "visible".', filename, linenr)
  981. if not isinstance(stmt, Menu):
  982. _parse_error(line,
  983. "'visible if' is only valid for menus.",
  984. filename,
  985. linenr)
  986. parsed_deps = self._parse_expr(tokens, stmt, line, filename, linenr)
  987. stmt.visible_if_expr = _make_and(stmt.visible_if_expr, parsed_deps)
  988. elif t0 == T_SELECT:
  989. target = tokens.get_next()
  990. stmt.referenced_syms.add(target)
  991. stmt.selected_syms.add(target)
  992. if tokens.check(T_IF):
  993. new_selects.append((target,
  994. self._parse_expr(tokens, stmt, line, filename, linenr)))
  995. else:
  996. new_selects.append((target, None))
  997. elif t0 in (T_BOOL, T_TRISTATE, T_INT, T_HEX, T_STRING):
  998. stmt.type = token_to_type[t0]
  999. if len(tokens) > 1:
  1000. new_prompt = parse_val_and_cond(tokens, line, filename, linenr)
  1001. elif t0 == T_RANGE:
  1002. lower = tokens.get_next()
  1003. upper = tokens.get_next()
  1004. stmt.referenced_syms.add(lower)
  1005. stmt.referenced_syms.add(upper)
  1006. if tokens.check(T_IF):
  1007. stmt.ranges.append((lower, upper,
  1008. self._parse_expr(tokens, stmt, line, filename, linenr)))
  1009. else:
  1010. stmt.ranges.append((lower, upper, None))
  1011. elif t0 == T_DEF_BOOL:
  1012. stmt.type = BOOL
  1013. if len(tokens) > 1:
  1014. new_def_exprs.append(parse_val_and_cond(tokens, line, filename, linenr))
  1015. elif t0 == T_DEF_TRISTATE:
  1016. stmt.type = TRISTATE
  1017. if len(tokens) > 1:
  1018. new_def_exprs.append(parse_val_and_cond(tokens, line, filename, linenr))
  1019. elif t0 == T_OPTIONAL:
  1020. if not isinstance(stmt, Choice):
  1021. _parse_error(line,
  1022. '"optional" is only valid for choices.',
  1023. filename,
  1024. linenr)
  1025. stmt.optional = True
  1026. elif t0 == T_OPTION:
  1027. if tokens.check(T_ENV) and tokens.check(T_EQUAL):
  1028. env_var = tokens.get_next()
  1029. stmt.is_special_ = True
  1030. stmt.is_from_env = True
  1031. if env_var not in os.environ:
  1032. self._warn("""
  1033. The symbol {0} references the non-existent environment variable {1} and will
  1034. get the empty string as its value.
  1035. If you're using kconfiglib via 'make (i)scriptconfig' it should have set up the
  1036. environment correctly for you. If you still got this message, that might be an
  1037. error, and you should e-mail kconfiglib@gmail.com.
  1038. .""" .format(stmt.name, env_var),
  1039. filename,
  1040. linenr)
  1041. stmt.cached_value = ""
  1042. else:
  1043. stmt.cached_value = os.environ[env_var]
  1044. elif tokens.check(T_DEFCONFIG_LIST):
  1045. self.defconfig_sym = stmt
  1046. elif tokens.check(T_MODULES):
  1047. self._warn("the 'modules' option is not supported. "
  1048. "Let me know if this is a problem for you; "
  1049. "it shouldn't be that hard to implement.",
  1050. filename,
  1051. linenr)
  1052. else:
  1053. _parse_error(line, "unrecognized option.", filename, linenr)
  1054. else:
  1055. # See comment in Config.__init__()
  1056. self.end_line = line
  1057. self.end_line_tokens = tokens
  1058. break
  1059. # Propagate dependencies from enclosing menus and if's.
  1060. # For menus and comments..
  1061. if isinstance(stmt, (Menu, Comment)):
  1062. stmt.orig_deps = stmt.dep_expr
  1063. stmt.deps_from_containing = deps
  1064. stmt.dep_expr = _make_and(stmt.dep_expr, deps)
  1065. stmt.all_referenced_syms = \
  1066. stmt.referenced_syms | _get_expr_syms(deps)
  1067. # For symbols and choices..
  1068. else:
  1069. # See comment for 'menu_dep'
  1070. stmt.menu_dep = depends_on_expr
  1071. # Propagate dependencies specified with 'depends on' to any new
  1072. # default expressions, prompts, and selections. ("New" since a
  1073. # symbol might be defined in multiple places and the dependencies
  1074. # should only apply to the local definition.)
  1075. new_def_exprs = [(val_expr, _make_and(cond_expr, depends_on_expr))
  1076. for (val_expr, cond_expr) in new_def_exprs]
  1077. new_selects = [(target, _make_and(cond_expr, depends_on_expr))
  1078. for (target, cond_expr) in new_selects]
  1079. if new_prompt is not None:
  1080. prompt, cond_expr = new_prompt
  1081. # 'visible if' dependencies from enclosing menus get propagated
  1082. # to prompts
  1083. if visible_if_deps is not None:
  1084. cond_expr = _make_and(cond_expr, visible_if_deps)
  1085. new_prompt = (prompt, _make_and(cond_expr, depends_on_expr))
  1086. # We save the original expressions -- before any menu and if
  1087. # conditions have been propagated -- so these can be retrieved
  1088. # later.
  1089. stmt.orig_def_exprs.extend(new_def_exprs)
  1090. if new_prompt is not None:
  1091. stmt.orig_prompts.append(new_prompt)
  1092. # Only symbols can select
  1093. if isinstance(stmt, Symbol):
  1094. stmt.orig_selects.extend(new_selects)
  1095. # Save dependencies from enclosing menus and if's
  1096. stmt.deps_from_containing = deps
  1097. # The set of symbols referenced directly by the symbol/choice plus
  1098. # all symbols referenced by enclosing menus and if's.
  1099. stmt.all_referenced_syms = \
  1100. stmt.referenced_syms | _get_expr_syms(deps)
  1101. # Propagate dependencies from enclosing menus and if's
  1102. stmt.def_exprs.extend([(val_expr, _make_and(cond_expr, deps))
  1103. for (val_expr, cond_expr) in new_def_exprs])
  1104. for (target, cond) in new_selects:
  1105. target.rev_dep = _make_or(target.rev_dep,
  1106. _make_and(stmt,
  1107. _make_and(cond, deps)))
  1108. if new_prompt is not None:
  1109. prompt, cond_expr = new_prompt
  1110. stmt.prompts.append((prompt, _make_and(cond_expr, deps)))
  1111. #
  1112. # Symbol table manipulation
  1113. #
  1114. def _sym_lookup(self, name, add_sym_if_not_exists = True):
  1115. """Fetches the symbol 'name' from the symbol table, optionally adding
  1116. it if it does not exist (this is usually what we want)."""
  1117. if name in self.syms:
  1118. return self.syms[name]
  1119. new_sym = Symbol()
  1120. new_sym.config = self
  1121. new_sym.name = name
  1122. if add_sym_if_not_exists:
  1123. self.syms[name] = new_sym
  1124. else:
  1125. # This warning is generated while evaluating an expression
  1126. # containing undefined symbols using Config.eval()
  1127. self._warn("no symbol {0} in configuration".format(name))
  1128. return new_sym
  1129. #
  1130. # Evaluation of symbols and expressions
  1131. #
  1132. def _eval_expr(self, expr):
  1133. """Evaluates an expression and returns one of the tristate values "n",
  1134. "m" or "y"."""
  1135. res = self._eval_expr_2(expr)
  1136. # Promote "m" to "y" if we're running without modules. Internally, "m"
  1137. # is often rewritten to "m" && MODULES by both the C implementation and
  1138. # kconfiglib, which takes care of cases where "m" should be false if
  1139. # we're running without modules.
  1140. if res == "m" and not self._has_modules():
  1141. return "y"
  1142. return res
  1143. def _eval_expr_2(self, expr):
  1144. if expr is None:
  1145. return "y"
  1146. if isinstance(expr, Symbol):
  1147. # Non-bool/tristate symbols are always "n" in a tristate sense,
  1148. # regardless of their value
  1149. if expr.type != BOOL and expr.type != TRISTATE:
  1150. return "n"
  1151. return expr.get_value()
  1152. if isinstance(expr, str):
  1153. return expr if (expr == "y" or expr == "m") else "n"
  1154. first_expr = expr[0]
  1155. if first_expr == OR:
  1156. res = "n"
  1157. for subexpr in expr[1]:
  1158. ev = self._eval_expr_2(subexpr)
  1159. # Return immediately upon discovering a "y" term
  1160. if ev == "y":
  1161. return "y"
  1162. if ev == "m":
  1163. res = "m"
  1164. # 'res' is either "n" or "m" here; we already handled the
  1165. # short-circuiting "y" case in the loop.
  1166. return res
  1167. if first_expr == AND:
  1168. res = "y"
  1169. for subexpr in expr[1]:
  1170. ev = self._eval_expr_2(subexpr)
  1171. # Return immediately upon discovering an "n" term
  1172. if ev == "n":
  1173. return "n"
  1174. if ev == "m":
  1175. res = "m"
  1176. # 'res' is either "m" or "y" here; we already handled the
  1177. # short-circuiting "n" case in the loop.
  1178. return res
  1179. if first_expr == NOT:
  1180. ev = self._eval_expr_2(expr[1])
  1181. if ev == "y":
  1182. return "n"
  1183. return "y" if (ev == "n") else "m"
  1184. if first_expr == EQUAL:
  1185. return "y" if (self._get_str_value(expr[1]) ==
  1186. self._get_str_value(expr[2])) else "n"
  1187. if first_expr == UNEQUAL:
  1188. return "y" if (self._get_str_value(expr[1]) !=
  1189. self._get_str_value(expr[2])) else "n"
  1190. _internal_error("Internal error while evaluating expression: "
  1191. "unknown operation {0}.".format(first_expr))
  1192. def _get_str_value(self, obj):
  1193. if isinstance(obj, str):
  1194. return obj
  1195. # obj is a Symbol
  1196. return obj.get_value()
  1197. def _eval_min(self, e1, e2):
  1198. e1_eval = self._eval_expr(e1)
  1199. e2_eval = self._eval_expr(e2)
  1200. return e1_eval if tri_less(e1_eval, e2_eval) else e2_eval
  1201. def _eval_max(self, e1, e2):
  1202. e1_eval = self._eval_expr(e1)
  1203. e2_eval = self._eval_expr(e2)
  1204. return e1_eval if tri_greater(e1_eval, e2_eval) else e2_eval
  1205. #
  1206. # Methods related to the MODULES symbol
  1207. #
  1208. def _has_modules(self):
  1209. modules_sym = self.syms.get("MODULES")
  1210. return (modules_sym is not None) and (modules_sym.get_value() == "y")
  1211. #
  1212. # Dependency tracking
  1213. #
  1214. def _build_dep(self):
  1215. """Populates the Symbol.dep sets, linking the symbol to the symbols
  1216. that immediately depend on it in the sense that changing the value of
  1217. the symbol might affect the values of those other symbols. This is used
  1218. for caching/invalidation purposes. The calculated sets might be larger
  1219. than necessary as we don't do any complicated analysis of the
  1220. expressions."""
  1221. for sym in self.syms.itervalues():
  1222. sym.dep = set()
  1223. # Adds 'sym' as a directly dependent symbol to all symbols that appear
  1224. # in the expression 'e'
  1225. def add_expr_deps(e, sym):
  1226. for s in _get_expr_syms(e):
  1227. s.dep.add(sym)
  1228. # The directly dependent symbols of a symbol are:
  1229. # - Any symbols whose prompts, default values, rev_dep (select
  1230. # condition), or ranges depend on the symbol
  1231. # - Any symbols that belong to the same choice statement as the symbol
  1232. # (these won't be included in 'dep' as that makes the dependency
  1233. # graph unwieldy, but Symbol._get_dependent() will include them)
  1234. # - Any symbols in a choice statement that depends on the symbol
  1235. for sym in self.syms.itervalues():
  1236. for (_, e) in sym.prompts:
  1237. add_expr_deps(e, sym)
  1238. for (v, e) in sym.def_exprs:
  1239. add_expr_deps(v, sym)
  1240. add_expr_deps(e, sym)
  1241. add_expr_deps(sym.rev_dep, sym)
  1242. for (l, u, e) in sym.ranges:
  1243. add_expr_deps(l, sym)
  1244. add_expr_deps(u, sym)
  1245. add_expr_deps(e, sym)
  1246. if sym.is_choice_symbol_:
  1247. choice = sym.parent
  1248. for (_, e) in choice.prompts:
  1249. add_expr_deps(e, sym)
  1250. for (_, e) in choice.def_exprs:
  1251. add_expr_deps(e, sym)
  1252. def _expr_val_str(self, expr, no_value_str = "(none)", get_val_instead_of_eval = False):
  1253. # Since values are valid expressions, _expr_to_str() will get a nice
  1254. # string representation for those as well.
  1255. if expr is None:
  1256. return no_value_str
  1257. if get_val_instead_of_eval:
  1258. if isinstance(expr, str):
  1259. return _expr_to_str(expr)
  1260. val = expr.get_value()
  1261. else:
  1262. val = self._eval_expr(expr)
  1263. return "{0} (value: {1})".format(_expr_to_str(expr), _expr_to_str(val))
  1264. def _expand_sym_refs(self, s):
  1265. """Expands $-references to symbols in 's' to symbol values, or to the
  1266. empty string for undefined symbols."""
  1267. while 1:
  1268. sym_ref_re_match = sym_ref_re.search(s)
  1269. if sym_ref_re_match is None:
  1270. return s
  1271. sym_name = sym_ref_re_match.group(0)[1:]
  1272. sym = self.syms.get(sym_name)
  1273. expansion = "" if sym is None else sym.get_value()
  1274. s = s[:sym_ref_re_match.start()] + \
  1275. expansion + \
  1276. s[sym_ref_re_match.end():]
  1277. def _get_sym_or_choice_str(self, sc):
  1278. """Symbols and choices have many properties in common, so we factor out
  1279. common __str__() stuff here. "sc" is short for "symbol or choice"."""
  1280. # As we deal a lot with string representations here, use some
  1281. # convenient shorthand:
  1282. s = _expr_to_str
  1283. #
  1284. # Common symbol/choice properties
  1285. #
  1286. user_value_str = "(no user value)" if sc.user_val is None else s(sc.user_val)
  1287. visibility_str = s(sc.get_visibility())
  1288. # Build prompts string
  1289. if sc.prompts == []:
  1290. prompts_str = " (no prompts)"
  1291. else:
  1292. prompts_str_rows = []
  1293. for (prompt, cond_expr) in sc.orig_prompts:
  1294. if cond_expr is None:
  1295. prompts_str_rows.append(' "{0}"'.format(prompt))
  1296. else:
  1297. prompts_str_rows.append(' "{0}" if '.format(prompt) +
  1298. self._expr_val_str(cond_expr))
  1299. prompts_str = "\n".join(prompts_str_rows)
  1300. # Build locations string
  1301. if sc.def_locations == []:
  1302. locations_str = "(no locations)"
  1303. else:
  1304. locations_str = " ".join(["{0}:{1}".format(filename, linenr) for
  1305. (filename, linenr) in sc.def_locations])
  1306. # Build additional-dependencies-from-menus-and-if's string
  1307. additional_deps_str = " " + self._expr_val_str(sc.deps_from_containing,
  1308. "(no additional dependencies)")
  1309. #
  1310. # Symbol-specific stuff
  1311. #
  1312. if isinstance(sc, Symbol):
  1313. # Build value string
  1314. value_str = s(sc.get_value())
  1315. # Build ranges string
  1316. if isinstance(sc, Symbol):
  1317. if sc.ranges == []:
  1318. ranges_str = " (no ranges)"
  1319. else:
  1320. ranges_str_rows = []
  1321. for (l, u, cond_expr) in sc.ranges:
  1322. if cond_expr is None:
  1323. ranges_str_rows.append(" [{0}, {1}]".format(s(l), s(u)))
  1324. else:
  1325. ranges_str_rows.append(" [{0}, {1}] if {2}"
  1326. .format(s(l), s(u), self._expr_val_str(cond_expr)))
  1327. ranges_str = "\n".join(ranges_str_rows)
  1328. # Build default values string
  1329. if sc.def_exprs == []:
  1330. defaults_str = " (no default values)"
  1331. else:
  1332. defaults_str_rows = []
  1333. for (val_expr, cond_expr) in sc.orig_def_exprs:
  1334. row_str = " " + self._expr_val_str(val_expr, "(none)", sc.type == STRING)
  1335. defaults_str_rows.append(row_str)
  1336. defaults_str_rows.append(" Condition: " + self._expr_val_str(cond_expr))
  1337. defaults_str = "\n".join(defaults_str_rows)
  1338. # Build selects string
  1339. if sc.orig_selects == []:
  1340. selects_str = " (no selects)"
  1341. else:
  1342. selects_str_rows = []
  1343. for (target, cond_expr) in sc.orig_selects:
  1344. if cond_expr is None:
  1345. selects_str_rows.append(" {0}".format(target.name))
  1346. else:
  1347. selects_str_rows.append(" {0} if ".format(target.name) +
  1348. self._expr_val_str(cond_expr))
  1349. selects_str = "\n".join(selects_str_rows)
  1350. # Build reverse dependencies string
  1351. if sc.rev_dep == "n":
  1352. rev_dep_str = " (no reverse dependencies)"
  1353. else:
  1354. rev_dep_str = " " + self._expr_val_str(sc.rev_dep)
  1355. res = _sep_lines("Symbol " + (sc.name if sc.name is not None else "(no name)"),
  1356. "Type : " + typename[sc.type],
  1357. "Value : " + value_str,
  1358. "User value : " + user_value_str,
  1359. "Visibility : " + visibility_str,
  1360. "Is choice item : " + bool_str[sc.is_choice_symbol_],
  1361. "Is defined : " + bool_str[sc.is_defined_],
  1362. "Is from env. : " + bool_str[sc.is_from_env],
  1363. "Is special : " + bool_str[sc.is_special_] + "\n")
  1364. if sc.ranges != []:
  1365. res += _sep_lines("Ranges:",
  1366. ranges_str + "\n")
  1367. res += _sep_lines("Prompts:",
  1368. prompts_str,
  1369. "Default values:",
  1370. defaults_str,
  1371. "Selects:",
  1372. selects_str,
  1373. "Reverse dependencies:",
  1374. rev_dep_str,
  1375. "Additional dependencies from enclosing menus and if's:",
  1376. additional_deps_str,
  1377. "Locations: " + locations_str)
  1378. return res
  1379. #
  1380. # Choice-specific stuff
  1381. #
  1382. # Build name string (for named choices)
  1383. if sc.name is None:
  1384. name_str = "(no name)"
  1385. else:
  1386. name_str = sc.name
  1387. # Build selected symbol string
  1388. sel = sc.get_selection()
  1389. if sel is None:
  1390. sel_str = "(no selection)"
  1391. else:
  1392. sel_str = sel.name
  1393. # Build mode string
  1394. mode_str = s(sc.get_mode())
  1395. # Build default values string
  1396. if sc.def_exprs == []:
  1397. defaults_str = " (no default values)"
  1398. else:
  1399. defaults_str_rows = []
  1400. for (sym, cond_expr) in sc.orig_def_exprs:
  1401. if cond_expr is None:
  1402. defaults_str_rows.append(" {0}".format(sym.name))
  1403. else:
  1404. defaults_str_rows.append(" {0} if ".format(sym.name) +
  1405. self._expr_val_str(cond_expr))
  1406. defaults_str = "\n".join(defaults_str_rows)
  1407. # Build contained symbols string
  1408. names = [sym.name for sym in sc.get_symbols()]
  1409. if names == []:
  1410. syms_string = "(empty)"
  1411. else:
  1412. syms_string = " ".join(names)
  1413. return _sep_lines("Choice",
  1414. "Name (for named choices): " + name_str,
  1415. "Type : " + typename[sc.type],
  1416. "Selected symbol : " + sel_str,
  1417. "User value : " + user_value_str,
  1418. "Mode : " + mode_str,
  1419. "Visibility : " + visibility_str,
  1420. "Optional : " + bool_str[sc.optional],
  1421. "Prompts:",
  1422. prompts_str,
  1423. "Defaults:",
  1424. defaults_str,
  1425. "Choice symbols:",
  1426. " " + syms_string,
  1427. "Additional dependencies from enclosing menus and if's:",
  1428. additional_deps_str,
  1429. "Locations: " + locations_str)
  1430. def _expr_depends_on(self, expr, sym):
  1431. """Reimplementation of expr_depends_symbol() from mconf.c. Used to
  1432. determine if a submenu should be implicitly created, which influences what
  1433. items inside choice statements are considered choice items."""
  1434. if expr is None:
  1435. return False
  1436. def rec(expr):
  1437. if isinstance(expr, str):
  1438. return False
  1439. if isinstance(expr, Symbol):
  1440. return expr is sym
  1441. e0 = expr[0]
  1442. if e0 == EQUAL or e0 == UNEQUAL:
  1443. return self._eq_to_sym(expr) is sym
  1444. if e0 == AND:
  1445. for and_expr in expr[1]:
  1446. if rec(and_expr):
  1447. return True
  1448. return False
  1449. return rec(expr)
  1450. def _eq_to_sym(self, eq):
  1451. """_expr_depends_on() helper. For (in)equalities of the form sym = y/m
  1452. or sym != n, returns sym. For other (in)equalities, returns None."""
  1453. relation, left, right = eq
  1454. left = self._transform_n_m_y(left)
  1455. right = self._transform_n_m_y(right)
  1456. # Make sure the symbol (if any) appears to the left
  1457. if not isinstance(left, Symbol):
  1458. left, right = right, left
  1459. if not isinstance(left, Symbol):
  1460. return None
  1461. if (relation == EQUAL and (right == "m" or right == "y")) or \
  1462. (relation == UNEQUAL and right == "n"):
  1463. return left
  1464. return None
  1465. def _transform_n_m_y(self, item):
  1466. """_eq_to_sym() helper. Translates the symbols n, m, and y to their
  1467. string equivalents."""
  1468. if item is self.n:
  1469. return "n"
  1470. if item is self.m:
  1471. return "m"
  1472. if item is self.y:
  1473. return "y"
  1474. return item
  1475. def _warn(self, msg, filename = None, linenr = None):
  1476. """For printing warnings to stderr."""
  1477. if self.print_warnings:
  1478. self._warn_or_undef_assign(msg, WARNING, filename, linenr)
  1479. def _undef_assign(self, msg, filename = None, linenr = None):
  1480. """For printing informational messages related to assignments
  1481. to undefined variables to stderr."""
  1482. if self.print_undef_assign:
  1483. self._warn_or_undef_assign(msg, UNDEF_ASSIGN, filename, linenr)
  1484. def _warn_or_undef_assign(self, msg, msg_type, filename, linenr):
  1485. if filename is not None:
  1486. sys.stderr.write("{0}:".format(_clean_up_path(filename)))
  1487. if linenr is not None:
  1488. sys.stderr.write("{0}:".format(linenr))
  1489. if msg_type == WARNING:
  1490. sys.stderr.write("warning: ")
  1491. elif msg_type == UNDEF_ASSIGN:
  1492. sys.stderr.write("info: ")
  1493. else:
  1494. _internal_error('Internal error while printing warning: unknown warning type "{0}".'
  1495. .format(msg_type))
  1496. sys.stderr.write(msg + "\n")
  1497. def _get_expr_syms(expr):
  1498. """Returns the set() of symbols appearing in expr."""
  1499. res = set()
  1500. if expr is None:
  1501. return res
  1502. def rec(expr):
  1503. if isinstance(expr, Symbol):
  1504. res.add(expr)
  1505. return
  1506. if isinstance(expr, str):
  1507. return
  1508. e0 = expr[0]
  1509. if e0 == OR or e0 == AND:
  1510. for term in expr[1]:
  1511. rec(term)
  1512. elif e0 == NOT:
  1513. rec(expr[1])
  1514. elif e0 == EQUAL or e0 == UNEQUAL:
  1515. _, v1, v2 = expr
  1516. if isinstance(v1, Symbol):
  1517. res.add(v1)
  1518. if isinstance(v2, Symbol):
  1519. res.add(v2)
  1520. else:
  1521. _internal_error("Internal error while fetching symbols from an "
  1522. "expression with token stream {0}.".format(expr))
  1523. rec(expr)
  1524. return res
  1525. #
  1526. # Construction of expressions
  1527. #
  1528. # These functions as well as the _eval_min/max() functions above equate
  1529. # None with "y", which is usually what we want, but needs to be kept in
  1530. # mind.
  1531. def _make_or(e1, e2):
  1532. # Perform trivial simplification and avoid None's (which
  1533. # correspond to y's)
  1534. if e1 is None or e2 is None or \
  1535. e1 == "y" or e2 == "y":
  1536. return "y"
  1537. if e1 == "n":
  1538. return e2
  1539. if e2 == "n":
  1540. return e1
  1541. # Prefer to merge/update argument list if possible instead of creating
  1542. # a new OR node
  1543. if isinstance(e1, tuple) and e1[0] == OR:
  1544. if isinstance(e2, tuple) and e2[0] == OR:
  1545. return (OR, e1[1] + e2[1])
  1546. return (OR, e1[1] + [e2])
  1547. if isinstance(e2, tuple) and e2[0] == OR:
  1548. return (OR, e2[1] + [e1])
  1549. return (OR, [e1, e2])
  1550. # Note: returns None if e1 == e2 == None
  1551. def _make_and(e1, e2):
  1552. if e1 == "n" or e2 == "n":
  1553. return "n"
  1554. if e1 is None or e1 == "y":
  1555. return e2
  1556. if e2 is None or e2 == "y":
  1557. return e1
  1558. # Prefer to merge/update argument list if possible instead of creating
  1559. # a new AND node
  1560. if isinstance(e1, tuple) and e1[0] == AND:
  1561. if isinstance(e2, tuple) and e2[0] == AND:
  1562. return (AND, e1[1] + e2[1])
  1563. return (AND, e1[1] + [e2])
  1564. if isinstance(e2, tuple) and e2[0] == AND:
  1565. return (AND, e2[1] + [e1])
  1566. return (AND, [e1, e2])
  1567. #
  1568. # Constants and functions related to types, parsing, evaluation and printing,
  1569. # put globally to unclutter the Config class a bit.
  1570. #
  1571. # Tokens
  1572. (T_OR, T_AND, T_NOT,
  1573. T_OPEN_PAREN, T_CLOSE_PAREN,
  1574. T_EQUAL, T_UNEQUAL,
  1575. T_MAINMENU, T_MENU, T_ENDMENU,
  1576. T_SOURCE, T_CHOICE, T_ENDCHOICE,
  1577. T_COMMENT, T_CONFIG, T_MENUCONFIG,
  1578. T_HELP, T_IF, T_ENDIF, T_DEPENDS, T_ON,
  1579. T_OPTIONAL, T_PROMPT, T_DEFAULT,
  1580. T_BOOL, T_TRISTATE, T_HEX, T_INT, T_STRING,
  1581. T_DEF_BOOL, T_DEF_TRISTATE,
  1582. T_SELECT, T_RANGE, T_OPTION, T_ENV,
  1583. T_DEFCONFIG_LIST, T_MODULES, T_VISIBLE) = range(0, 38)
  1584. # Keyword to token map
  1585. keywords = {
  1586. "mainmenu" : T_MAINMENU,
  1587. "menu" : T_MENU,
  1588. "endmenu" : T_ENDMENU,
  1589. "endif" : T_ENDIF,
  1590. "endchoice" : T_ENDCHOICE,
  1591. "source" : T_SOURCE,
  1592. "choice" : T_CHOICE,
  1593. "config" : T_CONFIG,
  1594. "comment" : T_COMMENT,
  1595. "menuconfig" : T_MENUCONFIG,
  1596. "help" : T_HELP,
  1597. "if" : T_IF,
  1598. "depends" : T_DEPENDS,
  1599. "on" : T_ON,
  1600. "optional" : T_OPTIONAL,
  1601. "prompt" : T_PROMPT,
  1602. "default" : T_DEFAULT,
  1603. "bool" : T_BOOL,
  1604. "boolean" : T_BOOL,
  1605. "tristate" : T_TRISTATE,
  1606. "int" : T_INT,
  1607. "hex" : T_HEX,
  1608. "def_bool" : T_DEF_BOOL,
  1609. "def_tristate" : T_DEF_TRISTATE,
  1610. "string" : T_STRING,
  1611. "select" : T_SELECT,
  1612. "range" : T_RANGE,
  1613. "option" : T_OPTION,
  1614. "env" : T_ENV,
  1615. "defconfig_list" : T_DEFCONFIG_LIST,
  1616. "modules" : T_MODULES,
  1617. "visible" : T_VISIBLE }
  1618. # Strings to use for True and False
  1619. bool_str = { False : "false", True : "true" }
  1620. # Tokens after which identifier-like lexemes are treated as strings. T_CHOICE
  1621. # is included to avoid symbols being registered for named choices.
  1622. string_lex = frozenset((T_BOOL, T_TRISTATE, T_INT, T_HEX, T_STRING, T_CHOICE,
  1623. T_PROMPT, T_MENU, T_COMMENT, T_SOURCE, T_MAINMENU))
  1624. # Matches the initial token on a line; see _tokenize().
  1625. initial_token_re = re.compile(r"[^\w]*(\w+)")
  1626. # Matches an identifier/keyword optionally preceded by whitespace
  1627. id_keyword_re = re.compile(r"\s*([\w./-]+)")
  1628. # Regular expressions for parsing .config files
  1629. set_re = re.compile(r"CONFIG_(\w+)=(.*)")
  1630. unset_re = re.compile(r"# CONFIG_(\w+) is not set")
  1631. # Regular expression for finding $-references to symbols in strings
  1632. sym_ref_re = re.compile(r"\$[A-Za-z_]+")
  1633. # Integers representing symbol types
  1634. UNKNOWN, BOOL, TRISTATE, STRING, HEX, INT = range(0, 6)
  1635. # Strings to use for types
  1636. typename = {
  1637. UNKNOWN : "unknown",
  1638. BOOL : "bool",
  1639. TRISTATE : "tristate",
  1640. STRING : "string",
  1641. HEX : "hex",
  1642. INT : "int" }
  1643. # Token to type mapping
  1644. token_to_type = { T_BOOL : BOOL,
  1645. T_TRISTATE : TRISTATE,
  1646. T_STRING : STRING,
  1647. T_INT : INT,
  1648. T_HEX : HEX }
  1649. # Default values for symbols of different types (the value the symbol gets if
  1650. # it is not assigned a user value and none of its 'default' clauses kick in)
  1651. default_value = { BOOL : "n",
  1652. TRISTATE : "n",
  1653. STRING : "",
  1654. INT : "",
  1655. HEX : "" }
  1656. # Indicates that no item is selected in a choice statement
  1657. NO_SELECTION = 0
  1658. # Integers representing expression types
  1659. OR, AND, NOT, EQUAL, UNEQUAL = range(0, 5)
  1660. # Map from tristate values to integers
  1661. tri_to_int = { "n" : 0, "m" : 1, "y" : 2 }
  1662. # Printing-related stuff
  1663. op_to_str = { AND : " && ",
  1664. OR : " || ",
  1665. EQUAL : " = ",
  1666. UNEQUAL : " != " }
  1667. precedence = { OR : 0, AND : 1, NOT : 2 }
  1668. # Types of informational messages
  1669. WARNING = 0
  1670. UNDEF_ASSIGN = 1
  1671. def _intersperse(lst, op):
  1672. """_expr_to_str() helper. Gets the string representation of each expression in lst
  1673. and produces a list where op has been inserted between the elements."""
  1674. if lst == []:
  1675. return ""
  1676. res = []
  1677. def handle_sub_expr(expr):
  1678. no_parens = isinstance(expr, (str, Symbol)) or \
  1679. expr[0] in (EQUAL, UNEQUAL) or \
  1680. precedence[op] <= precedence[expr[0]]
  1681. if not no_parens:
  1682. res.append("(")
  1683. res.extend(_expr_to_str_rec(expr))
  1684. if not no_parens:
  1685. res.append(")")
  1686. op_str = op_to_str[op]
  1687. handle_sub_expr(lst[0])
  1688. for expr in lst[1:]:
  1689. res.append(op_str)
  1690. handle_sub_expr(expr)
  1691. return res
  1692. def _expr_to_str(expr):
  1693. s = "".join(_expr_to_str_rec(expr))
  1694. return s
  1695. def _sym_str_string(sym_or_str):
  1696. if isinstance(sym_or_str, str):
  1697. return '"{0}"'.format(sym_or_str)
  1698. return sym_or_str.name
  1699. def _expr_to_str_rec(expr):
  1700. if expr is None:
  1701. return [""]
  1702. if isinstance(expr, (Symbol, str)):
  1703. return [_sym_str_string(expr)]
  1704. e0 = expr[0]
  1705. if e0 == OR or e0 == AND:
  1706. return _intersperse(expr[1], expr[0])
  1707. if e0 == NOT:
  1708. need_parens = not isinstance(expr[1], (str, Symbol))
  1709. res = ["!"]
  1710. if need_parens:
  1711. res.append("(")
  1712. res.extend(_expr_to_str_rec(expr[1]))
  1713. if need_parens:
  1714. res.append(")")
  1715. return res
  1716. if e0 == EQUAL or e0 == UNEQUAL:
  1717. return [_sym_str_string(expr[1]),
  1718. op_to_str[expr[0]],
  1719. _sym_str_string(expr[2])]
  1720. class _Block:
  1721. """Represents a list of items (symbols, menus, choice statements and
  1722. comments) appearing at the top-level of a file or witin a menu, choice or
  1723. if statement."""
  1724. def __init__(self):
  1725. self.items = []
  1726. def get_items(self):
  1727. return self.items
  1728. def add_item(self, item):
  1729. self.items.append(item)
  1730. def _make_conf(self):
  1731. # Collect the substrings in a list and later use join() instead of +=
  1732. # to build the final .config contents. With older Python versions, this
  1733. # yields linear instead of quadratic complexity.
  1734. strings = []
  1735. for item in self.items:
  1736. strings.extend(item._make_conf())
  1737. return strings
  1738. def add_depend_expr(self, expr):
  1739. for item in self.items:
  1740. item.add_depend_expr(expr)
  1741. class Item():
  1742. """Base class for symbols and other Kconfig constructs. Subclasses are
  1743. Symbol, Choice, Menu, and Comment."""
  1744. def is_symbol(self):
  1745. """Returns True if the item is a symbol, otherwise False. Short for
  1746. isinstance(item, kconfiglib.Symbol)."""
  1747. return isinstance(self, Symbol)
  1748. def is_choice(self):
  1749. """Returns True if the item is a choice, otherwise False. Short for
  1750. isinstance(item, kconfiglib.Choice)."""
  1751. return isinstance(self, Choice)
  1752. def is_menu(self):
  1753. """Returns True if the item is a menu, otherwise False. Short for
  1754. isinstance(item, kconfiglib.Menu)."""
  1755. return isinstance(self, Menu)
  1756. def is_comment(self):
  1757. """Returns True if the item is a comment, otherwise False. Short for
  1758. isinstance(item, kconfiglib.Comment)."""
  1759. return isinstance(self, Comment)
  1760. class _HasVisibility():
  1761. """Base class for elements that have a "visibility" that acts as an upper
  1762. limit on the values a user can set for them. Subclasses are Symbol and
  1763. Choice (which supply some of the attributes)."""
  1764. def __init__(self):
  1765. self.cached_visibility = None
  1766. self.prompts = []
  1767. def _invalidate(self):
  1768. self.cached_visibility = None
  1769. def _get_visibility(self):
  1770. if self.cached_visibility is None:
  1771. vis = "n"
  1772. for (prompt, cond_expr) in self.prompts:
  1773. vis = self.config._eval_max(vis, cond_expr)
  1774. if isinstance(self, Symbol) and self.is_choice_symbol_:
  1775. vis = self.config._eval_min(vis, self.parent._get_visibility())
  1776. # Promote "m" to "y" if we're dealing with a non-tristate
  1777. if vis == "m" and self.type != TRISTATE:
  1778. vis = "y"
  1779. self.cached_visibility = vis
  1780. return self.cached_visibility
  1781. class Symbol(Item, _HasVisibility):
  1782. """Represents a configuration symbol - e.g. FOO for
  1783. config FOO
  1784. ..."""
  1785. #
  1786. # Public interface
  1787. #
  1788. def get_value(self):
  1789. """Calculate and return the value of the symbol. See also
  1790. Symbol.set_user_value()."""
  1791. if self.cached_value is not None:
  1792. return self.cached_value
  1793. self.write_to_conf = False
  1794. # As a quirk of Kconfig, undefined symbols get their name as their
  1795. # value. This is why things like "FOO = bar" work for seeing if FOO has
  1796. # the value "bar".
  1797. if self.type == UNKNOWN:
  1798. self.cached_value = self.name
  1799. return self.name
  1800. new_val = default_value[self.type]
  1801. vis = self._get_visibility()
  1802. if self.type == BOOL or self.type == TRISTATE:
  1803. # The visibility and mode (modules-only or single-selection) of
  1804. # choice items will be taken into account in self._get_visibility()
  1805. if self.is_choice_symbol_:
  1806. if vis != "n":
  1807. choice = self.parent
  1808. mode = choice.get_mode()
  1809. self.write_to_conf = (mode != "n")
  1810. if mode == "y":
  1811. new_val = "y" if (choice.get_selection() is self) else "n"
  1812. elif mode == "m":
  1813. if self.user_val == "m" or self.user_val == "y":
  1814. new_val = "m"
  1815. else:
  1816. use_defaults = True
  1817. if vis != "n":
  1818. # If the symbol is visible and has a user value, use that.
  1819. # Otherwise, look at defaults.
  1820. self.write_to_conf = True
  1821. if self.user_val is not None:
  1822. new_val = self.config._eval_min(self.user_val, vis)
  1823. use_defaults = False
  1824. if use_defaults:
  1825. for (val_expr, cond_expr) in self.def_exprs:
  1826. cond_eval = self.config._eval_expr(cond_expr)
  1827. if cond_eval != "n":
  1828. self.write_to_conf = True
  1829. new_val = self.config._eval_min(val_expr, cond_eval)
  1830. break
  1831. # Reverse dependencies take precedence
  1832. rev_dep_val = self.config._eval_expr(self.rev_dep)
  1833. if rev_dep_val != "n":
  1834. self.write_to_conf = True
  1835. new_val = self.config._eval_max(new_val, rev_dep_val)
  1836. # Promote "m" to "y" for booleans
  1837. if new_val == "m" and self.type == BOOL:
  1838. new_val = "y"
  1839. elif self.type == STRING:
  1840. use_defaults = True
  1841. if vis != "n":
  1842. self.write_to_conf = True
  1843. if self.user_val is not None:
  1844. new_val = self.user_val
  1845. use_defaults = False
  1846. if use_defaults:
  1847. for (val_expr, cond_expr) in self.def_exprs:
  1848. if self.config._eval_expr(cond_expr) != "n":
  1849. self.write_to_conf = True
  1850. new_val = self.config._get_str_value(val_expr)
  1851. break
  1852. elif self.type == HEX or self.type == INT:
  1853. has_active_range = False
  1854. low = None
  1855. high = None
  1856. use_defaults = True
  1857. base = 16 if self.type == HEX else 10
  1858. for(l, h, cond_expr) in self.ranges:
  1859. if self.config._eval_expr(cond_expr) != "n":
  1860. has_active_range = True
  1861. low_str = self.config._get_str_value(l)
  1862. high_str = self.config._get_str_value(h)
  1863. low = int(low_str, base) if \
  1864. _is_base_n(low_str, base) else 0
  1865. high = int(high_str, base) if \
  1866. _is_base_n(high_str, base) else 0
  1867. break
  1868. if vis != "n":
  1869. self.write_to_conf = True
  1870. if self.user_val is not None and \
  1871. _is_base_n(self.user_val, base) and \
  1872. (not has_active_range or
  1873. low <= int(self.user_val, base) <= high):
  1874. # If the user value is OK, it is stored in exactly the same
  1875. # form as specified in the assignment (with or without
  1876. # "0x", etc).
  1877. use_defaults = False
  1878. new_val = self.user_val
  1879. if use_defaults:
  1880. for (val_expr, cond_expr) in self.def_exprs:
  1881. if self.config._eval_expr(cond_expr) != "n":
  1882. self.write_to_conf = True
  1883. # If the default value is OK, it is stored in exactly
  1884. # the same form as specified. Otherwise, it is clamped
  1885. # to the range, and the output has "0x" as appropriate
  1886. # for the type.
  1887. new_val = self.config._get_str_value(val_expr)
  1888. if _is_base_n(new_val, base):
  1889. new_val_num = int(new_val, base)
  1890. if has_active_range:
  1891. clamped_val = None
  1892. if new_val_num < low:
  1893. clamped_val = low
  1894. elif new_val_num > high:
  1895. clamped_val = high
  1896. if clamped_val is not None:
  1897. new_val = (hex(clamped_val) if \
  1898. self.type == HEX else str(clamped_val))
  1899. break
  1900. else: # For the for loop
  1901. # If no user value or default kicks in but the hex/int has
  1902. # an active range, then the low end of the range is used,
  1903. # provided it's > 0, with "0x" prepended as appropriate.
  1904. if has_active_range and low > 0:
  1905. new_val = (hex(low) if self.type == HEX else str(low))
  1906. self.cached_value = new_val
  1907. return new_val
  1908. def set_user_value(self, v):
  1909. """Sets the user value of the symbol.
  1910. Equal in effect to assigning the value to the symbol within a .config
  1911. file. Use get_lower/upper_bound() or get_assignable_values() to find
  1912. the range of currently assignable values for bool and tristate symbols;
  1913. setting values outside this range will cause the user value to differ
  1914. from the result of Symbol.get_value() (be truncated). Values that are
  1915. invalid for the type (such as a_bool.set_user_value("foo")) are
  1916. ignored, and a warning is emitted if an attempt is made to assign such
  1917. a value.
  1918. For any type of symbol, is_modifiable() can be used to check if a user
  1919. value will currently have any effect on the symbol, as determined by
  1920. its visibility and range of assignable values. Any value that is valid
  1921. for the type (bool, tristate, etc.) will end up being reflected in
  1922. get_user_value() though, and might have an effect later if conditions
  1923. change. To get rid of the user value, use unset_user_value().
  1924. Any symbols dependent on the symbol are (recursively) invalidated, so
  1925. things will just work with regards to dependencies.
  1926. v -- The user value to give to the symbol."""
  1927. self._set_user_value_no_invalidate(v, False)
  1928. # There might be something more efficient you could do here, but play
  1929. # it safe.
  1930. if self.name == "MODULES":
  1931. self.config._invalidate_all()
  1932. return
  1933. self._invalidate()
  1934. self._invalidate_dependent()
  1935. def unset_user_value(self):
  1936. """Resets the user value of the symbol, as if the symbol had never
  1937. gotten a user value via Config.load_config() or
  1938. Symbol.set_user_value()."""
  1939. self._unset_user_value_no_recursive_invalidate()
  1940. self._invalidate_dependent()
  1941. def get_user_value(self):
  1942. """Returns the value assigned to the symbol in a .config or via
  1943. Symbol.set_user_value() (provided the value was valid for the type of the
  1944. symbol). Returns None in case of no user value."""
  1945. return self.user_val
  1946. def get_name(self):
  1947. """Returns the name of the symbol."""
  1948. return self.name
  1949. def get_prompts(self):
  1950. """Returns a list of prompts defined for the symbol, in the order they
  1951. appear in the configuration files. Returns the empty list for symbols
  1952. with no prompt.
  1953. This list will have a single entry for the vast majority of symbols
  1954. having prompts, but having multiple prompts for a single symbol is
  1955. possible through having multiple 'config' entries for it."""
  1956. return [prompt for prompt, _ in self.orig_prompts]
  1957. def get_upper_bound(self):
  1958. """For string/hex/int symbols and for bool and tristate symbols that
  1959. cannot be modified (see is_modifiable()), returns None.
  1960. Otherwise, returns the highest value the symbol can be set to with
  1961. Symbol.set_user_value() (that will not be truncated): one of "m" or "y",
  1962. arranged from lowest to highest. This corresponds to the highest value
  1963. the symbol could be given in e.g. the 'make menuconfig' interface.
  1964. See also the tri_less*() and tri_greater*() functions, which could come
  1965. in handy."""
  1966. if self.type != BOOL and self.type != TRISTATE:
  1967. return None
  1968. rev_dep = self.config._eval_expr(self.rev_dep)
  1969. # A bool selected to "m" gets promoted to "y"
  1970. if self.type == BOOL and rev_dep == "m":
  1971. rev_dep = "y"
  1972. vis = self._get_visibility()
  1973. if (tri_to_int[vis] - tri_to_int[rev_dep]) > 0:
  1974. return vis
  1975. return None
  1976. def get_lower_bound(self):
  1977. """For string/hex/int symbols and for bool and tristate symbols that
  1978. cannot be modified (see is_modifiable()), returns None.
  1979. Otherwise, returns the lowest value the symbol can be set to with
  1980. Symbol.set_user_value() (that will not be truncated): one of "n" or "m",
  1981. arranged from lowest to highest. This corresponds to the lowest value
  1982. the symbol could be given in e.g. the 'make menuconfig' interface.
  1983. See also the tri_less*() and tri_greater*() functions, which could come
  1984. in handy."""
  1985. if self.type != BOOL and self.type != TRISTATE:
  1986. return None
  1987. rev_dep = self.config._eval_expr(self.rev_dep)
  1988. # A bool selected to "m" gets promoted to "y"
  1989. if self.type == BOOL and rev_dep == "m":
  1990. rev_dep = "y"
  1991. if (tri_to_int[self._get_visibility()] - tri_to_int[rev_dep]) > 0:
  1992. return rev_dep
  1993. return None
  1994. def get_assignable_values(self):
  1995. """For string/hex/int symbols and for bool and tristate symbols that
  1996. cannot be modified (see is_modifiable()), returns the empty list.
  1997. Otherwise, returns a list containing the user values that can be
  1998. assigned to the symbol (that won't be truncated). Usage example:
  1999. if "m" in sym.get_assignable_values():
  2000. sym.set_user_value("m")
  2001. This is basically a more convenient interface to
  2002. get_lower/upper_bound() when wanting to test if a particular tristate
  2003. value can be assigned."""
  2004. if self.type != BOOL and self.type != TRISTATE:
  2005. return []
  2006. rev_dep = self.config._eval_expr(self.rev_dep)
  2007. # A bool selected to "m" gets promoted to "y"
  2008. if self.type == BOOL and rev_dep == "m":
  2009. rev_dep = "y"
  2010. res = ["n", "m", "y"][tri_to_int[rev_dep] :
  2011. tri_to_int[self._get_visibility()] + 1]
  2012. return res if len(res) > 1 else []
  2013. def get_type(self):
  2014. """Returns the type of the symbol: one of UNKNOWN, BOOL, TRISTATE,
  2015. STRING, HEX, or INT. These are defined at the top level of the module,
  2016. so you'd do something like
  2017. if sym.get_type() == kconfiglib.STRING:
  2018. ..."""
  2019. return self.type
  2020. def get_visibility(self):
  2021. """Returns the visibility of the symbol: one of "n", "m" or "y". For
  2022. bool and tristate symbols, this is an upper bound on the value users
  2023. can set for the symbol. For other types of symbols, a visibility of "n"
  2024. means the user value will be ignored. A visibility of "n" corresponds
  2025. to not being visible in the 'make *config' interfaces.
  2026. Example (assuming we're running with modules enabled -- i.e., MODULES
  2027. set to 'y'):
  2028. # Assume this has been assigned 'n'
  2029. config N_SYM
  2030. tristate "N_SYM"
  2031. # Assume this has been assigned 'm'
  2032. config M_SYM
  2033. tristate "M_SYM"
  2034. # Has visibility 'n'
  2035. config A
  2036. tristate "A"
  2037. depends on N_SYM
  2038. # Has visibility 'm'
  2039. config B
  2040. tristate "B"
  2041. depends on M_SYM
  2042. # Has visibility 'y'
  2043. config C
  2044. tristate "C"
  2045. # Has no prompt, and hence visibility 'n'
  2046. config D
  2047. tristate
  2048. Having visibility be tri-valued ensures that e.g. a symbol cannot be
  2049. set to "y" by the user if it depends on a symbol with value "m", which
  2050. wouldn't be safe.
  2051. You should probably look at get_lower/upper_bound(),
  2052. get_assignable_values() and is_modifiable() before using this."""
  2053. return self._get_visibility()
  2054. def get_parent(self):
  2055. """Returns the menu or choice statement that contains the symbol, or
  2056. None if the symbol is at the top level. Note that if statements are
  2057. treated as syntactic and do not have an explicit class
  2058. representation."""
  2059. return self.parent
  2060. def get_referenced_symbols(self, refs_from_enclosing = False):
  2061. """Returns the set() of all symbols referenced by this symbol. For
  2062. example, the symbol defined by
  2063. config FOO
  2064. bool
  2065. prompt "foo" if A && B
  2066. default C if D
  2067. depends on E
  2068. select F if G
  2069. references the symbols A through G.
  2070. refs_from_enclosing (default: False) -- If True, the symbols
  2071. referenced by enclosing menus and if's will be
  2072. included in the result."""
  2073. return self.all_referenced_syms if refs_from_enclosing else self.referenced_syms
  2074. def get_selected_symbols(self):
  2075. """Returns the set() of all symbols X for which this symbol has a
  2076. 'select X' or 'select X if Y' (regardless of whether Y is satisfied or
  2077. not). This is a subset of the symbols returned by
  2078. get_referenced_symbols()."""
  2079. return self.selected_syms
  2080. def get_help(self):
  2081. """Returns the help text of the symbol, or None if the symbol has no
  2082. help text."""
  2083. return self.help
  2084. def get_config(self):
  2085. """Returns the Config instance this symbol is from."""
  2086. return self.config
  2087. def get_def_locations(self):
  2088. """Returns a list of (filename, linenr) tuples, where filename (string)
  2089. and linenr (int) represent a location where the symbol is defined. For
  2090. the vast majority of symbols this list will only contain one element.
  2091. For the following Kconfig, FOO would get two entries: the lines marked
  2092. with *.
  2093. config FOO *
  2094. bool "foo prompt 1"
  2095. config FOO *
  2096. bool "foo prompt 2"
  2097. """
  2098. return self.def_locations
  2099. def get_ref_locations(self):
  2100. """Returns a list of (filename, linenr) tuples, where filename (string)
  2101. and linenr (int) represent a location where the symbol is referenced in
  2102. the configuration. For example, the lines marked by * would be included
  2103. for FOO below:
  2104. config A
  2105. bool
  2106. default BAR || FOO *
  2107. config B
  2108. tristate
  2109. depends on FOO *
  2110. default m if FOO *
  2111. if FOO *
  2112. config A
  2113. bool "A"
  2114. endif
  2115. config FOO (definition not included)
  2116. bool
  2117. """
  2118. return self.ref_locations
  2119. def is_modifiable(self):
  2120. """Returns True if the value of the symbol could be modified by calling
  2121. Symbol.set_user_value() and False otherwise.
  2122. For bools and tristates, this corresponds to the symbol being visible
  2123. in the 'make menuconfig' interface and not already being pinned to a
  2124. specific value (e.g. because it is selected by another symbol).
  2125. For strings and numbers, this corresponds to just being visible. (See
  2126. Symbol.get_visibility().)"""
  2127. if self.is_special_:
  2128. return False
  2129. if self.type == BOOL or self.type == TRISTATE:
  2130. rev_dep = self.config._eval_expr(self.rev_dep)
  2131. # A bool selected to "m" gets promoted to "y"
  2132. if self.type == BOOL and rev_dep == "m":
  2133. rev_dep = "y"
  2134. return (tri_to_int[self._get_visibility()] -
  2135. tri_to_int[rev_dep]) > 0
  2136. return self._get_visibility() != "n"
  2137. def is_defined(self):
  2138. """Returns False if the symbol is referred to in the Kconfig but never
  2139. actually defined, otherwise True."""
  2140. return self.is_defined_
  2141. def is_special(self):
  2142. """Returns True if the symbol is one of the special symbols n, m, y, or
  2143. UNAME_RELEASE, or gets its value from the environment. Otherwise,
  2144. returns False."""
  2145. return self.is_special_
  2146. def is_from_environment(self):
  2147. """Returns True if the symbol gets its value from the environment.
  2148. Otherwise, returns False."""
  2149. return self.is_from_env
  2150. def has_ranges(self):
  2151. """Returns True if the symbol is of type INT or HEX and has ranges that
  2152. limits what values it can take on, otherwise False."""
  2153. return self.ranges != []
  2154. def is_choice_symbol(self):
  2155. """Returns True if the symbol is in a choice statement and is an actual
  2156. choice symbol (see Choice.get_symbols()); otherwise, returns
  2157. False."""
  2158. return self.is_choice_symbol_
  2159. def is_choice_selection(self):
  2160. """Returns True if the symbol is contained in a choice statement and is
  2161. the selected item, otherwise False. Equivalent to 'sym.is_choice_symbol()
  2162. and sym.get_parent().get_selection() is sym'."""
  2163. return self.is_choice_symbol_ and self.parent.get_selection() is self
  2164. def __str__(self):
  2165. """Returns a string containing various information about the symbol."""
  2166. return self.config._get_sym_or_choice_str(self)
  2167. #
  2168. # Private methods
  2169. #
  2170. def __init__(self):
  2171. """Symbol constructor -- not intended to be called directly by
  2172. kconfiglib clients."""
  2173. # Set default values
  2174. _HasVisibility.__init__(self)
  2175. self.config = None
  2176. self.parent = None
  2177. self.name = None
  2178. self.type = UNKNOWN
  2179. self.def_exprs = []
  2180. self.ranges = []
  2181. self.rev_dep = "n"
  2182. # The prompt, default value and select conditions without any
  2183. # dependencies from menus or if's propagated to them
  2184. self.orig_prompts = []
  2185. self.orig_def_exprs = []
  2186. self.orig_selects = []
  2187. # Dependencies inherited from containing menus and if's
  2188. self.deps_from_containing = None
  2189. self.help = None
  2190. # The set of symbols referenced by this symbol (see
  2191. # get_referenced_symbols())
  2192. self.referenced_syms = set()
  2193. # The set of symbols selected by this symbol (see
  2194. # get_selected_symbols())
  2195. self.selected_syms = set()
  2196. # Like 'referenced_syms', but includes symbols from
  2197. # dependencies inherited from enclosing menus and if's
  2198. self.all_referenced_syms = set()
  2199. # This is set to True for "actual" choice symbols. See
  2200. # Choice._determine_actual_symbols(). The trailing underscore avoids a
  2201. # collision with is_choice_symbol().
  2202. self.is_choice_symbol_ = False
  2203. # This records only dependencies specified with 'depends on'. Needed
  2204. # when determining actual choice items (hrrrr...). See also
  2205. # Choice._determine_actual_symbols().
  2206. self.menu_dep = None
  2207. # See Symbol.get_ref/def_locations().
  2208. self.def_locations = []
  2209. self.ref_locations = []
  2210. self.user_val = None
  2211. # Flags
  2212. # Should the symbol get an entry in .config?
  2213. self.write_to_conf = False
  2214. # Caches the calculated value
  2215. self.cached_value = None
  2216. # Note: An instance variable 'self.dep' gets set on the Symbol in
  2217. # Config._build_dep(), linking the symbol to the symbols that
  2218. # immediately depend on it (in a caching/invalidation sense). The total
  2219. # set of dependent symbols for the symbol (the transitive closure) is
  2220. # calculated on an as-needed basis in _get_dependent().
  2221. # Caches the total list of dependent symbols. Calculated in
  2222. # _get_dependent().
  2223. self.cached_deps = None
  2224. # Does the symbol have an entry in the Kconfig file? The trailing
  2225. # underscore avoids a collision with is_defined().
  2226. self.is_defined_ = False
  2227. # Does the symbol get its value in some special way, e.g. from the
  2228. # environment or by being one of the special symbols n, m, and y? If
  2229. # so, the value is stored in self.cached_value, which is never
  2230. # invalidated. The trailing underscore avoids a collision with
  2231. # is_special().
  2232. self.is_special_ = False
  2233. # Does the symbol get its value from the environment?
  2234. self.is_from_env = False
  2235. def _invalidate(self):
  2236. if self.is_special_:
  2237. return
  2238. if self.is_choice_symbol_:
  2239. self.parent._invalidate()
  2240. _HasVisibility._invalidate(self)
  2241. self.write_to_conf = False
  2242. self.cached_value = None
  2243. def _invalidate_dependent(self):
  2244. for sym in self._get_dependent():
  2245. sym._invalidate()
  2246. def _set_user_value_no_invalidate(self, v, suppress_load_warnings):
  2247. """Like set_user_value(), but does not invalidate any symbols.
  2248. suppress_load_warnings --
  2249. some warnings are annoying when loading a .config that can be helpful
  2250. when manually invoking set_user_value(). This flag is set to True to
  2251. suppress such warnings.
  2252. Perhaps this could be made optional for load_config() instead."""
  2253. if self.is_special_:
  2254. if self.is_from_env:
  2255. self.config._warn('attempt to assign the value "{0}" to the '
  2256. 'symbol {1}, which gets its value from the '
  2257. 'environment. Assignment ignored.'
  2258. .format(v, self.name))
  2259. else:
  2260. self.config._warn('attempt to assign the value "{0}" to the '
  2261. 'special symbol {1}. Assignment ignored.'
  2262. .format(v, self.name))
  2263. return
  2264. if not self.is_defined_:
  2265. filename, linenr = self.ref_locations[0]
  2266. self.config._undef_assign('attempt to assign the value "{0}" to {1}, '
  2267. "which is referenced at {2}:{3} but never "
  2268. "defined. Assignment ignored."
  2269. .format(v, self.name, filename, linenr))
  2270. return
  2271. # Check if the value is valid for our type
  2272. if not (( self.type == BOOL and (v == "n" or v == "y") ) or
  2273. ( self.type == TRISTATE and (v == "n" or v == "m" or
  2274. v == "y") ) or
  2275. ( self.type == STRING ) or
  2276. ( self.type == INT and _is_base_n(v, 10) ) or
  2277. ( self.type == HEX and _is_base_n(v, 16) )):
  2278. self.config._warn('the value "{0}" is invalid for {1}, which has type {2}. '
  2279. "Assignment ignored."
  2280. .format(v, self.name, typename[self.type]))
  2281. return
  2282. if self.prompts == [] and not suppress_load_warnings:
  2283. self.config._warn('assigning "{0}" to the symbol {1} which '
  2284. 'lacks prompts and thus has visibility "n". '
  2285. 'The assignment will have no effect.'
  2286. .format(v, self.name))
  2287. self.user_val = v
  2288. if self.is_choice_symbol_ and (self.type == BOOL or
  2289. self.type == TRISTATE):
  2290. choice = self.parent
  2291. if v == "y":
  2292. choice.user_val = self
  2293. choice.user_mode = "y"
  2294. elif v == "m":
  2295. choice.user_val = None
  2296. choice.user_mode = "m"
  2297. def _unset_user_value_no_recursive_invalidate(self):
  2298. self._invalidate()
  2299. self.user_val = None
  2300. if self.is_choice_symbol_:
  2301. self.parent._unset_user_value()
  2302. def _make_conf(self):
  2303. if self.already_written:
  2304. return []
  2305. self.already_written = True
  2306. # Note: write_to_conf is determined in get_value()
  2307. val = self.get_value()
  2308. if not self.write_to_conf:
  2309. return []
  2310. if self.type == BOOL or self.type == TRISTATE:
  2311. if val == "m" or val == "y":
  2312. return ["CONFIG_{0}={1}".format(self.name, val)]
  2313. return ["# CONFIG_{0} is not set".format(self.name)]
  2314. elif self.type == STRING:
  2315. # Escape \ and "
  2316. return ['CONFIG_{0}="{1}"'
  2317. .format(self.name,
  2318. val.replace("\\", "\\\\").replace('"', '\\"'))]
  2319. elif self.type == INT or self.type == HEX:
  2320. return ["CONFIG_{0}={1}".format(self.name, val)]
  2321. else:
  2322. _internal_error('Internal error while creating .config: unknown type "{0}".'
  2323. .format(self.type))
  2324. def _get_dependent(self):
  2325. """Returns the set of symbols that should be invalidated if the value
  2326. of the symbol changes, because they might be affected by the change.
  2327. Note that this is an internal API -- it's probably of limited
  2328. usefulness to clients."""
  2329. if self.cached_deps is not None:
  2330. return self.cached_deps
  2331. res = set()
  2332. self._add_dependent_ignore_siblings(res)
  2333. if self.is_choice_symbol_:
  2334. for s in self.parent.get_symbols():
  2335. if s is not self:
  2336. res.add(s)
  2337. s._add_dependent_ignore_siblings(res)
  2338. self.cached_deps = res
  2339. return res
  2340. def _add_dependent_ignore_siblings(self, to):
  2341. """Calculating dependencies gets a bit tricky for choice items as they
  2342. all depend on each other, potentially leading to infinite recursion.
  2343. This helper function calculates dependencies ignoring the other symbols
  2344. in the choice. It also works fine for symbols that are not choice
  2345. items."""
  2346. for s in self.dep:
  2347. to.add(s)
  2348. to |= s._get_dependent()
  2349. def _has_auto_menu_dep_on(self, on):
  2350. """See Choice._determine_actual_symbols()."""
  2351. if not isinstance(self.parent, Choice):
  2352. _internal_error("Attempt to determine auto menu dependency for symbol ouside of choice.")
  2353. if self.prompts == []:
  2354. # If we have no prompt, use the menu dependencies instead (what was
  2355. # specified with 'depends on')
  2356. return self.menu_dep is not None and \
  2357. self.config._expr_depends_on(self.menu_dep, on)
  2358. for (_, cond_expr) in self.prompts:
  2359. if self.config._expr_depends_on(cond_expr, on):
  2360. return True
  2361. return False
  2362. class Menu(Item):
  2363. """Represents a menu statement."""
  2364. #
  2365. # Public interface
  2366. #
  2367. def get_config(self):
  2368. """Return the Config instance this menu is from."""
  2369. return self.config
  2370. def get_visibility(self):
  2371. """Returns the visibility of the menu. This also affects the visibility
  2372. of subitems. See also Symbol.get_visibility()."""
  2373. return self.config._eval_expr(self.dep_expr)
  2374. def get_visible_if_visibility(self):
  2375. """Returns the visibility the menu gets from its 'visible if'
  2376. condition. "y" if the menu has no 'visible if' condition."""
  2377. return self.config._eval_expr(self.visible_if_expr)
  2378. def get_items(self, recursive = False):
  2379. """Returns a list containing the items (symbols, menus, choice
  2380. statements and comments) in in the menu, in the same order that the
  2381. items appear within the menu.
  2382. recursive (default: False) -- True if items contained in items within
  2383. the menu should be included
  2384. recursively (preorder)."""
  2385. if not recursive:
  2386. return self.block.get_items()
  2387. res = []
  2388. for item in self.block.get_items():
  2389. res.append(item)
  2390. if isinstance(item, Menu):
  2391. res.extend(item.get_items(True))
  2392. elif isinstance(item, Choice):
  2393. res.extend(item.get_items())
  2394. return res
  2395. def get_symbols(self, recursive = False):
  2396. """Returns a list containing the symbols in the menu, in the same order
  2397. that they appear within the menu.
  2398. recursive (default: False) -- True if symbols contained in items within
  2399. the menu should be included
  2400. recursively."""
  2401. return [item for item in self.get_items(recursive) if isinstance(item, Symbol)]
  2402. def get_title(self):
  2403. """Returns the title text of the menu."""
  2404. return self.title
  2405. def get_parent(self):
  2406. """Returns the menu or choice statement that contains the menu, or
  2407. None if the menu is at the top level. Note that if statements are
  2408. treated as syntactic sugar and do not have an explicit class
  2409. representation."""
  2410. return self.parent
  2411. def get_referenced_symbols(self, refs_from_enclosing = False):
  2412. """See Symbol.get_referenced_symbols()."""
  2413. return self.all_referenced_syms if refs_from_enclosing else self.referenced_syms
  2414. def get_location(self):
  2415. """Returns the location of the menu as a (filename, linenr) tuple,
  2416. where filename is a string and linenr an int."""
  2417. return (self.filename, self.linenr)
  2418. def __str__(self):
  2419. """Returns a string containing various information about the menu."""
  2420. depends_on_str = self.config._expr_val_str(self.orig_deps,
  2421. "(no dependencies)")
  2422. visible_if_str = self.config._expr_val_str(self.visible_if_expr,
  2423. "(no dependencies)")
  2424. additional_deps_str = " " + self.config._expr_val_str(self.deps_from_containing,
  2425. "(no additional dependencies)")
  2426. return _sep_lines("Menu",
  2427. "Title : " + self.title,
  2428. "'depends on' dependencies : " + depends_on_str,
  2429. "'visible if' dependencies : " + visible_if_str,
  2430. "Additional dependencies from enclosing menus and if's:",
  2431. additional_deps_str,
  2432. "Location: {0}:{1}".format(self.filename, self.linenr))
  2433. #
  2434. # Private methods
  2435. #
  2436. def __init__(self):
  2437. """Menu constructor -- not intended to be called directly by
  2438. kconfiglib clients."""
  2439. self.config = None
  2440. self.parent = None
  2441. self.title = None
  2442. self.block = None
  2443. self.dep_expr = None
  2444. # Dependency expression without dependencies from enclosing menus and
  2445. # if's propagated
  2446. self.orig_deps = None
  2447. # Dependencies inherited from containing menus and if's
  2448. self.deps_from_containing = None
  2449. # The 'visible if' expression
  2450. self.visible_if_expr = None
  2451. # The set of symbols referenced by this menu (see
  2452. # get_referenced_symbols())
  2453. self.referenced_syms = set()
  2454. # Like 'referenced_syms', but includes symbols from
  2455. # dependencies inherited from enclosing menus and if's
  2456. self.all_referenced_syms = None
  2457. self.filename = None
  2458. self.linenr = None
  2459. def _make_conf(self):
  2460. item_conf = self.block._make_conf()
  2461. if self.config._eval_expr(self.dep_expr) != "n" and \
  2462. self.config._eval_expr(self.visible_if_expr) != "n":
  2463. return ["\n#\n# {0}\n#".format(self.title)] + item_conf
  2464. return item_conf
  2465. class Choice(Item, _HasVisibility):
  2466. """Represents a choice statement. A choice can be in one of three modes:
  2467. "n" - The choice is not visible and no symbols can be selected.
  2468. "m" - Any number of symbols can be set to "m". The rest will be "n". This
  2469. is safe since potentially conflicting options don't actually get
  2470. compiled into the kernel simultaneously with "m".
  2471. "y" - One symbol will be "y" while the rest are "n".
  2472. Only tristate choices can be in "m" mode, and the visibility of the choice
  2473. is an upper bound on the mode, so that e.g. a choice that depends on a
  2474. symbol with value "m" will be in "m" mode.
  2475. The mode changes automatically when a value is assigned to a symbol within
  2476. the choice.
  2477. See Symbol.get_visibility() too."""
  2478. #
  2479. # Public interface
  2480. #
  2481. def get_selection(self):
  2482. """Returns the symbol selected (either by the user or through
  2483. defaults), or None if either no symbol is selected or the mode is not
  2484. "y"."""
  2485. if self.cached_selection is not None:
  2486. if self.cached_selection == NO_SELECTION:
  2487. return None
  2488. return self.cached_selection
  2489. if self.get_mode() != "y":
  2490. return self._cache_ret(None)
  2491. # User choice available?
  2492. if self.user_val is not None and \
  2493. self.user_val._get_visibility() == "y":
  2494. return self._cache_ret(self.user_val)
  2495. if self.optional:
  2496. return self._cache_ret(None)
  2497. return self._cache_ret(self.get_selection_from_defaults())
  2498. def get_selection_from_defaults(self):
  2499. """Like Choice.get_selection(), but acts as if no symbol has been
  2500. selected by the user and no 'optional' flag is in effect."""
  2501. if self.actual_symbols == []:
  2502. return None
  2503. for (symbol, cond_expr) in self.def_exprs:
  2504. if self.config._eval_expr(cond_expr) != "n":
  2505. chosen_symbol = symbol
  2506. break
  2507. else:
  2508. chosen_symbol = self.actual_symbols[0]
  2509. # Is the chosen symbol visible?
  2510. if chosen_symbol._get_visibility() != "n":
  2511. return chosen_symbol
  2512. # Otherwise, pick the first visible symbol
  2513. for sym in self.actual_symbols:
  2514. if sym._get_visibility() != "n":
  2515. return sym
  2516. return None
  2517. def get_user_selection(self):
  2518. """If the choice is in "y" mode and has a user-selected symbol, returns
  2519. that symbol. Otherwise, returns None."""
  2520. return self.user_val
  2521. def get_config(self):
  2522. """Returns the Config instance this choice is from."""
  2523. return self.config
  2524. def get_name(self):
  2525. """For named choices, returns the name. Returns None for unnamed
  2526. choices. No named choices appear anywhere in the kernel Kconfig files
  2527. as of Linux 3.7.0-rc8."""
  2528. return self.name
  2529. def get_prompts(self):
  2530. """Returns a list of prompts defined for the choice, in the order they
  2531. appear in the configuration files. Returns the empty list for choices
  2532. with no prompt.
  2533. This list will have a single entry for the vast majority of choices
  2534. having prompts, but having multiple prompts for a single choice is
  2535. possible through having multiple 'choice' entries for it (though I'm
  2536. not sure if that ever happens in practice)."""
  2537. return [prompt for prompt, _ in self.orig_prompts]
  2538. def get_help(self):
  2539. """Returns the help text of the choice, or None if the choice has no
  2540. help text."""
  2541. return self.help
  2542. def get_type(self):
  2543. """Returns the type of the choice. See Symbol.get_type()."""
  2544. return self.type
  2545. def get_items(self):
  2546. """Gets all items contained in the choice in the same order as within
  2547. the configuration ("items" instead of "symbols" since choices and
  2548. comments might appear within choices. This only happens in one place as
  2549. of Linux 3.7.0-rc8, in drivers/usb/gadget/Kconfig)."""
  2550. return self.block.get_items()
  2551. def get_symbols(self):
  2552. """Returns a list containing the choice's symbols.
  2553. A quirk (perhaps a bug) of Kconfig is that you can put items within a
  2554. choice that will not be considered members of the choice insofar as
  2555. selection is concerned. This happens for example if one symbol within a
  2556. choice 'depends on' the symbol preceding it, or if you put non-symbol
  2557. items within choices.
  2558. As of Linux 3.7.0-rc8, this seems to be used intentionally in one
  2559. place: drivers/usb/gadget/Kconfig.
  2560. This function returns the "proper" symbols of the choice in the order
  2561. they appear in the choice, excluding such items. If you want all items
  2562. in the choice, use get_items()."""
  2563. return self.actual_symbols
  2564. def get_parent(self):
  2565. """Returns the menu or choice statement that contains the choice, or
  2566. None if the choice is at the top level. Note that if statements are
  2567. treated as syntactic sugar and do not have an explicit class
  2568. representation."""
  2569. return self.parent
  2570. def get_referenced_symbols(self, refs_from_enclosing = False):
  2571. """See Symbol.get_referenced_symbols()."""
  2572. return self.all_referenced_syms if refs_from_enclosing else self.referenced_syms
  2573. def get_def_locations(self):
  2574. """Returns a list of (filename, linenr) tuples, where filename (string)
  2575. and linenr (int) represent a location where the choice is defined. For
  2576. the vast majority of choices (all of them as of Linux 3.7.0-rc8) this
  2577. list will only contain one element, but its possible for named choices
  2578. to be defined in multiple locations."""
  2579. return self.def_locations
  2580. def get_visibility(self):
  2581. """Returns the visibility of the choice statement: one of "n", "m" or
  2582. "y". This acts as an upper limit on the mode of the choice (though bool
  2583. choices can only have the mode "y"). See the class documentation for an
  2584. explanation of modes."""
  2585. return self._get_visibility()
  2586. def get_mode(self):
  2587. """Returns the mode of the choice. See the class documentation for
  2588. an explanation of modes."""
  2589. minimum_mode = "n" if self.optional else "m"
  2590. mode = self.user_mode if self.user_mode is not None else minimum_mode
  2591. mode = self.config._eval_min(mode, self._get_visibility())
  2592. # Promote "m" to "y" for boolean choices
  2593. if mode == "m" and self.type == BOOL:
  2594. return "y"
  2595. return mode
  2596. def is_optional(self):
  2597. """Returns True if the symbol has the optional flag set (and so will default
  2598. to "n" mode). Otherwise, returns False."""
  2599. return self.optional
  2600. def __str__(self):
  2601. """Returns a string containing various information about the choice
  2602. statement."""
  2603. return self.config._get_sym_or_choice_str(self)
  2604. #
  2605. # Private methods
  2606. #
  2607. def __init__(self):
  2608. """Choice constructor -- not intended to be called directly by
  2609. kconfiglib clients."""
  2610. _HasVisibility.__init__(self)
  2611. self.config = None
  2612. self.parent = None
  2613. self.name = None # Yes, choices can be named
  2614. self.type = UNKNOWN
  2615. self.def_exprs = []
  2616. self.help = None
  2617. self.optional = False
  2618. self.block = None
  2619. # The prompts and default values without any dependencies from
  2620. # enclosing menus or if's propagated
  2621. self.orig_prompts = []
  2622. self.orig_def_exprs = []
  2623. # Dependencies inherited from containing menus and if's
  2624. self.deps_from_containing = None
  2625. # We need to filter out symbols that appear within the choice block but
  2626. # are not considered choice items (see
  2627. # Choice._determine_actual_symbols()) This list holds the "actual" choice
  2628. # items.
  2629. self.actual_symbols = []
  2630. # The set of symbols referenced by this choice (see
  2631. # get_referenced_symbols())
  2632. self.referenced_syms = set()
  2633. # Like 'referenced_syms', but includes symbols from
  2634. # dependencies inherited from enclosing menus and if's
  2635. self.all_referenced_syms = set()
  2636. # See Choice.get_def_locations()
  2637. self.def_locations = []
  2638. self.user_val = None
  2639. self.user_mode = None
  2640. self.cached_selection = None
  2641. def _determine_actual_symbols(self):
  2642. """If a symbol's visibility depends on the preceding symbol within a
  2643. choice, it is no longer viewed as a choice item (quite possibly a bug,
  2644. but some things consciously use it.. ugh. It stems from automatic
  2645. submenu creation). In addition, it's possible to have choices and
  2646. comments within choices, and those shouldn't be considered as choice
  2647. items either. Only drivers/usb/gadget/Kconfig seems to depend on any of
  2648. this. This method computes the "actual" items in the choice and sets
  2649. the is_choice_symbol_ flag on them (retrieved via is_choice_symbol()).
  2650. Don't let this scare you: an earlier version simply checked for a
  2651. sequence of symbols where all symbols after the first appeared in the
  2652. 'depends on' expression of the first, and that worked fine. The added
  2653. complexity is to be future-proof in the event that
  2654. drivers/usb/gadget/Kconfig turns even more sinister. It might very well
  2655. be overkilling things (especially if that file is refactored ;)."""
  2656. items = self.block.get_items()
  2657. # Items might depend on each other in a tree structure, so we need a
  2658. # stack to keep track of the current tentative parent
  2659. stack = []
  2660. for item in items:
  2661. if not isinstance(item, Symbol):
  2662. stack = []
  2663. continue
  2664. while stack != []:
  2665. if item._has_auto_menu_dep_on(stack[-1]):
  2666. # The item should not be viewed as a choice item, so don't
  2667. # set item.is_choice_symbol_.
  2668. stack.append(item)
  2669. break
  2670. else:
  2671. stack.pop()
  2672. else:
  2673. item.is_choice_symbol_ = True
  2674. self.actual_symbols.append(item)
  2675. stack.append(item)
  2676. def _cache_ret(self, selection):
  2677. # As None is used to indicate the lack of a cached value we can't use
  2678. # that to cache the fact that the choice has no selection. Instead, we
  2679. # use the symbolic constant NO_SELECTION.
  2680. if selection is None:
  2681. self.cached_selection = NO_SELECTION
  2682. else:
  2683. self.cached_selection = selection
  2684. return selection
  2685. def _invalidate(self):
  2686. _HasVisibility._invalidate(self)
  2687. self.cached_selection = None
  2688. def _unset_user_value(self):
  2689. self._invalidate()
  2690. self.user_val = None
  2691. self.user_mode = None
  2692. def _make_conf(self):
  2693. return self.block._make_conf()
  2694. class Comment(Item):
  2695. """Represents a comment statement."""
  2696. #
  2697. # Public interface
  2698. #
  2699. def get_config(self):
  2700. """Returns the Config instance this comment is from."""
  2701. return self.config
  2702. def get_visibility(self):
  2703. """Returns the visibility of the comment. See also
  2704. Symbol.get_visibility()."""
  2705. return self.config._eval_expr(self.dep_expr)
  2706. def get_text(self):
  2707. """Returns the text of the comment."""
  2708. return self.text
  2709. def get_parent(self):
  2710. """Returns the menu or choice statement that contains the comment, or
  2711. None if the comment is at the top level. Note that if statements are
  2712. treated as syntactic sugar and do not have an explicit class
  2713. representation."""
  2714. return self.parent
  2715. def get_referenced_symbols(self, refs_from_enclosing = False):
  2716. """See Symbol.get_referenced_symbols()."""
  2717. return self.all_referenced_syms if refs_from_enclosing else self.referenced_syms
  2718. def get_location(self):
  2719. """Returns the location of the comment as a (filename, linenr) tuple,
  2720. where filename is a string and linenr an int."""
  2721. return (self.filename, self.linenr)
  2722. def __str__(self):
  2723. """Returns a string containing various information about the comment."""
  2724. dep_str = self.config._expr_val_str(self.orig_deps, "(no dependencies)")
  2725. additional_deps_str = " " + self.config._expr_val_str(self.deps_from_containing,
  2726. "(no additional dependencies)")
  2727. return _sep_lines("Comment",
  2728. "Text: " + str(self.text),
  2729. "Dependencies: " + dep_str,
  2730. "Additional dependencies from enclosing menus and if's:",
  2731. additional_deps_str,
  2732. "Location: {0}:{1}".format(self.filename, self.linenr))
  2733. #
  2734. # Private methods
  2735. #
  2736. def __init__(self):
  2737. """Comment constructor -- not intended to be called directly by
  2738. kconfiglib clients."""
  2739. self.config = None
  2740. self.parent = None
  2741. self.text = None
  2742. self.dep_expr = None
  2743. # Dependency expression without dependencies from enclosing menus and
  2744. # if's propagated
  2745. self.orig_deps = None
  2746. # Dependencies inherited from containing menus and if's
  2747. self.deps_from_containing = None
  2748. # The set of symbols referenced by this comment (see
  2749. # get_referenced_symbols())
  2750. self.referenced_syms = set()
  2751. # Like 'referenced_syms', but includes symbols from
  2752. # dependencies inherited from enclosing menus and if's
  2753. self.all_referenced_syms = None
  2754. self.filename = None
  2755. self.linenr = None
  2756. def _make_conf(self):
  2757. if self.config._eval_expr(self.dep_expr) != "n":
  2758. return ["\n#\n# {0}\n#".format(self.text)]
  2759. return []
  2760. class _Feed:
  2761. """Class for working with sequences in a stream-like fashion; handy for tokens."""
  2762. def __init__(self, items):
  2763. self.items = items
  2764. self.length = len(self.items)
  2765. self.i = 0
  2766. def get_next(self):
  2767. if self.i >= self.length:
  2768. return None
  2769. item = self.items[self.i]
  2770. self.i += 1
  2771. return item
  2772. def peek_next(self):
  2773. return None if self.i >= self.length else self.items[self.i]
  2774. def go_to_start(self):
  2775. self.i = 0
  2776. def __getitem__(self, index):
  2777. return self.items[index]
  2778. def __len__(self):
  2779. return len(self.items)
  2780. def is_empty(self):
  2781. return self.items == []
  2782. def check(self, token):
  2783. """Check if the next token is 'token'. If so, remove it from the token
  2784. feed and return True. Otherwise, leave it in and return False."""
  2785. if self.i >= self.length:
  2786. return None
  2787. if self.items[self.i] == token:
  2788. self.i += 1
  2789. return True
  2790. return False
  2791. def remove_while(self, pred):
  2792. while self.i < self.length and pred(self.items[self.i]):
  2793. self.i += 1
  2794. def go_back(self):
  2795. if self.i <= 0:
  2796. _internal_error("Attempt to move back in Feed while already at the beginning.")
  2797. self.i -= 1
  2798. class _FileFeed(_Feed):
  2799. """Feed subclass that keeps track of the current filename and line
  2800. number."""
  2801. def __init__(self, lines, filename):
  2802. self.filename = _clean_up_path(filename)
  2803. _Feed.__init__(self, lines)
  2804. def get_filename(self):
  2805. return self.filename
  2806. def get_linenr(self):
  2807. return self.i
  2808. #
  2809. # Misc. public global utility functions
  2810. #
  2811. def tri_less(v1, v2):
  2812. """Returns True if the tristate v1 is less than the tristate v2, where "n",
  2813. "m" and "y" are ordered from lowest to highest. Otherwise, returns
  2814. False."""
  2815. return tri_to_int[v1] < tri_to_int[v2]
  2816. def tri_less_eq(v1, v2):
  2817. """Returns True if the tristate v1 is less than or equal to the tristate
  2818. v2, where "n", "m" and "y" are ordered from lowest to highest. Otherwise,
  2819. returns False."""
  2820. return tri_to_int[v1] <= tri_to_int[v2]
  2821. def tri_greater(v1, v2):
  2822. """Returns True if the tristate v1 is greater than the tristate v2, where
  2823. "n", "m" and "y" are ordered from lowest to highest. Otherwise, returns
  2824. False."""
  2825. return tri_to_int[v1] > tri_to_int[v2]
  2826. def tri_greater_eq(v1, v2):
  2827. """Returns True if the tristate v1 is greater than or equal to the tristate
  2828. v2, where "n", "m" and "y" are ordered from lowest to highest. Otherwise,
  2829. returns False."""
  2830. return tri_to_int[v1] >= tri_to_int[v2]
  2831. #
  2832. # Helper functions, mostly related to text processing
  2833. #
  2834. def _strip_quotes(s, line, filename, linenr):
  2835. """Removes any quotes surrounding 's' if it has them; otherwise returns 's'
  2836. unmodified."""
  2837. s = s.strip()
  2838. if not s:
  2839. return ""
  2840. if s[0] == '"' or s[0] == "'":
  2841. if len(s) < 2 or s[-1] != s[0]:
  2842. _parse_error(line,
  2843. "malformed string literal",
  2844. filename,
  2845. linenr)
  2846. return s[1:-1]
  2847. return s
  2848. def _indentation(line):
  2849. """Returns the indentation of the line, treating tab stops as being spaced
  2850. 8 characters apart."""
  2851. if line.isspace():
  2852. _internal_error("Attempt to take indentation of blank line.")
  2853. indent = 0
  2854. for c in line:
  2855. if c == " ":
  2856. indent += 1
  2857. elif c == "\t":
  2858. # Go to the next tab stop
  2859. indent = (indent + 8) & ~7
  2860. else:
  2861. return indent
  2862. def _deindent(line, indent):
  2863. """Deindent 'line' by 'indent' spaces."""
  2864. line = line.expandtabs()
  2865. if len(line) <= indent:
  2866. return line
  2867. return line[indent:]
  2868. def _is_base_n(s, n):
  2869. try:
  2870. int(s, n)
  2871. return True
  2872. except ValueError:
  2873. return False
  2874. def _sep_lines(*args):
  2875. """Returns a string comprised of all arguments, with newlines inserted
  2876. between them."""
  2877. return "\n".join(args)
  2878. def _comment(s):
  2879. """Returns a new string with "#" inserted before each line in 's'."""
  2880. if not s:
  2881. return "#"
  2882. res = "".join(["#" + line for line in s.splitlines(True)])
  2883. if s.endswith("\n"):
  2884. return res + "#"
  2885. return res
  2886. def _get_lines(filename):
  2887. """Returns a list of lines from 'filename', joining any line ending in \\
  2888. with the following line."""
  2889. with open(filename, "r") as f:
  2890. lines = []
  2891. accum = ""
  2892. while 1:
  2893. line = f.readline()
  2894. if line == "":
  2895. return lines
  2896. if line.endswith("\\\n"):
  2897. accum += line[:-2]
  2898. else:
  2899. accum += line
  2900. lines.append(accum)
  2901. accum = ""
  2902. def _strip_trailing_slash(path):
  2903. """Removes any trailing slash from 'path'."""
  2904. return path[:-1] if path.endswith("/") else path
  2905. def _clean_up_path(path):
  2906. """Strips any initial "./" and trailing slash from 'path'."""
  2907. if path.startswith("./"):
  2908. path = path[2:]
  2909. return _strip_trailing_slash(path)
  2910. #
  2911. # Error handling
  2912. #
  2913. class Kconfig_Syntax_Error(Exception):
  2914. """Exception raised for syntax errors."""
  2915. pass
  2916. class Internal_Error(Exception):
  2917. """Exception raised for internal errors."""
  2918. pass
  2919. def _tokenization_error(s, index, filename, linenr):
  2920. if filename is not None:
  2921. assert linenr is not None
  2922. sys.stderr.write("{0}:{1}:\n".format(filename, linenr))
  2923. if s.endswith("\n"):
  2924. s = s[:-1]
  2925. # Calculate the visual offset corresponding to index 'index' in 's'
  2926. # assuming tabstops are spaced 8 characters apart
  2927. vis_index = 0
  2928. for c in s[:index]:
  2929. if c == "\t":
  2930. vis_index = (vis_index + 8) & ~7
  2931. else:
  2932. vis_index += 1
  2933. # Don't output actual tabs to be independent of how the terminal renders
  2934. # them
  2935. s = s.expandtabs()
  2936. raise Kconfig_Syntax_Error, (
  2937. _sep_lines("Error during tokenization at location indicated by caret.\n",
  2938. s,
  2939. " " * vis_index + "^\n"))
  2940. def _parse_error(s, msg, filename, linenr):
  2941. error_str = ""
  2942. if filename is not None:
  2943. assert linenr is not None
  2944. error_str += "{0}:{1}: ".format(filename, linenr)
  2945. if s.endswith("\n"):
  2946. s = s[:-1]
  2947. error_str += 'Error while parsing "{0}"'.format(s) + \
  2948. ("." if msg is None else ": " + msg)
  2949. raise Kconfig_Syntax_Error, error_str
  2950. def _internal_error(msg):
  2951. msg += "\nSorry! You may want to send an email to kconfiglib@gmail.com " \
  2952. "to tell me about this. Include the message above and the stack " \
  2953. "trace and describe what you were doing."
  2954. raise Internal_Error, msg
  2955. if use_psyco:
  2956. import psyco
  2957. Config._tokenize = psyco.proxy(Config._tokenize)
  2958. Config._eval_expr = psyco.proxy(Config._eval_expr)
  2959. _indentation = psyco.proxy(_indentation)
  2960. _get_lines = psyco.proxy(_get_lines)