kconfiglib.py 133 KB

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