kconfiglib.py 138 KB

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