kconfiglib.py 133 KB

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