kconfiglib.py 137 KB

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