kconfiglib.py 135 KB

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