kconfiglib.py 133 KB

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