kconfiglib.py 137 KB

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