2
1

kconfiglib.py 135 KB

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