blob: c7510b2cb266a57391258ed95077d1a54ca924e3 [file] [log] [blame]
Carles Cufi81da97c2018-02-06 11:43:05 +01001# Copyright (c) 2011-2018, Ulf Magnusson
Carles Cufi591eb572018-01-07 15:54:57 +01002# SPDX-License-Identifier: ISC
3
4"""
5Overview
6========
7
8Kconfiglib is a Python 2/3 library for scripting and extracting information
Carles Cufi81da97c2018-02-06 11:43:05 +01009from Kconfig (https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt)
10configuration systems.
Carles Cufi591eb572018-01-07 15:54:57 +010011
Carles Cufi81da97c2018-02-06 11:43:05 +010012See the homepage at https://github.com/ulfalizer/Kconfiglib for a longer
13overview.
Carles Cufi591eb572018-01-07 15:54:57 +010014
15Using Kconfiglib on the Linux kernel with the Makefile targets
16==============================================================
17
18For the Linux kernel, a handy interface is provided by the
Carles Cufi81da97c2018-02-06 11:43:05 +010019scripts/kconfig/Makefile patch, which can be applied with either 'git am' or
20the 'patch' utility:
Carles Cufi591eb572018-01-07 15:54:57 +010021
22 $ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | git am
23 $ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | patch -p1
24
25Warning: Not passing -p1 to patch will cause the wrong file to be patched.
26
27Please tell me if the patch does not apply. It should be trivial to apply
28manually, as it's just a block of text that needs to be inserted near the other
29*conf: targets in scripts/kconfig/Makefile.
30
Carles Cufi81da97c2018-02-06 11:43:05 +010031Look further down for a motivation for the Makefile patch and for instructions
32on how you can use Kconfiglib without it.
33
Carles Cufi591eb572018-01-07 15:54:57 +010034If you do not wish to install Kconfiglib via pip, the Makefile patch is set up
35so that you can also just clone Kconfiglib into the kernel root:
36
37 $ git clone git://github.com/ulfalizer/Kconfiglib.git
38 $ git am Kconfiglib/makefile.patch (or 'patch -p1 < Kconfiglib/makefile.patch')
39
40Warning: The directory name Kconfiglib/ is significant in this case, because
41it's added to PYTHONPATH by the new targets in makefile.patch.
42
Carles Cufi81da97c2018-02-06 11:43:05 +010043The targets added by the Makefile patch are described in the following
44sections.
Carles Cufi591eb572018-01-07 15:54:57 +010045
46
Ulf Magnusson905e65d2018-09-27 17:28:00 +020047make kmenuconfig
48----------------
49
50This target runs the curses menuconfig interface with Python 3 (Python 2 is
51currently not supported for the menuconfig).
52
53
Carles Cufi591eb572018-01-07 15:54:57 +010054make [ARCH=<arch>] iscriptconfig
55--------------------------------
56
57This target gives an interactive Python prompt where a Kconfig instance has
58been preloaded and is available in 'kconf'. To change the Python interpreter
59used, pass PYTHONCMD=<executable> to make. The default is "python".
60
61To get a feel for the API, try evaluating and printing the symbols in
62kconf.defined_syms, and explore the MenuNode menu tree starting at
63kconf.top_node by following 'next' and 'list' pointers.
64
65The item contained in a menu node is found in MenuNode.item (note that this can
Carles Cufi81da97c2018-02-06 11:43:05 +010066be one of the constants kconfiglib.MENU and kconfiglib.COMMENT), and all
67symbols and choices have a 'nodes' attribute containing their menu nodes
68(usually only one). Printing a menu node will print its item, in Kconfig
69format.
Carles Cufi591eb572018-01-07 15:54:57 +010070
71If you want to look up a symbol by name, use the kconf.syms dictionary.
72
73
74make scriptconfig SCRIPT=<script> [SCRIPT_ARG=<arg>]
75----------------------------------------------------
76
77This target runs the Python script given by the SCRIPT parameter on the
78configuration. sys.argv[1] holds the name of the top-level Kconfig file
79(currently always "Kconfig" in practice), and sys.argv[2] holds the SCRIPT_ARG
80argument, if given.
81
82See the examples/ subdirectory for example scripts.
83
84
Ulf Magnusson905e65d2018-09-27 17:28:00 +020085make dumpvarsconfig
86-------------------
87
88This target prints a list of all environment variables referenced from the
89Kconfig files, together with their values. See the
90Kconfiglib/examples/dumpvars.py script.
91
92Only environment variables that are referenced via the Kconfig preprocessor
93$(FOO) syntax are included. The preprocessor was added in Linux 4.18.
94
95
Carles Cufi591eb572018-01-07 15:54:57 +010096Using Kconfiglib without the Makefile targets
97=============================================
98
Ulf Magnusson9f8d4292018-08-29 10:16:51 +020099The make targets are only needed to pick up environment variables exported from
100the Kbuild makefiles and referenced inside Kconfig files, via e.g.
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200101'source "arch/$(SRCARCH)/Kconfig" and commands run via '$(shell,...)'.
Carles Cufi591eb572018-01-07 15:54:57 +0100102
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200103These variables are referenced as of writing (Linux 4.18), together with sample
104values:
Carles Cufi591eb572018-01-07 15:54:57 +0100105
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200106 srctree (.)
107 ARCH (x86)
108 SRCARCH (x86)
109 KERNELVERSION (4.18.0)
110 CC (gcc)
111 HOSTCC (gcc)
112 HOSTCXX (g++)
113 CC_VERSION_TEXT (gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200114
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200115Older kernels only reference ARCH, SRCARCH, and KERNELVERSION.
116
117If your kernel is recent enough (4.18+), you can get a list of referenced
118environment variables via 'make dumpvarsconfig' (see above). Note that this
119command is added by the Makefile patch.
120
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200121To run Kconfiglib without the Makefile patch, set the environment variables
122manually:
123
124 $ srctree=. ARCH=x86 SRCARCH=x86 KERNELVERSION=`make kernelversion` ... python(3)
Carles Cufi591eb572018-01-07 15:54:57 +0100125 >>> import kconfiglib
126 >>> kconf = kconfiglib.Kconfig() # filename defaults to "Kconfig"
127
128Search the top-level Makefile for "Additional ARCH settings" to see other
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200129possibilities for ARCH and SRCARCH.
130
Carles Cufi591eb572018-01-07 15:54:57 +0100131
Carles Cufi591eb572018-01-07 15:54:57 +0100132Intro to symbol values
133======================
134
135Kconfiglib has the same assignment semantics as the C implementation.
136
137Any symbol can be assigned a value by the user (via Kconfig.load_config() or
138Symbol.set_value()), but this user value is only respected if the symbol is
139visible, which corresponds to it (currently) being visible in the menuconfig
140interface.
141
Carles Cufi81da97c2018-02-06 11:43:05 +0100142For symbols with prompts, the visibility of the symbol is determined by the
143condition on the prompt. Symbols without prompts are never visible, so setting
144a user value on them is pointless. A warning will be printed by default if
145Symbol.set_value() is called on a promptless symbol. Assignments to promptless
146symbols are normal within a .config file, so no similar warning will be printed
147by load_config().
Carles Cufi591eb572018-01-07 15:54:57 +0100148
149Dependencies from parents and 'if'/'depends on' are propagated to properties,
150including prompts, so these two configurations are logically equivalent:
151
152(1)
153
154 menu "menu"
155 depends on A
156
157 if B
158
159 config FOO
160 tristate "foo" if D
161 default y
162 depends on C
163
164 endif
165
166 endmenu
167
168(2)
169
170 menu "menu"
171 depends on A
172
173 config FOO
174 tristate "foo" if A && B && C && D
175 default y if A && B && C
176
177 endmenu
178
179In this example, A && B && C && D (the prompt condition) needs to be non-n for
Carles Cufi81da97c2018-02-06 11:43:05 +0100180FOO to be visible (assignable). If its value is m, the symbol can only be
181assigned the value m: The visibility sets an upper bound on the value that can
Carles Cufi591eb572018-01-07 15:54:57 +0100182be assigned by the user, and any higher user value will be truncated down.
183
184'default' properties are independent of the visibility, though a 'default' will
185often get the same condition as the prompt due to dependency propagation.
186'default' properties are used if the symbol is not visible or has no user
187value.
188
Carles Cufi81da97c2018-02-06 11:43:05 +0100189Symbols with no user value (or that have a user value but are not visible) and
190no (active) 'default' default to n for bool/tristate symbols, and to the empty
191string for other symbol types.
Carles Cufi591eb572018-01-07 15:54:57 +0100192
193'select' works similarly to symbol visibility, but sets a lower bound on the
194value of the symbol. The lower bound is determined by the value of the
195select*ing* symbol. 'select' does not respect visibility, so non-visible
196symbols can be forced to a particular (minimum) value by a select as well.
197
198For non-bool/tristate symbols, it only matters whether the visibility is n or
199non-n: m visibility acts the same as y visibility.
200
201Conditions on 'default' and 'select' work in mostly intuitive ways. If the
202condition is n, the 'default' or 'select' is disabled. If it is m, the
203'default' or 'select' value (the value of the selecting symbol) is truncated
204down to m.
205
206When writing a configuration with Kconfig.write_config(), only symbols that are
207visible, have an (active) default, or are selected will get written out (note
208that this includes all symbols that would accept user values). Kconfiglib
209matches the .config format produced by the C implementations down to the
210character. This eases testing.
211
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100212For a visible bool/tristate symbol FOO with value n, this line is written to
213.config:
214
215 # CONFIG_FOO is not set
216
217The point is to remember the user n selection (which might differ from the
218default value the symbol would get), while at the same sticking to the rule
219that undefined corresponds to n (.config uses Makefile format, making the line
220above a comment). When the .config file is read back in, this line will be
221treated the same as the following assignment:
222
223 CONFIG_FOO=n
224
Carles Cufi591eb572018-01-07 15:54:57 +0100225In Kconfiglib, the set of (currently) assignable values for a bool/tristate
226symbol appear in Symbol.assignable. For other symbol types, just check if
Carles Cufi81da97c2018-02-06 11:43:05 +0100227sym.visibility is non-0 (non-n) to see whether the user value will have an
228effect.
Carles Cufi591eb572018-01-07 15:54:57 +0100229
230
231Intro to the menu tree
232======================
233
234The menu structure, as seen in e.g. menuconfig, is represented by a tree of
235MenuNode objects. The top node of the configuration corresponds to an implicit
236top-level menu, the title of which is shown at the top in the standard
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200237menuconfig interface. (The title is also available in Kconfig.mainmenu_text in
238Kconfiglib.)
Carles Cufi591eb572018-01-07 15:54:57 +0100239
240The top node is found in Kconfig.top_node. From there, you can visit child menu
241nodes by following the 'list' pointer, and any following menu nodes by
242following the 'next' pointer. Usually, a non-None 'list' pointer indicates a
243menu or Choice, but menu nodes for symbols can sometimes have a non-None 'list'
244pointer too due to submenus created implicitly from dependencies.
245
246MenuNode.item is either a Symbol or a Choice object, or one of the constants
Carles Cufi81da97c2018-02-06 11:43:05 +0100247MENU and COMMENT. The prompt of the menu node can be found in MenuNode.prompt,
248which also holds the title for menus and comments. For Symbol and Choice,
Carles Cufi591eb572018-01-07 15:54:57 +0100249MenuNode.help holds the help text (if any, otherwise None).
250
Carles Cufi81da97c2018-02-06 11:43:05 +0100251Most symbols will only have a single menu node. A symbol defined in multiple
252locations will have one menu node for each location. The list of menu nodes for
253a Symbol or Choice can be found in the Symbol/Choice.nodes attribute.
254
255Note that prompts and help texts for symbols and choices are stored in their
256menu node(s) rather than in the Symbol or Choice objects themselves. This makes
257it possible to define a symbol in multiple locations with a different prompt or
258help text in each location. To get the help text or prompt for a symbol with a
259single menu node, do sym.nodes[0].help and sym.nodes[0].prompt, respectively.
260The prompt is a (text, condition) tuple, where condition determines the
261visibility (see 'Intro to expressions' below).
Carles Cufi591eb572018-01-07 15:54:57 +0100262
263This organization mirrors the C implementation. MenuNode is called
264'struct menu' there, but I thought "menu" was a confusing name.
265
Carles Cufi591eb572018-01-07 15:54:57 +0100266It is possible to give a Choice a name and define it in multiple locations,
Ulf Magnussone307ba32018-05-16 20:42:40 +0200267hence why Choice.nodes is also a list.
268
269As a convenience, the properties added at a particular definition location are
270available on the MenuNode itself, in e.g. MenuNode.defaults. This is helpful
271when generating documentation, so that symbols/choices defined in multiple
272locations can be shown with the correct properties at each location.
Carles Cufi591eb572018-01-07 15:54:57 +0100273
274
275Intro to expressions
276====================
277
278Expressions can be evaluated with the expr_value() function and printed with
279the expr_str() function (these are used internally as well). Evaluating an
280expression always yields a tristate value, where n, m, and y are represented as
2810, 1, and 2, respectively.
282
283The following table should help you figure out how expressions are represented.
284A, B, C, ... are symbols (Symbol instances), NOT is the kconfiglib.NOT
285constant, etc.
286
287Expression Representation
288---------- --------------
289A A
290"A" A (constant symbol)
291!A (NOT, A)
292A && B (AND, A, B)
293A && B && C (AND, A, (AND, B, C))
294A || B (OR, A, B)
295A || (B && C && D) (OR, A, (AND, B, (AND, C, D)))
296A = B (EQUAL, A, B)
297A != "foo" (UNEQUAL, A, foo (constant symbol))
298A && B = C && D (AND, A, (AND, (EQUAL, B, C), D))
299n Kconfig.n (constant symbol)
300m Kconfig.m (constant symbol)
301y Kconfig.y (constant symbol)
302"y" Kconfig.y (constant symbol)
303
304Strings like "foo" in 'default "foo"' or 'depends on SYM = "foo"' are
305represented as constant symbols, so the only values that appear in expressions
306are symbols***. This mirrors the C implementation.
307
308***For choice symbols, the parent Choice will appear in expressions as well,
309but it's usually invisible as the value interfaces of Symbol and Choice are
310identical. This mirrors the C implementation and makes different choice modes
311"just work".
312
313Manual evaluation examples:
314
315 - The value of A && B is min(A.tri_value, B.tri_value)
316
317 - The value of A || B is max(A.tri_value, B.tri_value)
318
319 - The value of !A is 2 - A.tri_value
320
321 - The value of A = B is 2 (y) if A.str_value == B.str_value, and 0 (n)
322 otherwise. Note that str_value is used here instead of tri_value.
323
324 For constant (as well as undefined) symbols, str_value matches the name of
325 the symbol. This mirrors the C implementation and explains why
326 'depends on SYM = "foo"' above works as expected.
327
328n/m/y are automatically converted to the corresponding constant symbols
329"n"/"m"/"y" (Kconfig.n/m/y) during parsing.
330
331Kconfig.const_syms is a dictionary like Kconfig.syms but for constant symbols.
332
333If a condition is missing (e.g., <cond> when the 'if <cond>' is removed from
334'default A if <cond>'), it is actually Kconfig.y. The standard __str__()
335functions just avoid printing 'if y' conditions to give cleaner output.
336
337
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100338Kconfig extensions
339==================
340
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200341Kconfiglib includes a couple of Kconfig extensions:
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100342
343'source' with relative path
344---------------------------
345
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200346The 'rsource' statement sources Kconfig files with a path relative to directory
347of the Kconfig file containing the 'rsource' statement, instead of relative to
348the project root.
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100349
350Consider following directory tree:
351
352 Project
353 +--Kconfig
354 |
355 +--src
356 +--Kconfig
357 |
358 +--SubSystem1
359 +--Kconfig
360 |
361 +--ModuleA
362 +--Kconfig
363
Ulf Magnussona56be6f2018-08-17 22:27:01 +0200364In this example, assume that src/SubSystem1/Kconfig wants to source
365src/SubSystem1/ModuleA/Kconfig.
366
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200367With 'source', this statement would be used:
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100368
369 source "src/SubSystem1/ModuleA/Kconfig"
370
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200371With 'rsource', this turns into
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100372
373 rsource "ModuleA/Kconfig"
374
Ulf Magnussona56be6f2018-08-17 22:27:01 +0200375If an absolute path is given to 'rsource', it acts the same as 'source'.
376
377'rsource' can be used to create "position-independent" Kconfig trees that can
378be moved around freely.
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100379
380
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200381Globbing 'source'
382-----------------
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100383
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200384'source' and 'rsource' accept glob patterns, sourcing all matching Kconfig
385files. They require at least one matching file, throwing a KconfigError
386otherwise.
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100387
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200388For example, the following statement might source sub1/foofoofoo and
389sub2/foobarfoo:
390
391 source "sub[12]/foo*foo"
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100392
393The glob patterns accepted are the same as for the standard glob.glob()
394function.
395
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200396Two additional statements are provided for cases where it's acceptable for a
397pattern to match no files: 'osource' and 'orsource' (the o is for "optional").
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100398
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200399For example, the following statements will be no-ops if neither "foo" nor any
400files matching "bar*" exist:
401
402 osource "foo"
403 osource "bar*"
404
405'orsource' does a relative optional source.
406
407'source' and 'osource' are analogous to 'include' and '-include' in Make.
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100408
409
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200410Generalized def_* keywords
411--------------------------
412
413def_int, def_hex, and def_string are available in addition to def_bool and
414def_tristate, allowing int, hex, and string symbols to be given a type and a
415default at the same time.
416
417
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +0200418Extra optional warnings
419-----------------------
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200420
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +0200421Some optional warnings can be controlled via environment variables:
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200422
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +0200423 - KCONFIG_WARN_UNDEF: If set to 'y', warnings will be generated for all
424 references to undefined symbols within Kconfig files. The only gotcha is
425 that all hex literals must be prefixed with "0x" or "0X", to make it
426 possible to distinguish them from symbol references.
427
428 Some projects (e.g. the Linux kernel) use multiple Kconfig trees with many
429 shared Kconfig files, leading to some safe undefined symbol references.
430 KCONFIG_WARN_UNDEF is useful in projects that only have a single Kconfig
431 tree though.
432
433 KCONFIG_STRICT is an older alias for this environment variable, supported
434 for backwards compatibility.
435
436 - KCONFIG_WARN_UNDEF_ASSIGN: If set to 'y', warnings will be generated for
437 all assignments to undefined symbols within .config files. By default, no
438 such warnings are generated.
439
440 This warning can also be enabled/disabled via
441 Kconfig.enable/disable_undef_warnings().
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200442
443
444Preprocessor user functions defined in Python
445---------------------------------------------
446
447Preprocessor functions can be defined in Python, which makes it simple to
448integrate information from existing Python tools into Kconfig (e.g. to have
449Kconfig symbols depend on hardware information stored in some other format).
450
451Putting a Python module named kconfigfunctions(.py) anywhere in sys.path will
452cause it to be imported by Kconfiglib (in Kconfig.__init__()). Note that
453sys.path can be customized via PYTHONPATH, and includes the directory of the
454module being run by default, as well as installation directories.
455
456If the KCONFIG_FUNCTIONS environment variable is set, it gives a different
457module name to use instead of 'kconfigfunctions'.
458
459The imported module is expected to define a dictionary named 'functions', with
460the following format:
461
462 functions = {
463 "my-fn": (my_fn, <min.args>, <max.args>/None),
464 "my-other-fn": (my_other_fn, <min.args>, <max.args>/None),
465 ...
466 }
467
468 def my_fn(kconf, name, arg_1, arg_2, ...):
469 # kconf:
470 # Kconfig instance
471 #
472 # name:
473 # Name of the user-defined function ("my-fn"). Think argv[0].
474 #
475 # arg_1, arg_2, ...:
476 # Arguments passed to the function from Kconfig (strings)
477 #
478 # Returns a string to be substituted as the result of calling the
479 # function
480 ...
481
482 def my_other_fn(kconf, name, arg_1, arg_2, ...):
483 ...
484
485 ...
486
487<min.args> and <max.args> are the minimum and maximum number of arguments
488expected by the function (excluding the implicit 'name' argument). If
489<max.args> is None, there is no upper limit to the number of arguments. Passing
490an invalid number of arguments will generate a KconfigError exception.
491
492Once defined, user functions can be called from Kconfig in the same way as
493other preprocessor functions:
494
495 config FOO
496 ...
497 depends on $(my-fn,arg1,arg2)
498
499If my_fn() returns "n", this will result in
500
501 config FOO
502 ...
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +0200503 depends on n
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200504
505Warning
506*******
507
508User-defined preprocessor functions are called as they're encountered at parse
509time, before all Kconfig files have been processed, and before the menu tree
510has been finalized. There are no guarantees that accessing Kconfig symbols or
511the menu tree via the 'kconf' parameter will work, and it could potentially
512lead to a crash. The 'kconf' parameter is provided for future extension (and
513because the predefined functions take it anyway).
514
515Preferably, user-defined functions should be stateless.
516
517
Carles Cufi591eb572018-01-07 15:54:57 +0100518Feedback
519========
520
521Send bug reports, suggestions, and questions to ulfalizer a.t Google's email
522service, or open a ticket on the GitHub page.
523"""
524import errno
Carles Cufi33bbecb2018-01-07 15:56:10 +0100525import glob
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200526import importlib
Carles Cufi591eb572018-01-07 15:54:57 +0100527import os
528import platform
529import re
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200530import subprocess
Carles Cufi591eb572018-01-07 15:54:57 +0100531import sys
Ulf Magnusson4dc9e5b2018-05-16 20:24:03 +0200532import textwrap
Carles Cufi591eb572018-01-07 15:54:57 +0100533
534# File layout:
535#
536# Public classes
537# Public functions
538# Internal functions
539# Public global constants
540# Internal global constants
541
542# Line length: 79 columns
543
544#
545# Public classes
546#
547
548class Kconfig(object):
549 """
550 Represents a Kconfig configuration, e.g. for x86 or ARM. This is the set of
551 symbols, choices, and menu nodes appearing in the configuration. Creating
552 any number of Kconfig objects (including for different architectures) is
553 safe. Kconfiglib doesn't keep any global state.
554
555 The following attributes are available. They should be treated as
556 read-only, and some are implemented through @property magic.
557
558 syms:
559 A dictionary with all symbols in the configuration, indexed by name. Also
560 includes all symbols that are referenced in expressions but never
561 defined, except for constant (quoted) symbols.
562
Sebastian Bøe46239ba2018-03-14 10:36:59 +0100563 Undefined symbols can be recognized by Symbol.nodes being empty -- see
564 the 'Intro to the menu tree' section in the module docstring.
565
Carles Cufi591eb572018-01-07 15:54:57 +0100566 const_syms:
Ulf Magnussone307ba32018-05-16 20:42:40 +0200567 A dictionary like 'syms' for constant (quoted) symbols
Carles Cufi591eb572018-01-07 15:54:57 +0100568
569 named_choices:
Ulf Magnussone307ba32018-05-16 20:42:40 +0200570 A dictionary like 'syms' for named choices (choice FOO)
Carles Cufi591eb572018-01-07 15:54:57 +0100571
572 defined_syms:
573 A list with all defined symbols, in the same order as they appear in the
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200574 Kconfig files. Symbols defined in multiple locations appear multiple
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200575 times.
576
577 Note: You probably want to use 'unique_defined_syms' instead. This
578 attribute is mostly maintained for backwards compatibility.
579
580 unique_defined_syms:
581 A list like 'defined_syms', but with duplicates removed. Just the first
582 instance is kept for symbols defined in multiple locations. Kconfig order
583 is preserved otherwise.
584
585 Using this attribute instead of 'defined_syms' can save work, and
586 automatically gives reasonable behavior when writing configuration output
587 (symbols defined in multiple locations only generate output once, while
588 still preserving Kconfig order for readability).
Ulf Magnussoncb95ea02018-06-07 12:27:37 +0200589
590 choices:
591 A list with all choices, in the same order as they appear in the Kconfig
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200592 files.
593
594 Note: You probably want to use 'unique_choices' instead. This attribute
595 is mostly maintained for backwards compatibility.
596
597 unique_choices:
598 Analogous to 'unique_defined_syms', for choices. Named choices can have
599 multiple definition locations.
Ulf Magnussoncb95ea02018-06-07 12:27:37 +0200600
601 menus:
602 A list with all menus, in the same order as they appear in the Kconfig
603 files
604
605 comments:
606 A list with all comments, in the same order as they appear in the Kconfig
607 files
Carles Cufi591eb572018-01-07 15:54:57 +0100608
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200609 kconfig_filenames:
610 A list with the filenames of all Kconfig files included in the
611 configuration, relative to $srctree (or relative to the current directory
612 if $srctree isn't set).
613
614 The files are listed in the order they are source'd, starting with the
615 top-level Kconfig file. If a file is source'd multiple times, it will
616 appear multiple times. Use set() to get unique filenames.
617
618 Note: Using this for incremental builds is redundant. Kconfig.sync_deps()
619 already indirectly catches any file modifications that change the
620 configuration output.
621
622 env_vars:
623 A set() with the names of all environment variables referenced in the
624 Kconfig files.
625
626 Only environment variables referenced with the preprocessor $(FOO) syntax
627 will be registered. The older $FOO syntax is only supported for backwards
628 compatibility.
629
630 Also note that $(FOO) won't be registered unless the environment variable
631 $FOO is actually set. If it isn't, $(FOO) is an expansion of an unset
632 preprocessor variable (which gives the empty string).
633
634 Another gotcha is that environment variables referenced in the values of
635 recursively expanded preprocessor variables (those defined with =) will
636 only be registered if the variable is actually used (expanded) somewhere.
637
638 The note from the 'kconfig_filenames' documentation applies here too.
639
Carles Cufi591eb572018-01-07 15:54:57 +0100640 n/m/y:
641 The predefined constant symbols n/m/y. Also available in const_syms.
642
643 modules:
644 The Symbol instance for the modules symbol. Currently hardcoded to
645 MODULES, which is backwards compatible. Kconfiglib will warn if
646 'option modules' is set on some other symbol. Tell me if you need proper
647 'option modules' support.
648
649 'modules' is never None. If the MODULES symbol is not explicitly defined,
650 its tri_value will be 0 (n), as expected.
651
652 A simple way to enable modules is to do 'kconf.modules.set_value(2)'
653 (provided the MODULES symbol is defined and visible). Modules are
654 disabled by default in the kernel Kconfig files as of writing, though
655 nearly all defconfig files enable them (with 'CONFIG_MODULES=y').
656
657 defconfig_list:
658 The Symbol instance for the 'option defconfig_list' symbol, or None if no
659 defconfig_list symbol exists. The defconfig filename derived from this
660 symbol can be found in Kconfig.defconfig_filename.
661
662 defconfig_filename:
663 The filename given by the defconfig_list symbol. This is taken from the
664 first 'default' with a satisfied condition where the specified file
665 exists (can be opened for reading). If a defconfig file foo/defconfig is
666 not found and $srctree was set when the Kconfig was created,
667 $srctree/foo/defconfig is looked up as well.
668
Carles Cufi591eb572018-01-07 15:54:57 +0100669 'defconfig_filename' is None if either no defconfig_list symbol exists,
670 or if the defconfig_list symbol has no 'default' with a satisfied
671 condition that specifies a file that exists.
672
673 Gotcha: scripts/kconfig/Makefile might pass --defconfig=<defconfig> to
674 scripts/kconfig/conf when running e.g. 'make defconfig'. This option
675 overrides the defconfig_list symbol, meaning defconfig_filename might not
676 always match what 'make defconfig' would use.
677
678 top_node:
679 The menu node (see the MenuNode class) of the implicit top-level menu.
680 Acts as the root of the menu tree.
681
682 mainmenu_text:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200683 The prompt (title) of the top menu (top_node). Defaults to "Main menu".
684 Can be changed with the 'mainmenu' statement (see kconfig-language.txt).
685
686 variables:
687 A dictionary with all preprocessor variables, indexed by name. See the
688 Variable class.
Carles Cufi591eb572018-01-07 15:54:57 +0100689
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200690 warnings:
691 A list of strings containing all warnings that have been generated. This
692 allows flexibility in how warnings are printed and processed.
693
694 See the 'warn_to_stderr' parameter to Kconfig.__init__() and the
695 Kconfig.enable/disable_stderr_warnings() functions as well. Note that
696 warnings still get added to Kconfig.warnings when 'warn_to_stderr' is
697 True.
698
699 Just as for warnings printed to stderr, only optional warnings that are
700 enabled will get added to Kconfig.warnings. See the various
701 Kconfig.enable/disable_*_warnings() functions.
702
Carles Cufi591eb572018-01-07 15:54:57 +0100703 srctree:
704 The value of the $srctree environment variable when the configuration was
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200705 loaded, or the empty string if $srctree wasn't set. This gives nice
706 behavior with os.path.join(), which treats "" as the current directory,
707 without adding "./".
708
709 Kconfig files are looked up relative to $srctree (unless absolute paths
710 are used), and .config files are looked up relative to $srctree if they
711 are not found in the current directory. This is used to support
712 out-of-tree builds. The C tools use this environment variable in the same
713 way.
Carles Cufi591eb572018-01-07 15:54:57 +0100714
715 Changing $srctree after creating the Kconfig instance has no effect. Only
716 the value when the configuration is loaded matters. This avoids surprises
717 if multiple configurations are loaded with different values for $srctree.
718
719 config_prefix:
720 The value of the $CONFIG_ environment variable when the configuration was
Carles Cufi81da97c2018-02-06 11:43:05 +0100721 loaded. This is the prefix used (and expected) on symbol names in .config
722 files and C headers. Defaults to "CONFIG_". Used in the same way in the C
723 tools.
Carles Cufi591eb572018-01-07 15:54:57 +0100724
725 Like for srctree, only the value of $CONFIG_ when the configuration is
726 loaded matters.
727 """
728 __slots__ = (
Ulf Magnussondc97fc22018-05-02 09:14:18 +0200729 "_encoding",
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200730 "_functions",
731 "_set_match",
732 "_unset_match",
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200733 "_warn_for_no_prompt",
734 "_warn_for_redun_assign",
735 "_warn_for_undef_assign",
736 "_warn_to_stderr",
737 "_warnings_enabled",
Ulf Magnussoncb95ea02018-06-07 12:27:37 +0200738 "choices",
739 "comments",
Carles Cufi591eb572018-01-07 15:54:57 +0100740 "config_prefix",
741 "const_syms",
742 "defconfig_list",
743 "defined_syms",
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200744 "env_vars",
745 "kconfig_filenames",
Carles Cufi591eb572018-01-07 15:54:57 +0100746 "m",
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200747 "mainmenu_text",
Ulf Magnussoncb95ea02018-06-07 12:27:37 +0200748 "menus",
Carles Cufi591eb572018-01-07 15:54:57 +0100749 "modules",
750 "n",
751 "named_choices",
752 "srctree",
753 "syms",
754 "top_node",
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200755 "unique_choices",
756 "unique_defined_syms",
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200757 "variables",
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200758 "warnings",
Carles Cufi591eb572018-01-07 15:54:57 +0100759 "y",
760
761 # Parsing-related
762 "_parsing_kconfigs",
Carles Cufi591eb572018-01-07 15:54:57 +0100763 "_file",
764 "_filename",
765 "_linenr",
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200766 "_include_path",
Carles Cufi591eb572018-01-07 15:54:57 +0100767 "_filestack",
768 "_line",
Carles Cufi591eb572018-01-07 15:54:57 +0100769 "_tokens",
770 "_tokens_i",
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +0200771 "_reuse_tokens",
Carles Cufi591eb572018-01-07 15:54:57 +0100772 )
773
774 #
775 # Public interface
776 #
777
Ulf Magnussondc97fc22018-05-02 09:14:18 +0200778 def __init__(self, filename="Kconfig", warn=True, warn_to_stderr=True,
779 encoding="utf-8"):
Carles Cufi591eb572018-01-07 15:54:57 +0100780 """
Ulf Magnussondc6b0c82018-11-04 01:58:08 +0100781 Creates a new Kconfig object by parsing Kconfig files.
782 Note that Kconfig files are not the same as .config files (which store
783 configuration symbol values).
Carles Cufi591eb572018-01-07 15:54:57 +0100784
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +0200785 See the module docstring for some environment variables that influence
786 default warning settings (KCONFIG_WARN_UNDEF and
787 KCONFIG_WARN_UNDEF_ASSIGN).
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200788
Ulf Magnussondc6b0c82018-11-04 01:58:08 +0100789 Raises KconfigError on syntax errors, and (possibly a subclass of)
790 IOError on IO errors ('errno', 'strerror', and 'filename' are
791 available). Note that IOError can be caught as OSError on Python 3.
792
Carles Cufi591eb572018-01-07 15:54:57 +0100793 filename (default: "Kconfig"):
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200794 The Kconfig file to load. For the Linux kernel, you'll want "Kconfig"
Carles Cufi591eb572018-01-07 15:54:57 +0100795 from the top-level directory, as environment variables will make sure
796 the right Kconfig is included from there (arch/$SRCARCH/Kconfig as of
797 writing).
798
Ulf Magnussona56be6f2018-08-17 22:27:01 +0200799 If $srctree is set, 'filename' will be looked up relative to it.
800 $srctree is also used to look up source'd files within Kconfig files.
801 See the class documentation.
802
Carles Cufi591eb572018-01-07 15:54:57 +0100803 If you are using Kconfiglib via 'make scriptconfig', the filename of
804 the base base Kconfig file will be in sys.argv[1]. It's currently
805 always "Kconfig" in practice.
806
Carles Cufi591eb572018-01-07 15:54:57 +0100807 warn (default: True):
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200808 True if warnings related to this configuration should be generated.
809 This can be changed later with Kconfig.enable/disable_warnings(). It
810 is provided as a constructor argument since warnings might be
811 generated during parsing.
812
813 See the other Kconfig.enable_*_warnings() functions as well, which
814 enable or suppress certain warnings when warnings are enabled.
815
816 All generated warnings are added to the Kconfig.warnings list. See
817 the class documentation.
818
819 warn_to_stderr (default: True):
820 True if warnings should be printed to stderr in addition to being
821 added to Kconfig.warnings.
822
823 This can be changed later with
824 Kconfig.enable/disable_stderr_warnings().
Ulf Magnussondc97fc22018-05-02 09:14:18 +0200825
826 encoding (default: "utf-8"):
827 The encoding to use when reading and writing files. If None, the
828 encoding specified in the current locale will be used.
829
830 The "utf-8" default avoids exceptions on systems that are configured
831 to use the C locale, which implies an ASCII encoding.
832
833 This parameter has no effect on Python 2, due to implementation
834 issues (regular strings turning into Unicode strings, which are
835 distinct in Python 2). Python 2 doesn't decode regular strings
836 anyway.
837
838 Related PEP: https://www.python.org/dev/peps/pep-0538/
Carles Cufi591eb572018-01-07 15:54:57 +0100839 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200840 self.srctree = os.environ.get("srctree", "")
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200841 self.config_prefix = os.environ.get("CONFIG_", "CONFIG_")
Carles Cufi591eb572018-01-07 15:54:57 +0100842
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200843 # Regular expressions for parsing .config files
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200844 self._set_match = _re_match(self.config_prefix + r"([^=]+)=(.*)")
845 self._unset_match = \
846 _re_match(r"# {}([^ ]+) is not set".format(self.config_prefix))
Carles Cufi81da97c2018-02-06 11:43:05 +0100847
Carles Cufi591eb572018-01-07 15:54:57 +0100848
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200849 self.warnings = []
850
851 self._warnings_enabled = warn
852 self._warn_to_stderr = warn_to_stderr
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +0200853 self._warn_for_undef_assign = \
854 os.environ.get("KCONFIG_WARN_UNDEF_ASSIGN") == "y"
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200855 self._warn_for_redun_assign = True
856
Carles Cufi591eb572018-01-07 15:54:57 +0100857
Ulf Magnussondc97fc22018-05-02 09:14:18 +0200858 self._encoding = encoding
859
860
Carles Cufi591eb572018-01-07 15:54:57 +0100861 self.syms = {}
862 self.const_syms = {}
863 self.defined_syms = []
Ulf Magnussoncb95ea02018-06-07 12:27:37 +0200864
Carles Cufi591eb572018-01-07 15:54:57 +0100865 self.named_choices = {}
Ulf Magnussoncb95ea02018-06-07 12:27:37 +0200866 self.choices = []
867
868 self.menus = []
869 self.comments = []
Carles Cufi591eb572018-01-07 15:54:57 +0100870
871 for nmy in "n", "m", "y":
872 sym = Symbol()
873 sym.kconfig = self
874 sym.name = nmy
875 sym.is_constant = True
876 sym.orig_type = TRISTATE
877 sym._cached_tri_val = STR_TO_TRI[nmy]
878
879 self.const_syms[nmy] = sym
880
881 self.n = self.const_syms["n"]
882 self.m = self.const_syms["m"]
883 self.y = self.const_syms["y"]
884
885 # Make n/m/y well-formed symbols
886 for nmy in "n", "m", "y":
887 sym = self.const_syms[nmy]
888 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
889
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200890
891 # Maps preprocessor variables names to Variable instances
892 self.variables = {}
893
894 # Predefined preprocessor functions, with min/max number of arguments
895 self._functions = {
896 "info": (_info_fn, 1, 1),
897 "error-if": (_error_if_fn, 2, 2),
898 "filename": (_filename_fn, 0, 0),
899 "lineno": (_lineno_fn, 0, 0),
900 "shell": (_shell_fn, 1, 1),
901 "warning-if": (_warning_if_fn, 2, 2),
902 }
903
Ulf Magnusson905e65d2018-09-27 17:28:00 +0200904 # Add any user-defined preprocessor functions
905 try:
906 self._functions.update(
907 importlib.import_module(
908 os.environ.get("KCONFIG_FUNCTIONS", "kconfigfunctions")
909 ).functions)
910 except ImportError:
911 pass
912
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200913
Carles Cufi591eb572018-01-07 15:54:57 +0100914 # This is used to determine whether previously unseen symbols should be
915 # registered. They shouldn't be if we parse expressions after parsing,
916 # as part of Kconfig.eval_string().
917 self._parsing_kconfigs = True
918
919 self.modules = self._lookup_sym("MODULES")
920 self.defconfig_list = None
921
Carles Cufi591eb572018-01-07 15:54:57 +0100922 self.top_node = MenuNode()
923 self.top_node.kconfig = self
924 self.top_node.item = MENU
Ulf Magnussondb28a5d2018-04-05 12:02:10 +0200925 self.top_node.is_menuconfig = True
Carles Cufi591eb572018-01-07 15:54:57 +0100926 self.top_node.visibility = self.y
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200927 self.top_node.prompt = ("Main menu", self.y)
Carles Cufi591eb572018-01-07 15:54:57 +0100928 self.top_node.parent = None
929 self.top_node.dep = self.y
Ulf Magnussona56be6f2018-08-17 22:27:01 +0200930 self.top_node.filename = filename
Carles Cufi591eb572018-01-07 15:54:57 +0100931 self.top_node.linenr = 1
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200932 self.top_node.include_path = ()
Carles Cufi591eb572018-01-07 15:54:57 +0100933
934 # Parse the Kconfig files
935
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200936 # Not used internally. Provided as a convenience.
937 self.kconfig_filenames = [filename]
938 self.env_vars = set()
939
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +0200940 # Used to avoid retokenizing lines when we discover that they're not
941 # part of the construct currently being parsed. This is kinda like an
942 # unget operation.
943 self._reuse_tokens = False
Carles Cufi591eb572018-01-07 15:54:57 +0100944
945 # Keeps track of the location in the parent Kconfig files. Kconfig
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200946 # files usually source other Kconfig files. See _enter_file().
Carles Cufi591eb572018-01-07 15:54:57 +0100947 self._filestack = []
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200948 self._include_path = ()
Carles Cufi591eb572018-01-07 15:54:57 +0100949
950 # The current parsing location
Ulf Magnussona56be6f2018-08-17 22:27:01 +0200951 self._filename = filename
Carles Cufi591eb572018-01-07 15:54:57 +0100952 self._linenr = 0
953
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200954 # Open the top-level Kconfig file
Ulf Magnussona56be6f2018-08-17 22:27:01 +0200955 try:
956 self._file = self._open(os.path.join(self.srctree, filename), "r")
957 except IOError as e:
958 if self.srctree:
959 print(textwrap.fill(
960 _INIT_SRCTREE_NOTE.format(self.srctree), 80))
961 raise
Carles Cufi591eb572018-01-07 15:54:57 +0100962
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200963 try:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +0200964 # Parse everything
Ulf Magnussone307ba32018-05-16 20:42:40 +0200965 self._parse_block(None, self.top_node, self.top_node)
Ulf Magnussoncfb3c922018-04-26 18:34:32 +0200966 except UnicodeDecodeError as e:
967 _decoding_error(e, self._filename)
968
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200969 # Close the top-level Kconfig file
970 self._file.close()
971
Carles Cufi591eb572018-01-07 15:54:57 +0100972 self.top_node.list = self.top_node.next
973 self.top_node.next = None
974
975 self._parsing_kconfigs = False
976
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +0200977 self.unique_defined_syms = _ordered_unique(self.defined_syms)
978 self.unique_choices = _ordered_unique(self.choices)
979
Carles Cufi591eb572018-01-07 15:54:57 +0100980 # Do various post-processing of the menu tree
Ulf Magnussone307ba32018-05-16 20:42:40 +0200981 self._finalize_tree(self.top_node, self.y)
Carles Cufi591eb572018-01-07 15:54:57 +0100982
Ulf Magnusson8fc44f22018-04-06 17:20:19 +0200983
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +0200984 # Do sanity checks. Some of these depend on everything being finalized.
985 self._check_sym_sanity()
986 self._check_choice_sanity()
Ulf Magnusson8fc44f22018-04-06 17:20:19 +0200987
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +0200988 # KCONFIG_STRICT is an older alias for KCONFIG_WARN_UNDEF, supported
989 # for backwards compatibility
990 if os.environ.get("KCONFIG_WARN_UNDEF") == "y" or \
991 os.environ.get("KCONFIG_STRICT") == "y":
Ulf Magnusson8fc44f22018-04-06 17:20:19 +0200992
Ulf Magnusson9f8d4292018-08-29 10:16:51 +0200993 self._check_undef_syms()
Ulf Magnusson6686efb2018-08-10 06:04:23 +0200994
Ulf Magnusson8fc44f22018-04-06 17:20:19 +0200995
Ulf Magnusson54a59972018-06-20 00:07:51 +0200996 # Build Symbol._dependents for all symbols and choices
Carles Cufi591eb572018-01-07 15:54:57 +0100997 self._build_dep()
998
Ulf Magnusson54a59972018-06-20 00:07:51 +0200999 # Check for dependency loops
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01001000 check_dep_loop_sym = _check_dep_loop_sym # Micro-optimization
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001001 for sym in self.unique_defined_syms:
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01001002 check_dep_loop_sym(sym, False)
Ulf Magnusson54a59972018-06-20 00:07:51 +02001003
1004 # Add extra dependencies from choices to choice symbols that get
1005 # awkward during dependency loop detection
1006 self._add_choice_deps()
1007
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001008
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001009 self._warn_for_no_prompt = True
Carles Cufi591eb572018-01-07 15:54:57 +01001010
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001011 self.mainmenu_text = self.top_node.prompt[0]
Carles Cufi591eb572018-01-07 15:54:57 +01001012
1013 @property
1014 def defconfig_filename(self):
1015 """
1016 See the class documentation.
1017 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001018 if self.defconfig_list:
1019 for filename, cond in self.defconfig_list.defaults:
1020 if expr_value(cond):
1021 try:
1022 with self._open_config(filename.str_value) as f:
1023 return f.name
1024 except IOError:
1025 continue
Carles Cufi591eb572018-01-07 15:54:57 +01001026
1027 return None
1028
1029 def load_config(self, filename, replace=True):
1030 """
1031 Loads symbol values from a file in the .config format. Equivalent to
1032 calling Symbol.set_value() to set each of the values.
1033
1034 "# CONFIG_FOO is not set" within a .config file sets the user value of
1035 FOO to n. The C tools work the same way.
1036
Carles Cufi81da97c2018-02-06 11:43:05 +01001037 The Symbol.user_value attribute can be inspected afterwards to see what
1038 value the symbol was assigned in the .config file (if any). The user
1039 value might differ from Symbol.str/tri_value if there are unsatisfied
1040 dependencies.
1041
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01001042 Raises (possibly a subclass of) IOError on IO errors ('errno',
1043 'strerror', and 'filename' are available). Note that IOError can be
1044 caught as OSError on Python 3.
1045
Carles Cufi591eb572018-01-07 15:54:57 +01001046 filename:
1047 The file to load. Respects $srctree if set (see the class
1048 documentation).
1049
1050 replace (default: True):
1051 True if all existing user values should be cleared before loading the
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02001052 .config. Pass False to merge configurations.
Carles Cufi591eb572018-01-07 15:54:57 +01001053 """
1054 # Disable the warning about assigning to symbols without prompts. This
1055 # is normal and expected within a .config file.
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001056 self._warn_for_no_prompt = False
Carles Cufi591eb572018-01-07 15:54:57 +01001057
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001058 # This stub only exists to make sure _warn_for_no_prompt gets reenabled
Carles Cufi591eb572018-01-07 15:54:57 +01001059 try:
1060 self._load_config(filename, replace)
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001061 except UnicodeDecodeError as e:
1062 _decoding_error(e, filename)
Carles Cufi591eb572018-01-07 15:54:57 +01001063 finally:
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001064 self._warn_for_no_prompt = True
Carles Cufi591eb572018-01-07 15:54:57 +01001065
1066 def _load_config(self, filename, replace):
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001067 with self._open_config(filename) as f:
Carles Cufi591eb572018-01-07 15:54:57 +01001068 if replace:
1069 # If we're replacing the configuration, keep track of which
1070 # symbols and choices got set so that we can unset the rest
1071 # later. This avoids invalidating everything and is faster.
1072 # Another benefit is that invalidation must be rock solid for
1073 # it to work, making it a good test.
1074
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001075 for sym in self.unique_defined_syms:
Carles Cufi591eb572018-01-07 15:54:57 +01001076 sym._was_set = False
1077
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001078 for choice in self.unique_choices:
Carles Cufi591eb572018-01-07 15:54:57 +01001079 choice._was_set = False
1080
1081 # Small optimizations
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001082 set_match = self._set_match
1083 unset_match = self._unset_match
Carles Cufi591eb572018-01-07 15:54:57 +01001084 syms = self.syms
1085
1086 for linenr, line in enumerate(f, 1):
1087 # The C tools ignore trailing whitespace
1088 line = line.rstrip()
1089
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001090 match = set_match(line)
1091 if match:
1092 name, val = match.groups()
Carles Cufi591eb572018-01-07 15:54:57 +01001093 if name not in syms:
1094 self._warn_undef_assign_load(name, val, filename,
1095 linenr)
1096 continue
1097
1098 sym = syms[name]
1099 if not sym.nodes:
1100 self._warn_undef_assign_load(name, val, filename,
1101 linenr)
1102 continue
1103
1104 if sym.orig_type in (BOOL, TRISTATE):
1105 # The C implementation only checks the first character
1106 # to the right of '=', for whatever reason
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001107 if not ((sym.orig_type is BOOL and
Ulf Magnusson905e65d2018-09-27 17:28:00 +02001108 val.startswith(("n", "y"))) or
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001109 (sym.orig_type is TRISTATE and
Carles Cufi591eb572018-01-07 15:54:57 +01001110 val.startswith(("n", "m", "y")))):
1111 self._warn("'{}' is not a valid value for the {} "
1112 "symbol {}. Assignment ignored."
1113 .format(val, TYPE_TO_STR[sym.orig_type],
Ulf Magnusson4b358752018-03-28 22:26:43 +02001114 _name_and_loc(sym)),
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001115 filename, linenr)
Carles Cufi591eb572018-01-07 15:54:57 +01001116 continue
1117
Carles Cufi8f7fdad2018-02-07 11:32:09 +01001118 val = val[0]
Carles Cufi591eb572018-01-07 15:54:57 +01001119
Carles Cufi8f7fdad2018-02-07 11:32:09 +01001120 if sym.choice and val != "n":
Carles Cufi591eb572018-01-07 15:54:57 +01001121 # During .config loading, we infer the mode of the
1122 # choice from the kind of values that are assigned
1123 # to the choice symbols
1124
1125 prev_mode = sym.choice.user_value
Carles Cufi8f7fdad2018-02-07 11:32:09 +01001126 if prev_mode is not None and \
1127 TRI_TO_STR[prev_mode] != val:
1128
Carles Cufi591eb572018-01-07 15:54:57 +01001129 self._warn("both m and y assigned to symbols "
1130 "within the same choice",
1131 filename, linenr)
1132
1133 # Set the choice's mode
1134 sym.choice.set_value(val)
1135
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001136 elif sym.orig_type is STRING:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001137 match = _conf_string_match(val)
1138 if not match:
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001139 self._warn("malformed string literal in "
Carles Cufi591eb572018-01-07 15:54:57 +01001140 "assignment to {}. Assignment ignored."
Ulf Magnusson4b358752018-03-28 22:26:43 +02001141 .format(_name_and_loc(sym)),
Carles Cufi591eb572018-01-07 15:54:57 +01001142 filename, linenr)
1143 continue
1144
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001145 val = unescape(match.group(1))
Carles Cufi591eb572018-01-07 15:54:57 +01001146
1147 else:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001148 match = unset_match(line)
1149 if not match:
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001150 # Print a warning for lines that match neither
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001151 # set_match() nor unset_match() and that are not blank
1152 # lines or comments. 'line' has already been
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001153 # rstrip()'d, so blank lines show up as "" here.
1154 if line and not line.lstrip().startswith("#"):
1155 self._warn("ignoring malformed line '{}'"
1156 .format(line),
1157 filename, linenr)
1158
Carles Cufi591eb572018-01-07 15:54:57 +01001159 continue
1160
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001161 name = match.group(1)
Carles Cufi591eb572018-01-07 15:54:57 +01001162 if name not in syms:
1163 self._warn_undef_assign_load(name, "n", filename,
1164 linenr)
1165 continue
1166
1167 sym = syms[name]
1168 if sym.orig_type not in (BOOL, TRISTATE):
1169 continue
1170
Carles Cufi8f7fdad2018-02-07 11:32:09 +01001171 val = "n"
Carles Cufi591eb572018-01-07 15:54:57 +01001172
1173 # Done parsing the assignment. Set the value.
1174
1175 if sym._was_set:
Carles Cufi8f7fdad2018-02-07 11:32:09 +01001176 # Use strings for bool/tristate user values in the warning
Carles Cufi591eb572018-01-07 15:54:57 +01001177 if sym.orig_type in (BOOL, TRISTATE):
Carles Cufi591eb572018-01-07 15:54:57 +01001178 display_user_val = TRI_TO_STR[sym.user_value]
1179 else:
Carles Cufi591eb572018-01-07 15:54:57 +01001180 display_user_val = sym.user_value
1181
Carles Cufi81da97c2018-02-06 11:43:05 +01001182 warn_msg = '{} set more than once. Old value: "{}", new value: "{}".'.format(
Ulf Magnusson4b358752018-03-28 22:26:43 +02001183 _name_and_loc(sym), display_user_val, val
Carles Cufi81da97c2018-02-06 11:43:05 +01001184 )
1185
Carles Cufi8f7fdad2018-02-07 11:32:09 +01001186 if display_user_val == val:
Carles Cufi81da97c2018-02-06 11:43:05 +01001187 self._warn_redun_assign(warn_msg, filename, linenr)
1188 else:
1189 self._warn( warn_msg, filename, linenr)
Carles Cufi591eb572018-01-07 15:54:57 +01001190
1191 sym.set_value(val)
1192
1193 if replace:
1194 # If we're replacing the configuration, unset the symbols that
1195 # didn't get set
1196
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001197 for sym in self.unique_defined_syms:
Carles Cufi591eb572018-01-07 15:54:57 +01001198 if not sym._was_set:
1199 sym.unset_value()
1200
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001201 for choice in self.unique_choices:
Carles Cufi591eb572018-01-07 15:54:57 +01001202 if not choice._was_set:
1203 choice.unset_value()
1204
1205 def write_autoconf(self, filename,
1206 header="/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
1207 r"""
1208 Writes out symbol values as a C header file, matching the format used
Carles Cufi81da97c2018-02-06 11:43:05 +01001209 by include/generated/autoconf.h in the kernel.
1210
1211 The ordering of the #defines matches the one generated by
1212 write_config(). The order in the C implementation depends on the hash
1213 table implementation as of writing, and so won't match.
Carles Cufi591eb572018-01-07 15:54:57 +01001214
1215 filename:
1216 Self-explanatory.
1217
1218 header (default: "/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
1219 Text that will be inserted verbatim at the beginning of the file. You
1220 would usually want it enclosed in '/* */' to make it a C comment,
1221 and include a final terminating newline.
1222 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001223 with self._open(filename, "w") as f:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001224 f.write(header)
Carles Cufi591eb572018-01-07 15:54:57 +01001225
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001226 for sym in self.unique_defined_syms:
Ulf Magnussond67095b2018-08-21 22:01:07 +02001227 # Note: _write_to_conf is determined when the value is
1228 # calculated. This is a hidden function call due to
1229 # property magic.
1230 val = sym.str_value
1231 if sym._write_to_conf:
1232 if sym.orig_type in (BOOL, TRISTATE):
1233 if val != "n":
1234 f.write("#define {}{}{} 1\n"
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001235 .format(self.config_prefix, sym.name,
Ulf Magnussond67095b2018-08-21 22:01:07 +02001236 "_MODULE" if val == "m" else ""))
Carles Cufi591eb572018-01-07 15:54:57 +01001237
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001238 elif sym.orig_type is STRING:
Ulf Magnussond67095b2018-08-21 22:01:07 +02001239 f.write('#define {}{} "{}"\n'
1240 .format(self.config_prefix, sym.name,
1241 escape(val)))
Carles Cufi591eb572018-01-07 15:54:57 +01001242
Ulf Magnussond67095b2018-08-21 22:01:07 +02001243 elif sym.orig_type in (INT, HEX):
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001244 if sym.orig_type is HEX and \
Ulf Magnussond67095b2018-08-21 22:01:07 +02001245 not val.startswith(("0x", "0X")):
1246 val = "0x" + val
Carles Cufi591eb572018-01-07 15:54:57 +01001247
Ulf Magnussond67095b2018-08-21 22:01:07 +02001248 f.write("#define {}{} {}\n"
1249 .format(self.config_prefix, sym.name, val))
1250
1251 else:
1252 _internal_error("Internal error while creating C "
1253 'header: unknown type "{}".'
1254 .format(sym.orig_type))
Carles Cufi591eb572018-01-07 15:54:57 +01001255
Carles Cufi591eb572018-01-07 15:54:57 +01001256 def write_config(self, filename,
1257 header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
1258 r"""
Carles Cufi81da97c2018-02-06 11:43:05 +01001259 Writes out symbol values in the .config format. The format matches the
1260 C implementation, including ordering.
1261
1262 Symbols appear in the same order in generated .config files as they do
1263 in the Kconfig files. For symbols defined in multiple locations, a
1264 single assignment is written out corresponding to the first location
1265 where the symbol is defined.
1266
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001267 See the 'Intro to symbol values' section in the module docstring to
Carles Cufi81da97c2018-02-06 11:43:05 +01001268 understand which symbols get written out.
Carles Cufi591eb572018-01-07 15:54:57 +01001269
1270 filename:
1271 Self-explanatory.
1272
1273 header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
1274 Text that will be inserted verbatim at the beginning of the file. You
1275 would usually want each line to start with '#' to make it a comment,
1276 and include a final terminating newline.
1277 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001278 with self._open(filename, "w") as f:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001279 f.write(header)
Carles Cufi591eb572018-01-07 15:54:57 +01001280
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001281 for node in self.node_iter(unique_syms=True):
Ulf Magnussond67095b2018-08-21 22:01:07 +02001282 item = node.item
1283
1284 if isinstance(item, Symbol):
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001285 f.write(item.config_string)
Ulf Magnussond67095b2018-08-21 22:01:07 +02001286
1287 elif expr_value(node.dep) and \
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001288 ((item is MENU and expr_value(node.visibility)) or
1289 item is COMMENT):
Ulf Magnussond67095b2018-08-21 22:01:07 +02001290
1291 f.write("\n#\n# {}\n#\n".format(node.prompt[0]))
1292
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001293 def write_min_config(self, filename,
1294 header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
1295 """
1296 Writes out a "minimal" configuration file, omitting symbols whose value
1297 matches their default value. The format matches the one produced by
1298 'make savedefconfig'.
1299
1300 The resulting configuration file is incomplete, but a complete
1301 configuration can be derived from it by loading it. Minimal
1302 configuration files can serve as a more manageable configuration format
1303 compared to a "full" .config file, especially when configurations files
1304 are merged or edited by hand.
1305
1306 filename:
1307 Self-explanatory.
1308
1309 header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
1310 Text that will be inserted verbatim at the beginning of the file. You
1311 would usually want each line to start with '#' to make it a comment,
1312 and include a final terminating newline.
1313 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001314 with self._open(filename, "w") as f:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001315 f.write(header)
1316
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001317 for sym in self.unique_defined_syms:
Ulf Magnussond67095b2018-08-21 22:01:07 +02001318 # Skip symbols that cannot be changed. Only check
1319 # non-choice symbols, as selects don't affect choice
1320 # symbols.
1321 if not sym.choice and \
1322 sym.visibility <= expr_value(sym.rev_dep):
1323 continue
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001324
Ulf Magnussond67095b2018-08-21 22:01:07 +02001325 # Skip symbols whose value matches their default
1326 if sym.str_value == sym._str_default():
1327 continue
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001328
Ulf Magnussond67095b2018-08-21 22:01:07 +02001329 # Skip symbols that would be selected by default in a
1330 # choice, unless the choice is optional or the symbol type
1331 # isn't bool (it might be possible to set the choice mode
1332 # to n or the symbol to m in those cases).
1333 if sym.choice and \
1334 not sym.choice.is_optional and \
1335 sym.choice._get_selection_from_defaults() is sym and \
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001336 sym.orig_type is BOOL and \
Ulf Magnussond67095b2018-08-21 22:01:07 +02001337 sym.tri_value == 2:
1338 continue
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001339
Ulf Magnussond67095b2018-08-21 22:01:07 +02001340 f.write(sym.config_string)
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001341
1342 def sync_deps(self, path):
1343 """
1344 Creates or updates a directory structure that can be used to avoid
1345 doing a full rebuild whenever the configuration is changed, mirroring
1346 include/config/ in the kernel.
1347
1348 This function is intended to be called during each build, before
1349 compiling source files that depend on configuration symbols.
1350
1351 path:
1352 Path to directory
1353
1354 sync_deps(path) does the following:
1355
1356 1. If the directory <path> does not exist, it is created.
1357
1358 2. If <path>/auto.conf exists, old symbol values are loaded from it,
1359 which are then compared against the current symbol values. If a
1360 symbol has changed value (would generate different output in
1361 autoconf.h compared to before), the change is signaled by
1362 touch'ing a file corresponding to the symbol.
1363
1364 The first time sync_deps() is run on a directory, <path>/auto.conf
1365 won't exist, and no old symbol values will be available. This
1366 logically has the same effect as updating the entire
1367 configuration.
1368
1369 The path to a symbol's file is calculated from the symbol's name
1370 by replacing all '_' with '/' and appending '.h'. For example, the
1371 symbol FOO_BAR_BAZ gets the file <path>/foo/bar/baz.h, and FOO
1372 gets the file <path>/foo.h.
1373
1374 This scheme matches the C tools. The point is to avoid having a
1375 single directory with a huge number of files, which the underlying
1376 filesystem might not handle well.
1377
1378 3. A new auto.conf with the current symbol values is written, to keep
1379 track of them for the next build.
1380
1381
1382 The last piece of the puzzle is knowing what symbols each source file
1383 depends on. Knowing that, dependencies can be added from source files
1384 to the files corresponding to the symbols they depends on. The source
1385 file will then get recompiled (only) when the symbol value changes
1386 (provided sync_deps() is run first during each build).
1387
1388 The tool in the kernel that extracts symbol dependencies from source
1389 files is scripts/basic/fixdep.c. Missing symbol files also correspond
1390 to "not changed", which fixdep deals with by using the $(wildcard) Make
1391 function when adding symbol prerequisites to source files.
1392
1393 In case you need a different scheme for your project, the sync_deps()
1394 implementation can be used as a template."""
1395 if not os.path.exists(path):
1396 os.mkdir(path, 0o755)
1397
1398 # This setup makes sure that at least the current working directory
1399 # gets reset if things fail
1400 prev_dir = os.getcwd()
1401 try:
1402 # cd'ing into the symbol file directory simplifies
1403 # _sync_deps() and saves some work
1404 os.chdir(path)
1405 self._sync_deps()
1406 finally:
1407 os.chdir(prev_dir)
1408
1409 def _sync_deps(self):
1410 # Load old values from auto.conf, if any
1411 self._load_old_vals()
1412
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001413 for sym in self.unique_defined_syms:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001414 # Note: _write_to_conf is determined when the value is
1415 # calculated. This is a hidden function call due to
1416 # property magic.
1417 val = sym.str_value
1418
1419 # Note: n tristate values do not get written to auto.conf and
1420 # autoconf.h, making a missing symbol logically equivalent to n
1421
1422 if sym._write_to_conf:
1423 if sym._old_val is None and \
1424 sym.orig_type in (BOOL, TRISTATE) and \
1425 val == "n":
1426 # No old value (the symbol was missing or n), new value n.
1427 # No change.
1428 continue
1429
1430 if val == sym._old_val:
1431 # New value matches old. No change.
1432 continue
1433
1434 elif sym._old_val is None:
1435 # The symbol wouldn't appear in autoconf.h (because
1436 # _write_to_conf is false), and it wouldn't have appeared in
1437 # autoconf.h previously either (because it didn't appear in
1438 # auto.conf). No change.
1439 continue
1440
1441 # 'sym' has a new value. Flag it.
1442
1443 sym_path = sym.name.lower().replace("_", os.sep) + ".h"
1444 sym_path_dir = os.path.dirname(sym_path)
1445 if sym_path_dir and not os.path.exists(sym_path_dir):
1446 os.makedirs(sym_path_dir, 0o755)
1447
1448 # A kind of truncating touch, mirroring the C tools
1449 os.close(os.open(
1450 sym_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644))
1451
1452 # Remember the current values as the "new old" values.
1453 #
1454 # This call could go anywhere after the call to _load_old_vals(), but
1455 # putting it last means _sync_deps() can be safely rerun if it fails
1456 # before this point.
1457 self._write_old_vals()
1458
1459 def _write_old_vals(self):
1460 # Helper for writing auto.conf. Basically just a simplified
1461 # write_config() that doesn't write any comments (including
1462 # '# CONFIG_FOO is not set' comments). The format matches the C
1463 # implementation, though the ordering is arbitrary there (depends on
1464 # the hash table implementation).
1465 #
1466 # A separate helper function is neater than complicating write_config()
1467 # by passing a flag to it, plus we only need to look at symbols here.
1468
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001469 with self._open("auto.conf", "w") as f:
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001470 for sym in self.unique_defined_syms:
Ulf Magnussond67095b2018-08-21 22:01:07 +02001471 if not (sym.orig_type in (BOOL, TRISTATE) and
1472 not sym.tri_value):
1473 f.write(sym.config_string)
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001474
1475 def _load_old_vals(self):
1476 # Loads old symbol values from auto.conf into a dedicated
1477 # Symbol._old_val field. Mirrors load_config().
1478 #
1479 # The extra field could be avoided with some trickery involving dumping
1480 # symbol values and restoring them later, but this is simpler and
1481 # faster. The C tools also use a dedicated field for this purpose.
1482
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001483 for sym in self.unique_defined_syms:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001484 sym._old_val = None
1485
1486 if not os.path.exists("auto.conf"):
1487 # No old values
1488 return
1489
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001490 with self._open("auto.conf", "r") as f:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001491 for line in f:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001492 match = self._set_match(line)
1493 if not match:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001494 # We only expect CONFIG_FOO=... (and possibly a header
1495 # comment) in auto.conf
1496 continue
1497
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001498 name, val = match.groups()
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001499 if name in self.syms:
1500 sym = self.syms[name]
1501
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001502 if sym.orig_type is STRING:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001503 match = _conf_string_match(val)
1504 if not match:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001505 continue
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001506 val = unescape(match.group(1))
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001507
1508 self.syms[name]._old_val = val
1509
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001510 def node_iter(self, unique_syms=False):
1511 """
1512 Returns a generator for iterating through all MenuNode's in the Kconfig
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02001513 tree. The iteration is done in Kconfig definition order (each node is
1514 visited before its children, and the children of a node are visited
1515 before the next node).
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001516
1517 The Kconfig.top_node menu node is skipped. It contains an implicit menu
1518 that holds the top-level items.
1519
1520 As an example, the following code will produce a list equal to
1521 Kconfig.defined_syms:
1522
1523 defined_syms = [node.item for node in kconf.node_iter()
1524 if isinstance(node.item, Symbol)]
1525
1526 unique_syms (default: False):
1527 If True, only the first MenuNode will be included for symbols defined
1528 in multiple locations.
1529
1530 Using kconf.node_iter(True) in the example above would give a list
1531 equal to unique_defined_syms.
1532 """
1533 if unique_syms:
1534 for sym in self.unique_defined_syms:
1535 sym._visited = False
1536
1537 node = self.top_node
1538 while 1:
1539 # Jump to the next node with an iterative tree walk
1540 if node.list:
1541 node = node.list
1542 elif node.next:
1543 node = node.next
1544 else:
1545 while node.parent:
1546 node = node.parent
1547 if node.next:
1548 node = node.next
1549 break
1550 else:
1551 # No more nodes
1552 return
1553
1554 if unique_syms and isinstance(node.item, Symbol):
1555 if node.item._visited:
1556 continue
1557 node.item._visited = True
1558
1559 yield node
1560
Carles Cufi591eb572018-01-07 15:54:57 +01001561 def eval_string(self, s):
1562 """
1563 Returns the tristate value of the expression 's', represented as 0, 1,
Ulf Magnusson54a59972018-06-20 00:07:51 +02001564 and 2 for n, m, and y, respectively. Raises KconfigError if syntax
1565 errors are detected in 's'. Warns if undefined symbols are referenced.
Carles Cufi591eb572018-01-07 15:54:57 +01001566
1567 As an example, if FOO and BAR are tristate symbols at least one of
1568 which has the value y, then config.eval_string("y && (FOO || BAR)")
1569 returns 2 (y).
1570
1571 To get the string value of non-bool/tristate symbols, use
1572 Symbol.str_value. eval_string() always returns a tristate value, and
1573 all non-bool/tristate symbols have the tristate value 0 (n).
1574
1575 The expression parsing is consistent with how parsing works for
1576 conditional ('if ...') expressions in the configuration, and matches
1577 the C implementation. m is rewritten to 'm && MODULES', so
1578 eval_string("m") will return 0 (n) unless modules are enabled.
1579 """
1580 # The parser is optimized to be fast when parsing Kconfig files (where
1581 # an expression can never appear at the beginning of a line). We have
1582 # to monkey-patch things a bit here to reuse it.
1583
1584 self._filename = None
1585
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001586 # Don't include the "if " from below to avoid giving confusing error
1587 # messages
Carles Cufi591eb572018-01-07 15:54:57 +01001588 self._line = s
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001589 # [1:] removes the _T_IF token
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001590 self._tokens = self._tokenize("if " + s)[1:]
1591 self._tokens_i = -1
Carles Cufi591eb572018-01-07 15:54:57 +01001592
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001593 return expr_value(self._expect_expr_and_eol()) # transform_m
Carles Cufi591eb572018-01-07 15:54:57 +01001594
1595 def unset_values(self):
1596 """
1597 Resets the user values of all symbols, as if Kconfig.load_config() or
1598 Symbol.set_value() had never been called.
1599 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001600 self._warn_for_no_prompt = False
Carles Cufi591eb572018-01-07 15:54:57 +01001601 try:
1602 # set_value() already rejects undefined symbols, and they don't
1603 # need to be invalidated (because their value never changes), so we
1604 # can just iterate over defined symbols
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001605 for sym in self.unique_defined_syms:
Carles Cufi591eb572018-01-07 15:54:57 +01001606 sym.unset_value()
1607
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001608 for choice in self.unique_choices:
Carles Cufi591eb572018-01-07 15:54:57 +01001609 choice.unset_value()
1610 finally:
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001611 self._warn_for_no_prompt = True
Carles Cufi591eb572018-01-07 15:54:57 +01001612
1613 def enable_warnings(self):
1614 """
1615 See Kconfig.__init__().
1616 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001617 self._warnings_enabled = True
Carles Cufi591eb572018-01-07 15:54:57 +01001618
1619 def disable_warnings(self):
1620 """
1621 See Kconfig.__init__().
1622 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001623 self._warnings_enabled = False
1624
1625 def enable_stderr_warnings(self):
1626 """
1627 See Kconfig.__init__().
1628 """
1629 self._warn_to_stderr = True
1630
1631 def disable_stderr_warnings(self):
1632 """
1633 See Kconfig.__init__().
1634 """
1635 self._warn_to_stderr = False
Carles Cufi591eb572018-01-07 15:54:57 +01001636
1637 def enable_undef_warnings(self):
1638 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001639 Enables warnings for assignments to undefined symbols. Disabled by
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02001640 default unless the KCONFIG_WARN_UNDEF_ASSIGN environment variable was
1641 set to 'y' when the Kconfig instance was created.
Carles Cufi591eb572018-01-07 15:54:57 +01001642 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001643 self._warn_for_undef_assign = True
Carles Cufi591eb572018-01-07 15:54:57 +01001644
1645 def disable_undef_warnings(self):
1646 """
1647 See enable_undef_assign().
1648 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001649 self._warn_for_undef_assign = False
Carles Cufi591eb572018-01-07 15:54:57 +01001650
Carles Cufi81da97c2018-02-06 11:43:05 +01001651 def enable_redun_warnings(self):
1652 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001653 Enables warnings for duplicated assignments in .config files that all
1654 set the same value.
1655
1656 These warnings are enabled by default. Disabling them might be helpful
1657 in certain cases when merging configurations.
Carles Cufi81da97c2018-02-06 11:43:05 +01001658 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001659 self._warn_for_redun_assign = True
Carles Cufi81da97c2018-02-06 11:43:05 +01001660
1661 def disable_redun_warnings(self):
1662 """
1663 See enable_redun_warnings().
1664 """
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001665 self._warn_for_redun_assign = False
Carles Cufi81da97c2018-02-06 11:43:05 +01001666
Carles Cufi591eb572018-01-07 15:54:57 +01001667 def __repr__(self):
1668 """
1669 Returns a string with information about the Kconfig object when it is
1670 evaluated on e.g. the interactive Python prompt.
1671 """
1672 return "<{}>".format(", ".join((
1673 "configuration with {} symbols".format(len(self.syms)),
1674 'main menu prompt "{}"'.format(self.mainmenu_text),
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001675 "srctree is current directory" if not self.srctree else
Carles Cufi591eb572018-01-07 15:54:57 +01001676 'srctree "{}"'.format(self.srctree),
1677 'config symbol prefix "{}"'.format(self.config_prefix),
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001678 "warnings " +
1679 ("enabled" if self._warnings_enabled else "disabled"),
1680 "printing of warnings to stderr " +
1681 ("enabled" if self._warn_to_stderr else "disabled"),
Carles Cufi591eb572018-01-07 15:54:57 +01001682 "undef. symbol assignment warnings " +
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001683 ("enabled" if self._warn_for_undef_assign else "disabled"),
Carles Cufi81da97c2018-02-06 11:43:05 +01001684 "redundant symbol assignment warnings " +
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02001685 ("enabled" if self._warn_for_redun_assign else "disabled")
Carles Cufi591eb572018-01-07 15:54:57 +01001686 )))
1687
1688 #
1689 # Private methods
1690 #
1691
1692
1693 #
1694 # File reading
1695 #
1696
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001697 def _open_config(self, filename):
1698 # Opens a .config file. First tries to open 'filename', then
1699 # '$srctree/filename' if $srctree was set when the configuration was
1700 # loaded.
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001701
Carles Cufi591eb572018-01-07 15:54:57 +01001702 try:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001703 return self._open(filename, "r")
Carles Cufi591eb572018-01-07 15:54:57 +01001704 except IOError as e:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001705 # This will try opening the same file twice if $srctree is unset,
1706 # but it's not a big deal
1707 try:
1708 return self._open(os.path.join(self.srctree, filename), "r")
1709 except IOError as e2:
1710 # This is needed for Python 3, because e2 is deleted after
1711 # the try block:
1712 #
1713 # https://docs.python.org/3/reference/compound_stmts.html#the-try-statement
1714 e = e2
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001715
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01001716 raise _KconfigIOError(e, "\n" + textwrap.fill(
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001717 "Could not open '{}' ({}: {}){}".format(
1718 filename, errno.errorcode[e.errno], e.strerror,
1719 self._srctree_hint()),
Ulf Magnusson4dc9e5b2018-05-16 20:24:03 +02001720 80))
Carles Cufi591eb572018-01-07 15:54:57 +01001721
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001722 def _enter_file(self, full_filename, rel_filename):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001723 # Jumps to the beginning of a sourced Kconfig file, saving the previous
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001724 # position and file object.
1725 #
1726 # full_filename:
1727 # Actual path to the file.
1728 #
1729 # rel_filename:
1730 # File path with $srctree prefix stripped, stored in e.g.
1731 # self._filename (which makes it indirectly show up in
1732 # MenuNode.filename). Equals full_filename for absolute paths.
1733
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02001734 self.kconfig_filenames.append(rel_filename)
1735
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001736 # The parent Kconfig files are represented as a list of
1737 # (<include path>, <Python 'file' object for Kconfig file>) tuples.
1738 #
1739 # <include path> is immutable and holds a *tuple* of
1740 # (<filename>, <linenr>) tuples, giving the locations of the 'source'
1741 # statements in the parent Kconfig files. The current include path is
1742 # also available in Kconfig._include_path.
1743 #
1744 # The point of this redundant setup is to allow Kconfig._include_path
1745 # to be assigned directly to MenuNode.include_path without having to
1746 # copy it, sharing it wherever possible.
1747
1748 # Save include path and 'file' object before entering the file
1749 self._filestack.append((self._include_path, self._file))
1750
1751 # _include_path is a tuple, so this rebinds the variable instead of
1752 # doing in-place modification
1753 self._include_path += ((self._filename, self._linenr),)
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001754
Carles Cufi81da97c2018-02-06 11:43:05 +01001755 # Check for recursive 'source'
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001756 for name, _ in self._include_path:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001757 if name == rel_filename:
Ulf Magnusson54a59972018-06-20 00:07:51 +02001758 raise KconfigError(
Carles Cufi81da97c2018-02-06 11:43:05 +01001759 "\n{}:{}: Recursive 'source' of '{}' detected. Check that "
1760 "environment variables are set correctly.\n"
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001761 "Include path:\n{}"
1762 .format(self._filename, self._linenr, rel_filename,
Carles Cufi81da97c2018-02-06 11:43:05 +01001763 "\n".join("{}:{}".format(name, linenr)
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001764 for name, linenr in self._include_path)))
Carles Cufi81da97c2018-02-06 11:43:05 +01001765
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001766 # Note: We already know that the file exists
Carles Cufi591eb572018-01-07 15:54:57 +01001767
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001768 try:
1769 self._file = self._open(full_filename, "r")
1770 except IOError as e:
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01001771 raise _KconfigIOError(
1772 e, "{}:{}: Could not open '{}' ({}: {})"
1773 .format(self._filename, self._linenr, full_filename,
1774 errno.errorcode[e.errno], e.strerror))
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001775
1776 self._filename = rel_filename
Carles Cufi591eb572018-01-07 15:54:57 +01001777 self._linenr = 0
1778
1779 def _leave_file(self):
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001780 # Returns from a Kconfig file to the file that sourced it. See
1781 # _enter_file().
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001782
Carles Cufi591eb572018-01-07 15:54:57 +01001783 self._file.close()
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02001784 # Restore location from parent Kconfig file
1785 self._filename, self._linenr = self._include_path[-1]
1786 # Restore include path and 'file' object
1787 self._include_path, self._file = self._filestack.pop()
Carles Cufi591eb572018-01-07 15:54:57 +01001788
1789 def _next_line(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001790 # Fetches and tokenizes the next line from the current Kconfig file.
1791 # Returns False at EOF and True otherwise.
1792
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02001793 # We might already have tokens from parsing a line and discovering that
1794 # it's part of a different construct
1795 if self._reuse_tokens:
1796 self._reuse_tokens = False
1797 self._tokens_i = -1
1798 return True
1799
1800 # Note: readline() returns '' over and over at EOF, which we rely on
1801 # for help texts at the end of files (see _line_after_help())
1802 self._line = self._file.readline()
1803 if not self._line:
1804 return False
1805 self._linenr += 1
Carles Cufi591eb572018-01-07 15:54:57 +01001806
Carles Cufi591eb572018-01-07 15:54:57 +01001807 # Handle line joining
1808 while self._line.endswith("\\\n"):
1809 self._line = self._line[:-2] + self._file.readline()
1810 self._linenr += 1
1811
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001812 self._tokens = self._tokenize(self._line)
1813 self._tokens_i = -1 # Token index (minus one)
1814
Carles Cufi591eb572018-01-07 15:54:57 +01001815 return True
1816
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02001817 def _line_after_help(self, line):
1818 # Tokenizes the line after a help text. This case is special in that
1819 # the line has already been fetched (to discover that it isn't part of
1820 # the help text).
1821 #
1822 # An earlier version used a _saved_line variable instead that was
1823 # checked in _next_line(). This special-casing gets rid of it and makes
1824 # _reuse_tokens alone sufficient to handle unget.
1825
1826 if line:
1827 # Handle line joining
1828 while line.endswith("\\\n"):
1829 line = line[:-2] + self._file.readline()
1830 self._linenr += 1
1831
1832 self._line = line
1833
1834 self._tokens = self._tokenize(line)
1835 self._reuse_tokens = True
1836
Carles Cufi591eb572018-01-07 15:54:57 +01001837
1838 #
1839 # Tokenization
1840 #
1841
1842 def _lookup_sym(self, name):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001843 # Fetches the symbol 'name' from the symbol table, creating and
1844 # registering it if it does not exist. If '_parsing_kconfigs' is False,
1845 # it means we're in eval_string(), and new symbols won't be registered.
1846
Carles Cufi591eb572018-01-07 15:54:57 +01001847 if name in self.syms:
1848 return self.syms[name]
1849
1850 sym = Symbol()
1851 sym.kconfig = self
1852 sym.name = name
1853 sym.is_constant = False
1854 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
1855
1856 if self._parsing_kconfigs:
1857 self.syms[name] = sym
1858 else:
1859 self._warn("no symbol {} in configuration".format(name))
1860
1861 return sym
1862
1863 def _lookup_const_sym(self, name):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001864 # Like _lookup_sym(), for constant (quoted) symbols
1865
Carles Cufi591eb572018-01-07 15:54:57 +01001866 if name in self.const_syms:
1867 return self.const_syms[name]
1868
1869 sym = Symbol()
1870 sym.kconfig = self
1871 sym.name = name
1872 sym.is_constant = True
1873 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
1874
1875 if self._parsing_kconfigs:
1876 self.const_syms[name] = sym
1877
1878 return sym
1879
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001880 def _tokenize(self, s):
1881 # Parses 's', returning a None-terminated list of tokens. Registers any
1882 # new symbols encountered with _lookup(_const)_sym().
Sebastian Bøe46239ba2018-03-14 10:36:59 +01001883 #
1884 # Tries to be reasonably speedy by processing chunks of text via
1885 # regexes and string operations where possible. This is the biggest
1886 # hotspot during parsing.
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001887 #
1888 # Note: It might be possible to rewrite this to 'yield' tokens instead,
1889 # working across multiple lines. The 'option env' lookback thing below
1890 # complicates things though.
Carles Cufi591eb572018-01-07 15:54:57 +01001891
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001892 # Initial token on the line
1893 match = _command_match(s)
1894 if not match:
1895 if s.isspace() or s.lstrip().startswith("#"):
1896 return (None,)
1897 self._parse_error("unknown token at start of line")
Carles Cufi591eb572018-01-07 15:54:57 +01001898
Carles Cufi81da97c2018-02-06 11:43:05 +01001899 # Tricky implementation detail: While parsing a token, 'token' refers
1900 # to the previous token. See _STRING_LEX for why this is needed.
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001901 token = _get_keyword(match.group(1))
1902 if not token:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02001903 # Backwards compatibility with old versions of the C tools, which
1904 # (accidentally) accepted stuff like "--help--" and "-help---".
1905 # This was fixed in the C tools by commit c2264564 ("kconfig: warn
1906 # of unhandled characters in Kconfig commands"), committed in July
1907 # 2015, but it seems people still run Kconfiglib on older kernels.
1908 if s.strip(" \t\n-") == "help":
1909 return (_T_HELP, None)
1910
1911 # If the first token is not a keyword (and not a weird help token),
1912 # we have a preprocessor variable assignment (or a bare macro on a
1913 # line)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001914 self._parse_assignment(s)
1915 return (None,)
Carles Cufi591eb572018-01-07 15:54:57 +01001916
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001917 tokens = [token]
Carles Cufi591eb572018-01-07 15:54:57 +01001918 # The current index in the string being tokenized
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001919 i = match.end()
Carles Cufi591eb572018-01-07 15:54:57 +01001920
1921 # Main tokenization loop (for tokens past the first one)
1922 while i < len(s):
1923 # Test for an identifier/keyword first. This is the most common
1924 # case.
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001925 match = _id_keyword_match(s, i)
1926 if match:
Carles Cufi591eb572018-01-07 15:54:57 +01001927 # We have an identifier or keyword
1928
Carles Cufi591eb572018-01-07 15:54:57 +01001929 # Check what it is. lookup_sym() will take care of allocating
1930 # new symbols for us the first time we see them. Note that
1931 # 'token' still refers to the previous token.
1932
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001933 name = match.group(1)
Carles Cufi591eb572018-01-07 15:54:57 +01001934 keyword = _get_keyword(name)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001935 if keyword:
Carles Cufi591eb572018-01-07 15:54:57 +01001936 # It's a keyword
1937 token = keyword
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001938 # Jump past it
1939 i = match.end()
Carles Cufi591eb572018-01-07 15:54:57 +01001940
1941 elif token not in _STRING_LEX:
Carles Cufi81da97c2018-02-06 11:43:05 +01001942 # It's a non-const symbol, except we translate n, m, and y
1943 # into the corresponding constant symbols, like the C
1944 # implementation
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001945
1946 if "$" in name:
1947 # Macro expansion within symbol name
1948 name, s, i = self._expand_name(s, i)
1949 else:
1950 i = match.end()
1951
Carles Cufi81da97c2018-02-06 11:43:05 +01001952 token = self.const_syms[name] \
1953 if name in ("n", "m", "y") else \
1954 self._lookup_sym(name)
Carles Cufi591eb572018-01-07 15:54:57 +01001955
1956 else:
1957 # It's a case of missing quotes. For example, the
1958 # following is accepted:
1959 #
1960 # menu unquoted_title
1961 #
1962 # config A
1963 # tristate unquoted_prompt
1964 #
1965 # endmenu
1966 token = name
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001967 i = match.end()
Carles Cufi591eb572018-01-07 15:54:57 +01001968
1969 else:
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001970 # Neither a keyword nor a non-const symbol
Carles Cufi591eb572018-01-07 15:54:57 +01001971
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001972 # We always strip whitespace after tokens, so it is safe to
1973 # assume that s[i] is the start of a token here.
Carles Cufi591eb572018-01-07 15:54:57 +01001974 c = s[i]
Carles Cufi591eb572018-01-07 15:54:57 +01001975
1976 if c in "\"'":
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001977 s, end_i = self._expand_str(s, i)
Carles Cufi591eb572018-01-07 15:54:57 +01001978
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001979 # os.path.expandvars() and the $UNAME_RELEASE replace() is
1980 # a backwards compatibility hack, which should be
1981 # reasonably safe as expandvars() leaves references to
1982 # undefined env. vars. as is.
1983 #
1984 # The preprocessor functionality changed how environment
1985 # variables are referenced, to $(FOO).
1986 val = os.path.expandvars(
1987 s[i + 1:end_i - 1].replace("$UNAME_RELEASE",
1988 platform.uname()[2]))
Carles Cufi591eb572018-01-07 15:54:57 +01001989
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02001990 i = end_i
Carles Cufi591eb572018-01-07 15:54:57 +01001991
1992 # This is the only place where we don't survive with a
1993 # single token of lookback: 'option env="FOO"' does not
1994 # refer to a constant symbol named "FOO".
1995 token = val \
1996 if token in _STRING_LEX or \
Ulf Magnusson213a88f2018-09-05 12:24:45 +02001997 tokens[0] is _T_OPTION else \
Carles Cufi591eb572018-01-07 15:54:57 +01001998 self._lookup_const_sym(val)
1999
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002000 elif s.startswith("&&", i):
Carles Cufi591eb572018-01-07 15:54:57 +01002001 token = _T_AND
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002002 i += 2
Carles Cufi591eb572018-01-07 15:54:57 +01002003
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002004 elif s.startswith("||", i):
Carles Cufi591eb572018-01-07 15:54:57 +01002005 token = _T_OR
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002006 i += 2
Carles Cufi591eb572018-01-07 15:54:57 +01002007
2008 elif c == "=":
2009 token = _T_EQUAL
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002010 i += 1
2011
2012 elif s.startswith("!=", i):
2013 token = _T_UNEQUAL
2014 i += 2
2015
2016 elif c == "!":
2017 token = _T_NOT
2018 i += 1
Carles Cufi591eb572018-01-07 15:54:57 +01002019
2020 elif c == "(":
2021 token = _T_OPEN_PAREN
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002022 i += 1
Carles Cufi591eb572018-01-07 15:54:57 +01002023
2024 elif c == ")":
2025 token = _T_CLOSE_PAREN
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002026 i += 1
2027
Carles Cufi591eb572018-01-07 15:54:57 +01002028 elif c == "#":
2029 break
2030
Carles Cufi591eb572018-01-07 15:54:57 +01002031
2032 # Very rare
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002033
2034 elif s.startswith("<=", i):
2035 token = _T_LESS_EQUAL
2036 i += 2
2037
2038 elif c == "<":
2039 token = _T_LESS
2040 i += 1
2041
2042 elif s.startswith(">=", i):
2043 token = _T_GREATER_EQUAL
2044 i += 2
2045
Carles Cufi591eb572018-01-07 15:54:57 +01002046 elif c == ">":
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002047 token = _T_GREATER
2048 i += 1
2049
Carles Cufi591eb572018-01-07 15:54:57 +01002050
2051 else:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002052 self._parse_error("unknown tokens in line")
2053
Carles Cufi591eb572018-01-07 15:54:57 +01002054
2055 # Skip trailing whitespace
2056 while i < len(s) and s[i].isspace():
2057 i += 1
2058
Carles Cufi591eb572018-01-07 15:54:57 +01002059
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002060 # Add the token
2061 tokens.append(token)
2062
2063 # None-terminating the token list makes the token fetching functions
Carles Cufi591eb572018-01-07 15:54:57 +01002064 # simpler/faster
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002065 tokens.append(None)
2066
2067 return tokens
Carles Cufi591eb572018-01-07 15:54:57 +01002068
2069 def _next_token(self):
2070 self._tokens_i += 1
2071 return self._tokens[self._tokens_i]
2072
2073 def _peek_token(self):
2074 return self._tokens[self._tokens_i + 1]
2075
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002076 # The functions below are just _next_token() and _parse_expr() with extra
2077 # syntax checking. Inlining _next_token() and _peek_token() into them saves
2078 # a few % of parsing time.
Carles Cufi81da97c2018-02-06 11:43:05 +01002079 #
2080 # See the 'Intro to expressions' section for what a constant symbol is.
2081
2082 def _expect_sym(self):
2083 self._tokens_i += 1
2084 token = self._tokens[self._tokens_i]
2085
2086 if not isinstance(token, Symbol):
2087 self._parse_error("expected symbol")
2088
2089 return token
2090
2091 def _expect_nonconst_sym(self):
2092 self._tokens_i += 1
2093 token = self._tokens[self._tokens_i]
2094
2095 if not isinstance(token, Symbol) or token.is_constant:
2096 self._parse_error("expected nonconstant symbol")
2097
2098 return token
2099
2100 def _expect_nonconst_sym_and_eol(self):
2101 self._tokens_i += 1
2102 token = self._tokens[self._tokens_i]
2103
2104 if not isinstance(token, Symbol) or token.is_constant:
2105 self._parse_error("expected nonconstant symbol")
2106
2107 if self._tokens[self._tokens_i + 1] is not None:
2108 self._parse_error("extra tokens at end of line")
2109
2110 return token
2111
2112 def _expect_str(self):
2113 self._tokens_i += 1
2114 token = self._tokens[self._tokens_i]
2115
2116 if not isinstance(token, str):
2117 self._parse_error("expected string")
2118
2119 return token
2120
2121 def _expect_str_and_eol(self):
2122 self._tokens_i += 1
2123 token = self._tokens[self._tokens_i]
2124
2125 if not isinstance(token, str):
2126 self._parse_error("expected string")
2127
2128 if self._tokens[self._tokens_i + 1] is not None:
2129 self._parse_error("extra tokens at end of line")
2130
2131 return token
2132
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002133 def _expect_expr_and_eol(self):
2134 expr = self._parse_expr(True)
2135
2136 if self._peek_token() is not None:
2137 self._parse_error("extra tokens at end of line")
2138
2139 return expr
2140
Carles Cufi591eb572018-01-07 15:54:57 +01002141 def _check_token(self, token):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002142 # If the next token is 'token', removes it and returns True
2143
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002144 if self._tokens[self._tokens_i + 1] is token:
Carles Cufi591eb572018-01-07 15:54:57 +01002145 self._tokens_i += 1
2146 return True
2147 return False
2148
2149
2150 #
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002151 # Preprocessor logic
2152 #
2153
2154 def _parse_assignment(self, s):
2155 # Parses a preprocessor variable assignment, registering the variable
2156 # if it doesn't already exist. Also takes care of bare macros on lines
2157 # (which are allowed, and can be useful for their side effects).
2158
2159 # Expand any macros in the left-hand side of the assignment (the
2160 # variable name)
2161 s = s.lstrip()
2162 i = 0
2163 while 1:
2164 i = _assignment_lhs_fragment_match(s, i).end()
2165 if s.startswith("$(", i):
2166 s, i = self._expand_macro(s, i, ())
2167 else:
2168 break
2169
2170 if s.isspace():
2171 # We also accept a bare macro on a line (e.g.
2172 # $(warning-if,$(foo),ops)), provided it expands to a blank string
2173 return
2174
2175 # Assigned variable
2176 name = s[:i]
2177
2178
2179 # Extract assignment operator (=, :=, or +=) and value
2180 rhs_match = _assignment_rhs_match(s, i)
2181 if not rhs_match:
2182 self._parse_error("syntax error")
2183
2184 op, val = rhs_match.groups()
2185
2186
2187 if name in self.variables:
2188 # Already seen variable
2189 var = self.variables[name]
2190 else:
2191 # New variable
2192 var = Variable()
2193 var.kconfig = self
2194 var.name = name
2195 var._n_expansions = 0
2196 self.variables[name] = var
2197
2198 # += acts like = on undefined variables (defines a recursive
2199 # variable)
2200 if op == "+=":
2201 op = "="
2202
2203 if op == "=":
2204 var.is_recursive = True
2205 var.value = val
2206 elif op == ":=":
2207 var.is_recursive = False
2208 var.value = self._expand_whole(val, ())
2209 else: # op == "+="
2210 # += does immediate expansion if the variable was last set
2211 # with :=
Ulf Magnusson905e65d2018-09-27 17:28:00 +02002212 var.value += " " + (val if var.is_recursive else
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002213 self._expand_whole(val, ()))
2214
2215 def _expand_whole(self, s, args):
2216 # Expands preprocessor macros in all of 's'. Used whenever we don't
2217 # have to worry about delimiters. See _expand_macro() re. the 'args'
2218 # parameter.
2219 #
2220 # Returns the expanded string.
2221
2222 i = 0
2223 while 1:
2224 i = s.find("$(", i)
2225 if i == -1:
2226 break
2227 s, i = self._expand_macro(s, i, args)
2228 return s
2229
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002230 def _expand_name(self, s, i):
2231 # Expands a symbol name starting at index 'i' in 's'.
2232 #
2233 # Returns the expanded name, the expanded 's' (including the part
2234 # before the name), and the index of the first character in the next
2235 # token after the name.
2236
2237 s, end_i = self._expand_name_iter(s, i)
2238 name = s[i:end_i]
2239 # isspace() is False for empty strings
2240 if not name.strip():
2241 # Avoid creating a Kconfig symbol with a blank name. It's almost
2242 # guaranteed to be an error.
2243 self._parse_error("macro expanded to blank string")
2244
2245 # Skip trailing whitespace
2246 while end_i < len(s) and s[end_i].isspace():
2247 end_i += 1
2248
2249 return name, s, end_i
2250
2251 def _expand_name_iter(self, s, i):
2252 # Expands a symbol name starting at index 'i' in 's'.
2253 #
2254 # Returns the expanded 's' (including the part before the name) and the
2255 # index of the first character after the expanded name in 's'.
2256
2257 while 1:
2258 match = _name_special_search(s, i)
2259
2260 if match.group() == "$(":
2261 s, i = self._expand_macro(s, match.start(), ())
2262 else:
2263 return (s, match.start())
2264
2265 def _expand_str(self, s, i):
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002266 # Expands a quoted string starting at index 'i' in 's'. Handles both
2267 # backslash escapes and macro expansion.
2268 #
2269 # Returns the expanded 's' (including the part before the string) and
2270 # the index of the first character after the expanded string in 's'.
2271
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002272 quote = s[i]
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002273 i += 1 # Skip over initial "/'
2274 while 1:
2275 match = _string_special_search(s, i)
2276 if not match:
2277 self._parse_error("unterminated string")
2278
2279
2280 if match.group() == quote:
2281 # Found the end of the string
2282 return (s, match.end())
2283
2284 elif match.group() == "\\":
2285 # Replace '\x' with 'x'. 'i' ends up pointing to the character
2286 # after 'x', which allows macros to be canceled with '\$(foo)'.
2287 i = match.end()
2288 s = s[:match.start()] + s[i:]
2289
2290 elif match.group() == "$(":
2291 # A macro call within the string
2292 s, i = self._expand_macro(s, match.start(), ())
2293
2294 else:
2295 # A ' quote within " quotes or vice versa
2296 i += 1
2297
2298 def _expand_macro(self, s, i, args):
2299 # Expands a macro starting at index 'i' in 's'. If this macro resulted
2300 # from the expansion of another macro, 'args' holds the arguments
2301 # passed to that macro.
2302 #
2303 # Returns the expanded 's' (including the part before the macro) and
2304 # the index of the first character after the expanded macro in 's'.
2305
2306 start = i
2307 i += 2 # Skip over "$("
2308
2309 # Start of current macro argument
2310 arg_start = i
2311
2312 # Arguments of this macro call
2313 new_args = []
2314
2315 while 1:
2316 match = _macro_special_search(s, i)
2317 if not match:
2318 self._parse_error("missing end parenthesis in macro expansion")
2319
2320
2321 if match.group() == ")":
2322 # Found the end of the macro
2323
2324 new_args.append(s[arg_start:match.start()])
2325
2326 prefix = s[:start]
2327
2328 # $(1) is replaced by the first argument to the function, etc.,
2329 # provided at least that many arguments were passed
2330
2331 try:
2332 # Does the macro look like an integer, with a corresponding
2333 # argument? If so, expand it to the value of the argument.
2334 prefix += args[int(new_args[0])]
2335 except (ValueError, IndexError):
2336 # Regular variables are just functions without arguments,
2337 # and also go through the function value path
2338 prefix += self._fn_val(new_args)
2339
2340 return (prefix + s[match.end():],
2341 len(prefix))
2342
2343 elif match.group() == ",":
2344 # Found the end of a macro argument
2345 new_args.append(s[arg_start:match.start()])
2346 arg_start = i = match.end()
2347
2348 else: # match.group() == "$("
2349 # A nested macro call within the macro
2350 s, i = self._expand_macro(s, match.start(), args)
2351
2352 def _fn_val(self, args):
2353 # Returns the result of calling the function args[0] with the arguments
2354 # args[1..len(args)-1]. Plain variables are treated as functions
2355 # without arguments.
2356
2357 fn = args[0]
2358
2359 if fn in self.variables:
2360 var = self.variables[fn]
2361
2362 if len(args) == 1:
2363 # Plain variable
2364 if var._n_expansions:
2365 self._parse_error("Preprocessor variable {} recursively "
2366 "references itself".format(var.name))
2367 elif var._n_expansions > 100:
2368 # Allow functions to call themselves, but guess that functions
2369 # that are overly recursive are stuck
2370 self._parse_error("Preprocessor function {} seems stuck "
2371 "in infinite recursion".format(var.name))
2372
2373 var._n_expansions += 1
2374 res = self._expand_whole(self.variables[fn].value, args)
2375 var._n_expansions -= 1
2376 return res
2377
2378 if fn in self._functions:
Ulf Magnusson905e65d2018-09-27 17:28:00 +02002379 # Built-in or user-defined function
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002380
2381 py_fn, min_arg, max_arg = self._functions[fn]
2382
Ulf Magnusson905e65d2018-09-27 17:28:00 +02002383 if len(args) - 1 < min_arg or \
2384 (max_arg is not None and len(args) - 1 > max_arg):
2385
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002386 if min_arg == max_arg:
2387 expected_args = min_arg
Ulf Magnusson905e65d2018-09-27 17:28:00 +02002388 elif max_arg is None:
2389 expected_args = "{} or more".format(min_arg)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002390 else:
2391 expected_args = "{}-{}".format(min_arg, max_arg)
2392
2393 raise KconfigError("{}:{}: bad number of arguments in call "
2394 "to {}, expected {}, got {}"
2395 .format(self._filename, self._linenr, fn,
2396 expected_args, len(args) - 1))
2397
Ulf Magnusson905e65d2018-09-27 17:28:00 +02002398 return py_fn(self, *args)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002399
2400 # Environment variables are tried last
2401 if fn in os.environ:
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02002402 self.env_vars.add(fn)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002403 return os.environ[fn]
2404
2405 return ""
2406
2407
2408 #
Carles Cufi591eb572018-01-07 15:54:57 +01002409 # Parsing
2410 #
2411
2412 def _make_and(self, e1, e2):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002413 # Constructs an AND (&&) expression. Performs trivial simplification.
2414
Carles Cufi591eb572018-01-07 15:54:57 +01002415 if e1 is self.y:
2416 return e2
2417
2418 if e2 is self.y:
2419 return e1
2420
2421 if e1 is self.n or e2 is self.n:
2422 return self.n
2423
2424 return (AND, e1, e2)
2425
2426 def _make_or(self, e1, e2):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002427 # Constructs an OR (||) expression. Performs trivial simplification.
2428
Carles Cufi591eb572018-01-07 15:54:57 +01002429 if e1 is self.n:
2430 return e2
2431
2432 if e2 is self.n:
2433 return e1
2434
2435 if e1 is self.y or e2 is self.y:
2436 return self.y
2437
2438 return (OR, e1, e2)
2439
Ulf Magnussone307ba32018-05-16 20:42:40 +02002440 def _parse_block(self, end_token, parent, prev):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002441 # Parses a block, which is the contents of either a file or an if,
2442 # menu, or choice statement.
2443 #
2444 # end_token:
2445 # The token that ends the block, e.g. _T_ENDIF ("endif") for ifs.
2446 # None for files.
2447 #
2448 # parent:
2449 # The parent menu node, corresponding to a menu, Choice, or 'if'.
2450 # 'if's are flattened after parsing.
2451 #
Ulf Magnusson4b358752018-03-28 22:26:43 +02002452 # prev:
2453 # The previous menu node. New nodes will be added after this one (by
2454 # modifying their 'next' pointer).
2455 #
2456 # 'prev' is reused to parse a list of child menu nodes (for a menu or
2457 # Choice): After parsing the children, the 'next' pointer is assigned
2458 # to the 'list' pointer to "tilt up" the children above the node.
2459 #
Ulf Magnusson4b358752018-03-28 22:26:43 +02002460 # Returns the final menu node in the block (or 'prev' if the block is
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002461 # empty). This allows chaining.
Carles Cufi591eb572018-01-07 15:54:57 +01002462
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02002463 while self._next_line():
Carles Cufi591eb572018-01-07 15:54:57 +01002464 t0 = self._next_token()
Carles Cufi591eb572018-01-07 15:54:57 +01002465
2466 if t0 in (_T_CONFIG, _T_MENUCONFIG):
2467 # The tokenizer allocates Symbol objects for us
Carles Cufi81da97c2018-02-06 11:43:05 +01002468 sym = self._expect_nonconst_sym_and_eol()
2469 self.defined_syms.append(sym)
Carles Cufi591eb572018-01-07 15:54:57 +01002470
2471 node = MenuNode()
2472 node.kconfig = self
2473 node.item = sym
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002474 node.is_menuconfig = (t0 is _T_MENUCONFIG)
Ulf Magnusson4b358752018-03-28 22:26:43 +02002475 node.prompt = node.help = node.list = None
Carles Cufi591eb572018-01-07 15:54:57 +01002476 node.parent = parent
2477 node.filename = self._filename
2478 node.linenr = self._linenr
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002479 node.include_path = self._include_path
Carles Cufi591eb572018-01-07 15:54:57 +01002480
Carles Cufi81da97c2018-02-06 11:43:05 +01002481 sym.nodes.append(node)
2482
Ulf Magnussone307ba32018-05-16 20:42:40 +02002483 self._parse_properties(node)
Carles Cufi591eb572018-01-07 15:54:57 +01002484
Carles Cufi81da97c2018-02-06 11:43:05 +01002485 if node.is_menuconfig and not node.prompt:
2486 self._warn("the menuconfig symbol {} has no prompt"
Ulf Magnussona56be6f2018-08-17 22:27:01 +02002487 .format(_name_and_loc(sym)))
Carles Cufi591eb572018-01-07 15:54:57 +01002488
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01002489 # Equivalent to
2490 #
2491 # prev.next = node
2492 # prev = node
2493 #
2494 # due to tricky Python semantics. The order matters.
Ulf Magnusson4b358752018-03-28 22:26:43 +02002495 prev.next = prev = node
Carles Cufi591eb572018-01-07 15:54:57 +01002496
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02002497 elif t0 is None:
2498 # Blank line
2499 continue
2500
Ulf Magnusson6686efb2018-08-10 06:04:23 +02002501 elif t0 in (_T_SOURCE, _T_RSOURCE, _T_OSOURCE, _T_ORSOURCE):
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002502 pattern = self._expect_str_and_eol()
Ulf Magnusson6686efb2018-08-10 06:04:23 +02002503
2504 # Check if the pattern is absolute and avoid stripping srctree
2505 # from it below in that case. We must do the check before
2506 # join()'ing, as srctree might be an absolute path.
2507 isabs = os.path.isabs(pattern)
2508
2509 if t0 in (_T_RSOURCE, _T_ORSOURCE):
2510 # Relative source
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002511 pattern = os.path.join(os.path.dirname(self._filename),
2512 pattern)
2513
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002514 # Sort the glob results to ensure a consistent ordering of
2515 # Kconfig symbols, which indirectly ensures a consistent
2516 # ordering in e.g. .config files
Ulf Magnusson6686efb2018-08-10 06:04:23 +02002517 filenames = \
2518 sorted(glob.iglob(os.path.join(self.srctree, pattern)))
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002519
Ulf Magnusson6686efb2018-08-10 06:04:23 +02002520 if not filenames and t0 in (_T_SOURCE, _T_RSOURCE):
2521 raise KconfigError("\n" + textwrap.fill(
2522 "{}:{}: '{}' does not exist{}".format(
2523 self._filename, self._linenr, pattern,
2524 self._srctree_hint()),
2525 80))
2526
2527 for filename in filenames:
2528 self._enter_file(
2529 filename,
2530 # Unless an absolute path is passed to *source, strip
2531 # the $srctree prefix from the filename. That way it
2532 # appears without a $srctree prefix in
2533 # MenuNode.filename, which is nice e.g. when generating
2534 # documentation.
2535 filename if isabs else
2536 os.path.relpath(filename, self.srctree))
2537
Ulf Magnussone307ba32018-05-16 20:42:40 +02002538 prev = self._parse_block(None, parent, prev)
Ulf Magnusson6686efb2018-08-10 06:04:23 +02002539
Carles Cufi33bbecb2018-01-07 15:56:10 +01002540 self._leave_file()
Carles Cufi591eb572018-01-07 15:54:57 +01002541
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002542 elif t0 is end_token:
Carles Cufi591eb572018-01-07 15:54:57 +01002543 # We have reached the end of the block. Terminate the final
2544 # node and return it.
Ulf Magnusson4b358752018-03-28 22:26:43 +02002545 prev.next = None
2546 return prev
Carles Cufi591eb572018-01-07 15:54:57 +01002547
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002548 elif t0 is _T_IF:
Carles Cufi591eb572018-01-07 15:54:57 +01002549 node = MenuNode()
2550 node.item = node.prompt = None
2551 node.parent = parent
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002552 node.dep = self._expect_expr_and_eol()
Carles Cufi591eb572018-01-07 15:54:57 +01002553
Ulf Magnussone307ba32018-05-16 20:42:40 +02002554 self._parse_block(_T_ENDIF, node, node)
Carles Cufi591eb572018-01-07 15:54:57 +01002555 node.list = node.next
2556
Ulf Magnusson4b358752018-03-28 22:26:43 +02002557 prev.next = prev = node
Carles Cufi591eb572018-01-07 15:54:57 +01002558
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002559 elif t0 is _T_MENU:
Carles Cufi591eb572018-01-07 15:54:57 +01002560 node = MenuNode()
2561 node.kconfig = self
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01002562 node.item = t0 # _T_MENU == MENU
Ulf Magnusson46a172a2018-04-04 17:13:34 +02002563 node.is_menuconfig = True
Ulf Magnussone307ba32018-05-16 20:42:40 +02002564 node.prompt = (self._expect_str_and_eol(), self.y)
Carles Cufi591eb572018-01-07 15:54:57 +01002565 node.visibility = self.y
2566 node.parent = parent
2567 node.filename = self._filename
2568 node.linenr = self._linenr
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002569 node.include_path = self._include_path
Carles Cufi591eb572018-01-07 15:54:57 +01002570
Ulf Magnussoncb95ea02018-06-07 12:27:37 +02002571 self.menus.append(node)
2572
Ulf Magnussone307ba32018-05-16 20:42:40 +02002573 self._parse_properties(node)
2574 self._parse_block(_T_ENDMENU, node, node)
Carles Cufi591eb572018-01-07 15:54:57 +01002575 node.list = node.next
2576
Ulf Magnusson4b358752018-03-28 22:26:43 +02002577 prev.next = prev = node
Carles Cufi591eb572018-01-07 15:54:57 +01002578
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002579 elif t0 is _T_COMMENT:
Carles Cufi591eb572018-01-07 15:54:57 +01002580 node = MenuNode()
2581 node.kconfig = self
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01002582 node.item = t0 # _T_COMMENT == COMMENT
Ulf Magnusson46a172a2018-04-04 17:13:34 +02002583 node.is_menuconfig = False
Ulf Magnussone307ba32018-05-16 20:42:40 +02002584 node.prompt = (self._expect_str_and_eol(), self.y)
Carles Cufi591eb572018-01-07 15:54:57 +01002585 node.list = None
2586 node.parent = parent
2587 node.filename = self._filename
2588 node.linenr = self._linenr
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002589 node.include_path = self._include_path
Carles Cufi591eb572018-01-07 15:54:57 +01002590
Ulf Magnussoncb95ea02018-06-07 12:27:37 +02002591 self.comments.append(node)
2592
Ulf Magnussone307ba32018-05-16 20:42:40 +02002593 self._parse_properties(node)
Carles Cufi591eb572018-01-07 15:54:57 +01002594
Ulf Magnusson4b358752018-03-28 22:26:43 +02002595 prev.next = prev = node
Carles Cufi591eb572018-01-07 15:54:57 +01002596
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002597 elif t0 is _T_CHOICE:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002598 if self._peek_token() is None:
Carles Cufi591eb572018-01-07 15:54:57 +01002599 choice = Choice()
Ulf Magnussond3bfbfe2018-04-24 11:41:47 +02002600 choice.direct_dep = self.n
Carles Cufi591eb572018-01-07 15:54:57 +01002601 else:
2602 # Named choice
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002603 name = self._expect_str_and_eol()
Carles Cufi591eb572018-01-07 15:54:57 +01002604 choice = self.named_choices.get(name)
2605 if not choice:
2606 choice = Choice()
Carles Cufi591eb572018-01-07 15:54:57 +01002607 choice.name = name
Ulf Magnussond3bfbfe2018-04-24 11:41:47 +02002608 choice.direct_dep = self.n
Carles Cufi591eb572018-01-07 15:54:57 +01002609 self.named_choices[name] = choice
2610
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02002611 self.choices.append(choice)
2612
Carles Cufi591eb572018-01-07 15:54:57 +01002613 choice.kconfig = self
2614
2615 node = MenuNode()
2616 node.kconfig = self
2617 node.item = choice
Ulf Magnusson46a172a2018-04-04 17:13:34 +02002618 node.is_menuconfig = True
Ulf Magnussondb28a5d2018-04-05 12:02:10 +02002619 node.prompt = node.help = None
Carles Cufi591eb572018-01-07 15:54:57 +01002620 node.parent = parent
2621 node.filename = self._filename
2622 node.linenr = self._linenr
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002623 node.include_path = self._include_path
Carles Cufi591eb572018-01-07 15:54:57 +01002624
Ulf Magnusson80f19cc2018-06-15 19:22:28 +02002625 choice.nodes.append(node)
2626
Ulf Magnussone307ba32018-05-16 20:42:40 +02002627 self._parse_properties(node)
2628 self._parse_block(_T_ENDCHOICE, node, node)
Carles Cufi591eb572018-01-07 15:54:57 +01002629 node.list = node.next
2630
Ulf Magnusson4b358752018-03-28 22:26:43 +02002631 prev.next = prev = node
Carles Cufi591eb572018-01-07 15:54:57 +01002632
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002633 elif t0 is _T_MAINMENU:
Carles Cufi81da97c2018-02-06 11:43:05 +01002634 self.top_node.prompt = (self._expect_str_and_eol(), self.y)
Carles Cufi591eb572018-01-07 15:54:57 +01002635 self.top_node.filename = self._filename
2636 self.top_node.linenr = self._linenr
2637
2638 else:
Ulf Magnusson905e65d2018-09-27 17:28:00 +02002639 # A valid endchoice/endif/endmenu is caught by the 'end_token'
2640 # check above
2641 self._parse_error(
2642 "no corresponding 'choice'" if t0 is _T_ENDCHOICE else
2643 "no corresponding 'if'" if t0 is _T_ENDIF else
2644 "no corresponding 'menu'" if t0 is _T_ENDMENU else
2645 "unrecognized construct")
Carles Cufi591eb572018-01-07 15:54:57 +01002646
2647 # End of file reached. Terminate the final node and return it.
2648
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002649 if end_token:
Ulf Magnusson54a59972018-06-20 00:07:51 +02002650 raise KconfigError("Unexpected end of file " + self._filename)
Carles Cufi591eb572018-01-07 15:54:57 +01002651
Ulf Magnusson4b358752018-03-28 22:26:43 +02002652 prev.next = None
2653 return prev
Carles Cufi591eb572018-01-07 15:54:57 +01002654
2655 def _parse_cond(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002656 # Parses an optional 'if <expr>' construct and returns the parsed
2657 # <expr>, or self.y if the next token is not _T_IF
2658
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002659 return self._expect_expr_and_eol() if self._check_token(_T_IF) \
2660 else self.y
Carles Cufi591eb572018-01-07 15:54:57 +01002661
Ulf Magnussone307ba32018-05-16 20:42:40 +02002662 def _parse_properties(self, node):
2663 # Parses and adds properties to the MenuNode 'node' (type, 'prompt',
2664 # 'default's, etc.) Properties are later copied up to symbols and
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02002665 # choices in a separate pass after parsing, in e.g.
2666 # _add_props_to_sym().
Ulf Magnussone307ba32018-05-16 20:42:40 +02002667 #
2668 # An older version of this code added properties directly to symbols
2669 # and choices instead of to their menu nodes (and handled dependency
2670 # propagation simultaneously), but that loses information on where a
2671 # property is added when a symbol or choice is defined in multiple
2672 # locations. Some Kconfig configuration systems rely heavily on such
2673 # symbols, and better docs can be generated by keeping track of where
2674 # properties are added.
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002675 #
2676 # node:
Ulf Magnussone307ba32018-05-16 20:42:40 +02002677 # The menu node we're parsing properties on
Carles Cufi591eb572018-01-07 15:54:57 +01002678
Ulf Magnussone307ba32018-05-16 20:42:40 +02002679 # Dependencies from 'depends on'. Will get propagated to the properties
2680 # below.
Carles Cufi591eb572018-01-07 15:54:57 +01002681 node.dep = self.y
2682
Carles Cufi591eb572018-01-07 15:54:57 +01002683 while self._next_line():
2684 t0 = self._next_token()
Carles Cufi591eb572018-01-07 15:54:57 +01002685
2686 if t0 in _TYPE_TOKENS:
Ulf Magnussonaa262892018-05-18 22:33:03 +02002687 self._set_type(node, _TOKEN_TO_TYPE[t0])
Carles Cufi591eb572018-01-07 15:54:57 +01002688 if self._peek_token() is not None:
Ulf Magnussonaa262892018-05-18 22:33:03 +02002689 self._parse_prompt(node)
Carles Cufi591eb572018-01-07 15:54:57 +01002690
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002691 elif t0 is _T_DEPENDS:
Carles Cufi591eb572018-01-07 15:54:57 +01002692 if not self._check_token(_T_ON):
2693 self._parse_error('expected "on" after "depends"')
2694
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02002695 node.dep = self._make_and(node.dep,
2696 self._expect_expr_and_eol())
Carles Cufi591eb572018-01-07 15:54:57 +01002697
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002698 elif t0 is _T_HELP:
Ulf Magnussonaa262892018-05-18 22:33:03 +02002699 self._parse_help(node)
Carles Cufi591eb572018-01-07 15:54:57 +01002700
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002701 elif t0 is _T_SELECT:
Carles Cufi591eb572018-01-07 15:54:57 +01002702 if not isinstance(node.item, Symbol):
2703 self._parse_error("only symbols can select")
2704
Ulf Magnussone307ba32018-05-16 20:42:40 +02002705 node.selects.append((self._expect_nonconst_sym(),
2706 self._parse_cond()))
Carles Cufi591eb572018-01-07 15:54:57 +01002707
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02002708 elif t0 is None:
2709 # Blank line
2710 continue
Carles Cufi591eb572018-01-07 15:54:57 +01002711
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002712 elif t0 is _T_DEFAULT:
Ulf Magnussone307ba32018-05-16 20:42:40 +02002713 node.defaults.append((self._parse_expr(False),
2714 self._parse_cond()))
Carles Cufi591eb572018-01-07 15:54:57 +01002715
Ulf Magnusson6686efb2018-08-10 06:04:23 +02002716 elif t0 in (_T_DEF_BOOL, _T_DEF_TRISTATE, _T_DEF_INT, _T_DEF_HEX,
2717 _T_DEF_STRING):
Ulf Magnussonaa262892018-05-18 22:33:03 +02002718 self._set_type(node, _TOKEN_TO_TYPE[t0])
Ulf Magnussone307ba32018-05-16 20:42:40 +02002719 node.defaults.append((self._parse_expr(False),
2720 self._parse_cond()))
Carles Cufi591eb572018-01-07 15:54:57 +01002721
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002722 elif t0 is _T_PROMPT:
Ulf Magnussonaa262892018-05-18 22:33:03 +02002723 self._parse_prompt(node)
Carles Cufi591eb572018-01-07 15:54:57 +01002724
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002725 elif t0 is _T_RANGE:
Ulf Magnussone307ba32018-05-16 20:42:40 +02002726 node.ranges.append((self._expect_sym(),
2727 self._expect_sym(),
2728 self._parse_cond()))
Carles Cufi591eb572018-01-07 15:54:57 +01002729
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02002730 elif t0 is _T_IMPLY:
2731 if not isinstance(node.item, Symbol):
2732 self._parse_error("only symbols can imply")
2733
2734 node.implies.append((self._expect_nonconst_sym(),
2735 self._parse_cond()))
2736
2737 elif t0 is _T_VISIBLE:
2738 if not self._check_token(_T_IF):
2739 self._parse_error('expected "if" after "visible"')
2740
2741 node.visibility = self._make_and(node.visibility,
2742 self._expect_expr_and_eol())
2743
2744
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002745 elif t0 is _T_OPTION:
Carles Cufi591eb572018-01-07 15:54:57 +01002746 if self._check_token(_T_ENV):
2747 if not self._check_token(_T_EQUAL):
Carles Cufi81da97c2018-02-06 11:43:05 +01002748 self._parse_error('expected "=" after "env"')
Carles Cufi591eb572018-01-07 15:54:57 +01002749
Carles Cufi81da97c2018-02-06 11:43:05 +01002750 env_var = self._expect_str_and_eol()
Carles Cufi591eb572018-01-07 15:54:57 +01002751 node.item.env_var = env_var
2752
Ulf Magnussonaa262892018-05-18 22:33:03 +02002753 if env_var in os.environ:
2754 node.defaults.append(
2755 (self._lookup_const_sym(os.environ[env_var]),
2756 self.y))
2757 else:
Ulf Magnusson4dc9e5b2018-05-16 20:24:03 +02002758 self._warn("{1} has 'option env=\"{0}\"', "
2759 "but the environment variable {0} is not "
2760 "set".format(node.item.name, env_var),
Carles Cufi591eb572018-01-07 15:54:57 +01002761 self._filename, self._linenr)
Carles Cufi591eb572018-01-07 15:54:57 +01002762
Ulf Magnussond44fee32018-05-21 15:48:23 +02002763 if env_var != node.item.name:
2764 self._warn("Kconfiglib expands environment variables "
2765 "in strings directly, meaning you do not "
2766 "need 'option env=...' \"bounce\" symbols. "
2767 "For compatibility with the C tools, "
2768 "rename {} to {} (so that the symbol name "
2769 "matches the environment variable name)."
2770 .format(node.item.name, env_var),
2771 self._filename, self._linenr)
2772
Carles Cufi591eb572018-01-07 15:54:57 +01002773 elif self._check_token(_T_DEFCONFIG_LIST):
2774 if not self.defconfig_list:
2775 self.defconfig_list = node.item
2776 else:
2777 self._warn("'option defconfig_list' set on multiple "
2778 "symbols ({0} and {1}). Only {0} will be "
2779 "used.".format(self.defconfig_list.name,
2780 node.item.name),
2781 self._filename, self._linenr)
2782
2783 elif self._check_token(_T_MODULES):
2784 # To reduce warning spam, only warn if 'option modules' is
2785 # set on some symbol that isn't MODULES, which should be
2786 # safe. I haven't run into any projects that make use
2787 # modules besides the kernel yet, and there it's likely to
2788 # keep being called "MODULES".
2789 if node.item is not self.modules:
2790 self._warn("the 'modules' option is not supported. "
2791 "Let me know if this is a problem for you, "
2792 "as it wouldn't be that hard to implement. "
2793 "Note that modules are supported -- "
2794 "Kconfiglib just assumes the symbol name "
2795 "MODULES, like older versions of the C "
2796 "implementation did when 'option modules' "
2797 "wasn't used.",
2798 self._filename, self._linenr)
2799
2800 elif self._check_token(_T_ALLNOCONFIG_Y):
2801 if not isinstance(node.item, Symbol):
2802 self._parse_error("the 'allnoconfig_y' option is only "
2803 "valid for symbols")
2804
2805 node.item.is_allnoconfig_y = True
2806
2807 else:
2808 self._parse_error("unrecognized option")
2809
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002810 elif t0 is _T_OPTIONAL:
Carles Cufi591eb572018-01-07 15:54:57 +01002811 if not isinstance(node.item, Choice):
2812 self._parse_error('"optional" is only valid for choices')
2813
2814 node.item.is_optional = True
2815
2816 else:
Carles Cufi591eb572018-01-07 15:54:57 +01002817 # Reuse the tokens for the non-property line later
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02002818 self._reuse_tokens = True
Ulf Magnussone307ba32018-05-16 20:42:40 +02002819 return
Carles Cufi591eb572018-01-07 15:54:57 +01002820
Ulf Magnussonaa262892018-05-18 22:33:03 +02002821 def _set_type(self, node, new_type):
2822 if node.item.orig_type not in (UNKNOWN, new_type):
2823 self._warn("{} defined with multiple types, {} will be used"
2824 .format(_name_and_loc(node.item),
2825 TYPE_TO_STR[new_type]))
2826
2827 node.item.orig_type = new_type
2828
2829 def _parse_prompt(self, node):
2830 # 'prompt' properties override each other within a single definition of
2831 # a symbol, but additional prompts can be added by defining the symbol
2832 # multiple times
2833 if node.prompt:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002834 self._warn(_name_and_loc(node.item) +
2835 " defined with multiple prompts in single location")
Ulf Magnussonaa262892018-05-18 22:33:03 +02002836
2837 prompt = self._expect_str()
2838 if prompt != prompt.strip():
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002839 self._warn(_name_and_loc(node.item) +
2840 " has leading or trailing whitespace in its prompt")
Ulf Magnussonaa262892018-05-18 22:33:03 +02002841
2842 # This avoid issues for e.g. reStructuredText documentation, where
2843 # '*prompt *' is invalid
2844 prompt = prompt.strip()
2845
2846 node.prompt = (prompt, self._parse_cond())
2847
2848 def _parse_help(self, node):
2849 # Find first non-blank (not all-space) line and get its indentation
2850
2851 if node.help is not None:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002852 self._warn(_name_and_loc(node.item) +
2853 " defined with more than one help text -- only the "
2854 "last one will be used")
Ulf Magnussonaa262892018-05-18 22:33:03 +02002855
2856 # Small optimization. This code is pretty hot.
2857 readline = self._file.readline
2858
2859 while 1:
2860 line = readline()
2861 self._linenr += 1
2862 if not line or not line.isspace():
2863 break
2864
2865 if not line:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002866 self._warn(_name_and_loc(node.item) +
2867 " has 'help' but empty help text")
Ulf Magnussonaa262892018-05-18 22:33:03 +02002868
2869 node.help = ""
2870 return
2871
2872 indent = _indentation(line)
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01002873 if not indent:
Ulf Magnussonaa262892018-05-18 22:33:03 +02002874 # If the first non-empty lines has zero indent, there is no help
2875 # text
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02002876 self._warn(_name_and_loc(node.item) +
2877 " has 'help' but empty help text")
Ulf Magnussonaa262892018-05-18 22:33:03 +02002878
2879 node.help = ""
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02002880 self._line_after_help(line)
Ulf Magnussonaa262892018-05-18 22:33:03 +02002881 return
2882
2883 # The help text goes on till the first non-empty line with less indent
2884 # than the first line
2885
2886 help_lines = []
Ulf Magnussond44fee32018-05-21 15:48:23 +02002887 # Small optimizations
Ulf Magnussonaa262892018-05-18 22:33:03 +02002888 add_help_line = help_lines.append
Ulf Magnussond44fee32018-05-21 15:48:23 +02002889 indentation = _indentation
Ulf Magnussonaa262892018-05-18 22:33:03 +02002890
Ulf Magnussond44fee32018-05-21 15:48:23 +02002891 while line and (line.isspace() or indentation(line) >= indent):
Ulf Magnussonaa262892018-05-18 22:33:03 +02002892 # De-indent 'line' by 'indent' spaces and rstrip() it to remove any
2893 # newlines (which gets rid of other trailing whitespace too, but
2894 # that's fine).
2895 #
2896 # This prepares help text lines in a speedy way: The [indent:]
2897 # might already remove trailing newlines for lines shorter than
2898 # indent (e.g. empty lines). The rstrip() makes it consistent,
2899 # meaning we can join the lines with "\n" later.
2900 add_help_line(line.expandtabs()[indent:].rstrip())
2901
2902 line = readline()
Ulf Magnussoncb95ea02018-06-07 12:27:37 +02002903
2904 self._linenr += len(help_lines)
Ulf Magnussonaa262892018-05-18 22:33:03 +02002905
2906 node.help = "\n".join(help_lines).rstrip() + "\n"
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02002907 self._line_after_help(line)
Ulf Magnussonaa262892018-05-18 22:33:03 +02002908
Carles Cufi591eb572018-01-07 15:54:57 +01002909 def _parse_expr(self, transform_m):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002910 # Parses an expression from the tokens in Kconfig._tokens using a
2911 # simple top-down approach. See the module docstring for the expression
2912 # format.
2913 #
2914 # transform_m:
2915 # True if m should be rewritten to m && MODULES. See the
2916 # Kconfig.eval_string() documentation.
Carles Cufi591eb572018-01-07 15:54:57 +01002917
Carles Cufi591eb572018-01-07 15:54:57 +01002918 # Grammar:
2919 #
2920 # expr: and_expr ['||' expr]
2921 # and_expr: factor ['&&' and_expr]
2922 # factor: <symbol> ['='/'!='/'<'/... <symbol>]
2923 # '!' factor
2924 # '(' expr ')'
2925 #
2926 # It helps to think of the 'expr: and_expr' case as a single-operand OR
2927 # (no ||), and of the 'and_expr: factor' case as a single-operand AND
2928 # (no &&). Parsing code is always a bit tricky.
2929
2930 # Mind dump: parse_factor() and two nested loops for OR and AND would
2931 # work as well. The straightforward implementation there gives a
2932 # (op, (op, (op, A, B), C), D) parse for A op B op C op D. Representing
2933 # expressions as (op, [list of operands]) instead goes nicely with that
2934 # version, but is wasteful for short expressions and complicates
2935 # expression evaluation and other code that works on expressions (more
2936 # complicated code likely offsets any performance gain from less
2937 # recursion too). If we also try to optimize the list representation by
2938 # merging lists when possible (e.g. when ANDing two AND expressions),
2939 # we end up allocating a ton of lists instead of reusing expressions,
2940 # which is bad.
2941
2942 and_expr = self._parse_and_expr(transform_m)
2943
2944 # Return 'and_expr' directly if we have a "single-operand" OR.
2945 # Otherwise, parse the expression on the right and make an OR node.
2946 # This turns A || B || C || D into (OR, A, (OR, B, (OR, C, D))).
2947 return and_expr \
2948 if not self._check_token(_T_OR) else \
2949 (OR, and_expr, self._parse_expr(transform_m))
2950
2951 def _parse_and_expr(self, transform_m):
2952 factor = self._parse_factor(transform_m)
2953
2954 # Return 'factor' directly if we have a "single-operand" AND.
2955 # Otherwise, parse the right operand and make an AND node. This turns
2956 # A && B && C && D into (AND, A, (AND, B, (AND, C, D))).
2957 return factor \
2958 if not self._check_token(_T_AND) else \
2959 (AND, factor, self._parse_and_expr(transform_m))
2960
2961 def _parse_factor(self, transform_m):
2962 token = self._next_token()
2963
2964 if isinstance(token, Symbol):
2965 # Plain symbol or relation
2966
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02002967 if self._peek_token() not in _RELATIONS:
Carles Cufi591eb572018-01-07 15:54:57 +01002968 # Plain symbol
2969
2970 # For conditional expressions ('depends on <expr>',
2971 # '... if <expr>', etc.), m is rewritten to m && MODULES.
2972 if transform_m and token is self.m:
2973 return (AND, self.m, self.modules)
2974
2975 return token
2976
2977 # Relation
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002978 #
2979 # _T_EQUAL, _T_UNEQUAL, etc., deliberately have the same values as
2980 # EQUAL, UNEQUAL, etc., so we can just use the token directly
2981 return (self._next_token(), token, self._expect_sym())
Carles Cufi591eb572018-01-07 15:54:57 +01002982
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002983 if token is _T_NOT:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002984 # token == _T_NOT == NOT
2985 return (token, self._parse_factor(transform_m))
Carles Cufi591eb572018-01-07 15:54:57 +01002986
Ulf Magnusson213a88f2018-09-05 12:24:45 +02002987 if token is _T_OPEN_PAREN:
Carles Cufi591eb572018-01-07 15:54:57 +01002988 expr_parse = self._parse_expr(transform_m)
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002989 if self._check_token(_T_CLOSE_PAREN):
2990 return expr_parse
Carles Cufi591eb572018-01-07 15:54:57 +01002991
2992 self._parse_error("malformed expression")
2993
2994 #
2995 # Caching and invalidation
2996 #
2997
2998 def _build_dep(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01002999 # Populates the Symbol/Choice._dependents sets, which contain all other
3000 # items (symbols and choices) that immediately depend on the item in
3001 # the sense that changing the value of the item might affect the value
3002 # of the dependent items. This is used for caching/invalidation.
3003 #
3004 # The calculated sets might be larger than necessary as we don't do any
3005 # complex analysis of the expressions.
Carles Cufi591eb572018-01-07 15:54:57 +01003006
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01003007 make_depend_on = _make_depend_on # Micro-optimization
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003008
Carles Cufi591eb572018-01-07 15:54:57 +01003009 # Only calculate _dependents for defined symbols. Constant and
3010 # undefined symbols could theoretically be selected/implied, but it
3011 # wouldn't change their value, so it's not a true dependency.
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02003012 for sym in self.unique_defined_syms:
Carles Cufi591eb572018-01-07 15:54:57 +01003013 # Symbols depend on the following:
3014
3015 # The prompt conditions
3016 for node in sym.nodes:
3017 if node.prompt:
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003018 make_depend_on(sym, node.prompt[1])
Carles Cufi591eb572018-01-07 15:54:57 +01003019
3020 # The default values and their conditions
3021 for value, cond in sym.defaults:
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003022 make_depend_on(sym, value)
3023 make_depend_on(sym, cond)
Carles Cufi591eb572018-01-07 15:54:57 +01003024
3025 # The reverse and weak reverse dependencies
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003026 make_depend_on(sym, sym.rev_dep)
3027 make_depend_on(sym, sym.weak_rev_dep)
Carles Cufi591eb572018-01-07 15:54:57 +01003028
3029 # The ranges along with their conditions
3030 for low, high, cond in sym.ranges:
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003031 make_depend_on(sym, low)
3032 make_depend_on(sym, high)
3033 make_depend_on(sym, cond)
Carles Cufi591eb572018-01-07 15:54:57 +01003034
3035 # The direct dependencies. This is usually redundant, as the direct
3036 # dependencies get propagated to properties, but it's needed to get
3037 # invalidation solid for 'imply', which only checks the direct
3038 # dependencies (even if there are no properties to propagate it
3039 # to).
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003040 make_depend_on(sym, sym.direct_dep)
Carles Cufi591eb572018-01-07 15:54:57 +01003041
3042 # In addition to the above, choice symbols depend on the choice
3043 # they're in, but that's handled automatically since the Choice is
3044 # propagated to the conditions of the properties before
3045 # _build_dep() runs.
3046
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02003047 for choice in self.unique_choices:
Carles Cufi591eb572018-01-07 15:54:57 +01003048 # Choices depend on the following:
3049
3050 # The prompt conditions
3051 for node in choice.nodes:
3052 if node.prompt:
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003053 make_depend_on(choice, node.prompt[1])
Carles Cufi591eb572018-01-07 15:54:57 +01003054
3055 # The default symbol conditions
3056 for _, cond in choice.defaults:
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003057 make_depend_on(choice, cond)
Carles Cufi591eb572018-01-07 15:54:57 +01003058
Ulf Magnusson54a59972018-06-20 00:07:51 +02003059 def _add_choice_deps(self):
3060 # Choices also depend on the choice symbols themselves, because the
3061 # y-mode selection of the choice might change if a choice symbol's
3062 # visibility changes.
3063 #
3064 # We add these dependencies separately after dependency loop detection.
3065 # The invalidation algorithm can handle the resulting
3066 # <choice symbol> <-> <choice> dependency loops, but they make loop
3067 # detection awkward.
3068
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02003069 for choice in self.unique_choices:
Carles Cufi591eb572018-01-07 15:54:57 +01003070 for sym in choice.syms:
Carles Cufi591eb572018-01-07 15:54:57 +01003071 sym._dependents.add(choice)
3072
3073 def _invalidate_all(self):
3074 # Undefined symbols never change value and don't need to be
3075 # invalidated, so we can just iterate over defined symbols.
3076 # Invalidating constant symbols would break things horribly.
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02003077 for sym in self.unique_defined_syms:
Carles Cufi591eb572018-01-07 15:54:57 +01003078 sym._invalidate()
3079
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02003080 for choice in self.unique_choices:
Carles Cufi591eb572018-01-07 15:54:57 +01003081 choice._invalidate()
3082
3083
3084 #
Ulf Magnussone307ba32018-05-16 20:42:40 +02003085 # Post-parsing menu tree processing, including dependency propagation and
3086 # implicit submenu creation
3087 #
3088
3089 def _finalize_tree(self, node, visible_if):
3090 # Propagates properties and dependencies, creates implicit menus (see
3091 # kconfig-language.txt), removes 'if' nodes, and finalizes choices.
3092 # This pretty closely mirrors menu_finalize() from the C
3093 # implementation, with some minor tweaks (MenuNode holds lists of
3094 # properties instead of each property having a MenuNode pointer, for
3095 # example).
3096 #
3097 # node:
3098 # The current "parent" menu node, from which we propagate
3099 # dependencies
3100 #
3101 # visible_if:
3102 # Dependencies from 'visible if' on parent menus. These are added to
3103 # the prompts of symbols and choices.
3104
3105 if node.list:
3106 # The menu node is a choice, menu, or if. Finalize each child in
3107 # it.
3108
Ulf Magnusson213a88f2018-09-05 12:24:45 +02003109 if node.item is MENU:
Ulf Magnussone307ba32018-05-16 20:42:40 +02003110 visible_if = self._make_and(visible_if, node.visibility)
3111
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003112 # Propagate the menu node's dependencies to each child menu node.
3113 #
3114 # The recursive _finalize_tree() calls assume that the current
3115 # "level" in the tree has already had dependencies propagated. This
Ulf Magnusson80f19cc2018-06-15 19:22:28 +02003116 # makes e.g. implicit submenu creation easier, because it needs to
3117 # look ahead.
Ulf Magnussone307ba32018-05-16 20:42:40 +02003118 self._propagate_deps(node, visible_if)
3119
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003120 # Finalize the children
Ulf Magnussone307ba32018-05-16 20:42:40 +02003121 cur = node.list
3122 while cur:
3123 self._finalize_tree(cur, visible_if)
3124 cur = cur.next
3125
3126 elif isinstance(node.item, Symbol):
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003127 # Add the node's non-node-specific properties (defaults, ranges,
3128 # etc.) to the Symbol
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003129 self._add_props_to_sym(node)
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003130
3131 # See if we can create an implicit menu rooted at the Symbol and
3132 # finalize each child menu node in that menu if so, like for the
3133 # choice/menu/if case above
Ulf Magnussone307ba32018-05-16 20:42:40 +02003134 cur = node
3135 while cur.next and _auto_menu_dep(node, cur.next):
3136 # This also makes implicit submenu creation work recursively,
3137 # with implicit menus inside implicit menus
3138 self._finalize_tree(cur.next, visible_if)
3139 cur = cur.next
3140 cur.parent = node
3141
3142 if cur is not node:
3143 # Found symbols that should go in an implicit submenu. Tilt
3144 # them up above us.
3145 node.list = node.next
3146 node.next = cur.next
3147 cur.next = None
3148
3149
3150 if node.list:
3151 # We have a parent node with individually finalized child nodes. Do
3152 # final steps to finalize this "level" in the menu tree.
3153 _flatten(node.list)
3154 _remove_ifs(node)
3155
3156 # Empty choices (node.list None) are possible, so this needs to go
3157 # outside
3158 if isinstance(node.item, Choice):
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003159 # Add the node's non-node-specific properties to the choice, like
3160 # _add_props_to_sym() does
3161 choice = node.item
3162 choice.direct_dep = self._make_or(choice.direct_dep, node.dep)
3163 choice.defaults += node.defaults
3164
Ulf Magnussone307ba32018-05-16 20:42:40 +02003165 _finalize_choice(node)
3166
3167 def _propagate_deps(self, node, visible_if):
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003168 # Propagates 'node's dependencies to its child menu nodes
Ulf Magnussone307ba32018-05-16 20:42:40 +02003169
3170 # If the parent node holds a Choice, we use the Choice itself as the
3171 # parent dependency. This makes sense as the value (mode) of the choice
3172 # limits the visibility of the contained choice symbols. The C
3173 # implementation works the same way.
3174 #
3175 # Due to the similar interface, Choice works as a drop-in replacement
3176 # for Symbol here.
3177 basedep = node.item if isinstance(node.item, Choice) else node.dep
3178
3179 cur = node.list
3180 while cur:
3181 cur.dep = dep = self._make_and(cur.dep, basedep)
3182
3183 # Propagate dependencies to prompt
3184 if cur.prompt:
3185 cur.prompt = (cur.prompt[0],
3186 self._make_and(cur.prompt[1], dep))
3187
3188 if isinstance(cur.item, (Symbol, Choice)):
Ulf Magnussone307ba32018-05-16 20:42:40 +02003189 # Propagate 'visible if' dependencies to the prompt
3190 if cur.prompt:
3191 cur.prompt = (cur.prompt[0],
3192 self._make_and(cur.prompt[1], visible_if))
3193
3194 # Propagate dependencies to defaults
Ulf Magnussone307ba32018-05-16 20:42:40 +02003195 if cur.defaults:
3196 cur.defaults = [(default, self._make_and(cond, dep))
3197 for default, cond in cur.defaults]
Ulf Magnussone307ba32018-05-16 20:42:40 +02003198
3199 # Propagate dependencies to ranges
Ulf Magnussone307ba32018-05-16 20:42:40 +02003200 if cur.ranges:
3201 cur.ranges = [(low, high, self._make_and(cond, dep))
3202 for low, high, cond in cur.ranges]
Ulf Magnussone307ba32018-05-16 20:42:40 +02003203
3204 # Propagate dependencies to selects
Ulf Magnussone307ba32018-05-16 20:42:40 +02003205 if cur.selects:
3206 cur.selects = [(target, self._make_and(cond, dep))
3207 for target, cond in cur.selects]
Ulf Magnussone307ba32018-05-16 20:42:40 +02003208
3209 # Propagate dependencies to implies
Ulf Magnussone307ba32018-05-16 20:42:40 +02003210 if cur.implies:
3211 cur.implies = [(target, self._make_and(cond, dep))
3212 for target, cond in cur.implies]
Ulf Magnussone307ba32018-05-16 20:42:40 +02003213
3214
3215 cur = cur.next
3216
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003217 def _add_props_to_sym(self, node):
Ulf Magnusson80f19cc2018-06-15 19:22:28 +02003218 # Copies properties from the menu node 'node' up to its contained
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003219 # symbol, and adds (weak) reverse dependencies to selected/implied
3220 # symbols.
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003221 #
3222 # This can't be rolled into _propagate_deps(), because that function
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003223 # traverses the menu tree roughly breadth-first, meaning properties on
3224 # symbols defined in multiple locations could end up in the wrong
3225 # order.
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003226
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003227 sym = node.item
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003228
3229 # See the Symbol class docstring
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003230 sym.direct_dep = self._make_or(sym.direct_dep, node.dep)
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003231
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003232 sym.defaults += node.defaults
3233 sym.ranges += node.ranges
3234 sym.selects += node.selects
3235 sym.implies += node.implies
Ulf Magnussona56be6f2018-08-17 22:27:01 +02003236
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003237 # Modify the reverse dependencies of the selected symbol
3238 for target, cond in node.selects:
3239 target.rev_dep = self._make_or(
3240 target.rev_dep,
3241 self._make_and(sym, cond))
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003242
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003243 # Modify the weak reverse dependencies of the implied
3244 # symbol
3245 for target, cond in node.implies:
3246 target.weak_rev_dep = self._make_or(
3247 target.weak_rev_dep,
3248 self._make_and(sym, cond))
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02003249
3250
Ulf Magnussone307ba32018-05-16 20:42:40 +02003251 #
Carles Cufi591eb572018-01-07 15:54:57 +01003252 # Misc.
3253 #
3254
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003255 def _check_sym_sanity(self):
3256 # Checks various symbol properties that are handiest to check after
3257 # parsing. Only generates errors and warnings.
3258
3259 def num_ok(sym, type_):
3260 # Returns True if the (possibly constant) symbol 'sym' is valid as a value
3261 # for a symbol of type type_ (INT or HEX)
3262
3263 # 'not sym.nodes' implies a constant or undefined symbol, e.g. a plain
3264 # "123"
3265 if not sym.nodes:
3266 return _is_base_n(sym.name, _TYPE_TO_BASE[type_])
3267
3268 return sym.orig_type is type_
3269
3270 for sym in self.unique_defined_syms:
3271 if sym.orig_type in (BOOL, TRISTATE):
3272 # A helper function could be factored out here, but keep it
3273 # speedy/straightforward
3274
3275 for target_sym, _ in sym.selects:
3276 if target_sym.orig_type not in (BOOL, TRISTATE, UNKNOWN):
3277 self._warn("{} selects the {} symbol {}, which is not "
3278 "bool or tristate"
3279 .format(_name_and_loc(sym),
3280 TYPE_TO_STR[target_sym.orig_type],
3281 _name_and_loc(target_sym)))
3282
3283 for target_sym, _ in sym.implies:
3284 if target_sym.orig_type not in (BOOL, TRISTATE, UNKNOWN):
3285 self._warn("{} implies the {} symbol {}, which is not "
3286 "bool or tristate"
3287 .format(_name_and_loc(sym),
3288 TYPE_TO_STR[target_sym.orig_type],
3289 _name_and_loc(target_sym)))
3290
3291 elif sym.orig_type in (STRING, INT, HEX):
3292 for default, _ in sym.defaults:
3293 if not isinstance(default, Symbol):
3294 raise KconfigError(
3295 "the {} symbol {} has a malformed default {} -- expected "
3296 "a single symbol"
3297 .format(TYPE_TO_STR[sym.orig_type], _name_and_loc(sym),
3298 expr_str(default)))
3299
3300 if sym.orig_type is STRING:
3301 if not default.is_constant and not default.nodes and \
3302 not default.name.isupper():
3303 # 'default foo' on a string symbol could be either a symbol
3304 # reference or someone leaving out the quotes. Guess that
3305 # the quotes were left out if 'foo' isn't all-uppercase
3306 # (and no symbol named 'foo' exists).
3307 self._warn("style: quotes recommended around "
3308 "default value for string symbol "
3309 + _name_and_loc(sym))
3310
3311 elif sym.orig_type in (INT, HEX) and \
3312 not num_ok(default, sym.orig_type):
3313
3314 self._warn("the {0} symbol {1} has a non-{0} default {2}"
3315 .format(TYPE_TO_STR[sym.orig_type],
3316 _name_and_loc(sym),
3317 _name_and_loc(default)))
3318
3319 if sym.selects or sym.implies:
3320 self._warn("the {} symbol {} has selects or implies"
3321 .format(TYPE_TO_STR[sym.orig_type],
3322 _name_and_loc(sym)))
3323
3324 else: # UNKNOWN
3325 self._warn("{} defined without a type"
3326 .format(_name_and_loc(sym)))
3327
3328
3329 if sym.ranges:
3330 if sym.orig_type not in (INT, HEX):
3331 self._warn(
3332 "the {} symbol {} has ranges, but is not int or hex"
3333 .format(TYPE_TO_STR[sym.orig_type],
3334 _name_and_loc(sym)))
3335 else:
3336 for low, high, _ in sym.ranges:
3337 if not num_ok(low, sym.orig_type) or \
3338 not num_ok(high, sym.orig_type):
3339
3340 self._warn("the {0} symbol {1} has a non-{0} "
3341 "range [{2}, {3}]"
3342 .format(TYPE_TO_STR[sym.orig_type],
3343 _name_and_loc(sym),
3344 _name_and_loc(low),
3345 _name_and_loc(high)))
3346
3347 def _check_choice_sanity(self):
3348 # Checks various choice properties that are handiest to check after
3349 # parsing. Only generates errors and warnings.
3350
3351 def warn_select_imply(sym, expr, expr_type):
3352 msg = "the choice symbol {} is {} by the following symbols, which " \
3353 "has no effect: ".format(_name_and_loc(sym), expr_type)
3354
3355 # si = select/imply
3356 for si in split_expr(expr, OR):
3357 msg += "\n - " + _name_and_loc(split_expr(si, AND)[0])
3358
3359 self._warn(msg)
3360
3361 for choice in self.unique_choices:
3362 if choice.orig_type not in (BOOL, TRISTATE):
3363 self._warn("{} defined with type {}"
3364 .format(_name_and_loc(choice),
3365 TYPE_TO_STR[choice.orig_type]))
3366
3367 for node in choice.nodes:
3368 if node.prompt:
3369 break
3370 else:
3371 self._warn(_name_and_loc(choice) + " defined without a prompt")
3372
3373 for default, _ in choice.defaults:
3374 if not isinstance(default, Symbol):
3375 raise KconfigError(
3376 "{} has a malformed default {}"
3377 .format(_name_and_loc(choice), expr_str(default)))
3378
3379 if default.choice is not choice:
3380 self._warn("the default selection {} of {} is not "
3381 "contained in the choice"
3382 .format(_name_and_loc(default),
3383 _name_and_loc(choice)))
3384
3385 for sym in choice.syms:
3386 if sym.defaults:
3387 self._warn("default on the choice symbol {} will have "
3388 "no effect, as defaults do not affect choice "
3389 "symbols".format(_name_and_loc(sym)))
3390
3391 if sym.rev_dep is not sym.kconfig.n:
3392 warn_select_imply(sym, sym.rev_dep, "selected")
3393
3394 if sym.weak_rev_dep is not sym.kconfig.n:
3395 warn_select_imply(sym, sym.weak_rev_dep, "implied")
3396
3397 for node in sym.nodes:
3398 if node.parent.item is choice:
3399 if not node.prompt:
3400 self._warn("the choice symbol {} has no prompt"
3401 .format(_name_and_loc(sym)))
3402
3403 elif node.prompt:
3404 self._warn("the choice symbol {} is defined with a "
3405 "prompt outside the choice"
3406 .format(_name_and_loc(sym)))
3407
Carles Cufi591eb572018-01-07 15:54:57 +01003408 def _parse_error(self, msg):
3409 if self._filename is None:
3410 loc = ""
3411 else:
3412 loc = "{}:{}: ".format(self._filename, self._linenr)
3413
Ulf Magnusson54a59972018-06-20 00:07:51 +02003414 raise KconfigError(
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02003415 "{}couldn't parse '{}': {}".format(loc, self._line.rstrip(), msg))
Carles Cufi591eb572018-01-07 15:54:57 +01003416
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003417 def _open(self, filename, mode):
3418 # open() wrapper:
3419 #
3420 # - Enable universal newlines mode on Python 2 to ease
3421 # interoperability between Linux and Windows. It's already the
3422 # default on Python 3.
3423 #
3424 # The "U" flag would currently work for both Python 2 and 3, but it's
3425 # deprecated on Python 3, so play it future-safe.
3426 #
3427 # A simpler solution would be to use io.open(), which defaults to
3428 # universal newlines on both Python 2 and 3 (and is an alias for
3429 # open() on Python 3), but it's appreciably slower on Python 2:
3430 #
3431 # Parsing x86 Kconfigs on Python 2
3432 #
3433 # with open(..., "rU"):
3434 #
3435 # real 0m0.930s
3436 # user 0m0.905s
3437 # sys 0m0.025s
3438 #
3439 # with io.open():
3440 #
3441 # real 0m1.069s
3442 # user 0m1.040s
3443 # sys 0m0.029s
3444 #
3445 # There's no appreciable performance difference between "r" and
3446 # "rU" for parsing performance on Python 2.
3447 #
3448 # - For Python 3, force the encoding. Forcing the encoding on Python 2
3449 # turns strings into Unicode strings, which gets messy. Python 2
3450 # doesn't decode regular strings anyway.
3451 return open(filename, "rU" if mode == "r" else mode) if _IS_PY2 else \
Ulf Magnussondc97fc22018-05-02 09:14:18 +02003452 open(filename, mode, encoding=self._encoding)
3453
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02003454 def _check_undef_syms(self):
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003455 # Prints warnings for all references to undefined symbols within the
3456 # Kconfig files
3457
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003458 def is_num(s):
3459 # Returns True if the string 's' looks like a number.
3460 #
3461 # Internally, all operands in Kconfig are symbols, only undefined symbols
3462 # (which numbers usually are) get their name as their value.
3463 #
3464 # Only hex numbers that start with 0x/0X are classified as numbers.
3465 # Otherwise, symbols whose names happen to contain only the letters A-F
3466 # would trigger false positives.
3467
3468 try:
3469 int(s)
3470 except ValueError:
3471 if not s.startswith(("0x", "0X")):
3472 return False
3473
3474 try:
3475 int(s, 16)
3476 except ValueError:
3477 return False
3478
3479 return True
3480
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02003481 for sym in (self.syms.viewvalues if _IS_PY2 else self.syms.values)():
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003482 # - sym.nodes empty means the symbol is undefined (has no
3483 # definition locations)
3484 #
3485 # - Due to Kconfig internals, numbers show up as undefined Kconfig
3486 # symbols, but shouldn't be flagged
3487 #
3488 # - The MODULES symbol always exists
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003489 if not sym.nodes and not is_num(sym.name) and \
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003490 sym.name != "MODULES":
3491
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02003492 msg = "undefined symbol {}:".format(sym.name)
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003493
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02003494 for node in self.node_iter():
3495 if sym in node.referenced:
3496 msg += "\n\n- Referenced at {}:{}:\n\n{}" \
3497 .format(node.filename, node.linenr, node)
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003498
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02003499 self._warn(msg)
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003500
Carles Cufi591eb572018-01-07 15:54:57 +01003501 def _warn(self, msg, filename=None, linenr=None):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003502 # For printing general warnings
3503
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02003504 if self._warnings_enabled:
3505 msg = "warning: " + msg
3506 if filename is not None:
3507 msg = "{}:{}: {}".format(filename, linenr, msg)
3508
3509 self.warnings.append(msg)
3510 if self._warn_to_stderr:
3511 sys.stderr.write(msg + "\n")
Carles Cufi591eb572018-01-07 15:54:57 +01003512
3513 def _warn_undef_assign(self, msg, filename=None, linenr=None):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003514 # See the class documentation
3515
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02003516 if self._warn_for_undef_assign:
3517 self._warn(msg, filename, linenr)
Carles Cufi591eb572018-01-07 15:54:57 +01003518
3519 def _warn_undef_assign_load(self, name, val, filename, linenr):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003520 # Special version for load_config()
3521
Carles Cufi591eb572018-01-07 15:54:57 +01003522 self._warn_undef_assign(
Carles Cufi81da97c2018-02-06 11:43:05 +01003523 'attempt to assign the value "{}" to the undefined symbol {}'
Carles Cufi591eb572018-01-07 15:54:57 +01003524 .format(val, name), filename, linenr)
3525
Carles Cufi81da97c2018-02-06 11:43:05 +01003526 def _warn_redun_assign(self, msg, filename=None, linenr=None):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003527 # See the class documentation
3528
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02003529 if self._warn_for_redun_assign:
3530 self._warn(msg, filename, linenr)
Carles Cufi591eb572018-01-07 15:54:57 +01003531
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003532 def _srctree_hint(self):
3533 # Hint printed when Kconfig files can't be found or .config files can't
3534 # be opened
3535
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02003536 return ". Perhaps the $srctree environment variable ({}) " \
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003537 "is set incorrectly. Note that the current value of $srctree " \
3538 "is saved when the Kconfig instance is created (for " \
3539 "consistency and to cleanly separate instances)." \
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02003540 .format("set to '{}'".format(self.srctree) if self.srctree
3541 else "unset or blank")
Ulf Magnusson6686efb2018-08-10 06:04:23 +02003542
Carles Cufi591eb572018-01-07 15:54:57 +01003543class Symbol(object):
3544 """
3545 Represents a configuration symbol:
3546
3547 (menu)config FOO
3548 ...
3549
3550 The following attributes are available. They should be viewed as read-only,
3551 and some are implemented through @property magic (but are still efficient
3552 to access due to internal caching).
3553
3554 Note: Prompts, help texts, and locations are stored in the Symbol's
3555 MenuNode(s) rather than in the Symbol itself. Check the MenuNode class and
3556 the Symbol.nodes attribute. This organization matches the C tools.
3557
3558 name:
3559 The name of the symbol, e.g. "FOO" for 'config FOO'.
3560
3561 type:
3562 The type of the symbol. One of BOOL, TRISTATE, STRING, INT, HEX, UNKNOWN.
3563 UNKNOWN is for undefined symbols, (non-special) constant symbols, and
3564 symbols defined without a type.
3565
3566 When running without modules (MODULES having the value n), TRISTATE
3567 symbols magically change type to BOOL. This also happens for symbols
3568 within choices in "y" mode. This matches the C tools, and makes sense for
3569 menuconfig-like functionality.
3570
3571 orig_type:
3572 The type as given in the Kconfig file, without any magic applied. Used
3573 when printing the symbol.
3574
3575 str_value:
3576 The value of the symbol as a string. Gives the value for string/int/hex
3577 symbols. For bool/tristate symbols, gives "n", "m", or "y".
3578
3579 This is the symbol value that's used in relational expressions
3580 (A = B, A != B, etc.)
3581
3582 Gotcha: For int/hex symbols, the exact format of the value must often be
3583 preserved (e.g., when writing a .config file), hence why you can't get it
3584 directly as an int. Do int(int_sym.str_value) or
3585 int(hex_sym.str_value, 16) to get the integer value.
3586
3587 tri_value:
3588 The tristate value of the symbol as an integer. One of 0, 1, 2,
3589 representing n, m, y. Always 0 (n) for non-bool/tristate symbols.
3590
3591 This is the symbol value that's used outside of relation expressions
3592 (A, !A, A && B, A || B).
3593
3594 assignable:
3595 A tuple containing the tristate user values that can currently be
3596 assigned to the symbol (that would be respected), ordered from lowest (0,
3597 representing n) to highest (2, representing y). This corresponds to the
3598 selections available in the menuconfig interface. The set of assignable
3599 values is calculated from the symbol's visibility and selects/implies.
3600
3601 Returns the empty set for non-bool/tristate symbols and for symbols with
3602 visibility n. The other possible values are (0, 2), (0, 1, 2), (1, 2),
3603 (1,), and (2,). A (1,) or (2,) result means the symbol is visible but
3604 "locked" to m or y through a select, perhaps in combination with the
3605 visibility. menuconfig represents this as -M- and -*-, respectively.
3606
3607 For string/hex/int symbols, check if Symbol.visibility is non-0 (non-n)
3608 instead to determine if the value can be changed.
3609
3610 Some handy 'assignable' idioms:
3611
3612 # Is 'sym' an assignable (visible) bool/tristate symbol?
3613 if sym.assignable:
3614 # What's the highest value it can be assigned? [-1] in Python
3615 # gives the last element.
3616 sym_high = sym.assignable[-1]
3617
3618 # The lowest?
3619 sym_low = sym.assignable[0]
3620
3621 # Can the symbol be set to at least m?
3622 if sym.assignable[-1] >= 1:
3623 ...
3624
3625 # Can the symbol be set to m?
3626 if 1 in sym.assignable:
3627 ...
3628
3629 visibility:
3630 The visibility of the symbol. One of 0, 1, 2, representing n, m, y. See
3631 the module documentation for an overview of symbol values and visibility.
3632
3633 user_value:
3634 The user value of the symbol. None if no user value has been assigned
3635 (via Kconfig.load_config() or Symbol.set_value()).
3636
3637 Holds 0, 1, or 2 for bool/tristate symbols, and a string for the other
3638 symbol types.
3639
3640 WARNING: Do not assign directly to this. It will break things. Use
3641 Symbol.set_value().
3642
3643 config_string:
3644 The .config assignment string that would get written out for the symbol
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003645 by Kconfig.write_config(). Returns the empty string if no .config
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02003646 assignment would get written out.
3647
3648 In general, visible symbols, symbols with (active) defaults, and selected
3649 symbols get written out. This includes all non-n-valued bool/tristate
3650 symbols, and all visible string/int/hex symbols.
3651
3652 Symbols with the (no longer needed) 'option env=...' option generate no
3653 configuration output, and neither does the special
3654 'option defconfig_list' symbol.
3655
3656 Tip: This field is useful when generating custom configuration output,
3657 even for non-.config-like formats. To write just the symbols that would
3658 get written out to .config files, do this:
3659
3660 if sym.config_string:
3661 *Write symbol, e.g. by looking sym.str_value*
3662
3663 This is a superset of the symbols written out by write_autoconf().
3664 That function skips all n-valued symbols.
3665
3666 There usually won't be any great harm in just writing all symbols either,
3667 though you might get some special symbols and possibly some "redundant"
3668 n-valued symbol entries in there.
Carles Cufi591eb572018-01-07 15:54:57 +01003669
3670 nodes:
3671 A list of MenuNodes for this symbol. Will contain a single MenuNode for
3672 most symbols. Undefined and constant symbols have an empty nodes list.
3673 Symbols defined in multiple locations get one node for each location.
3674
3675 choice:
3676 Holds the parent Choice for choice symbols, and None for non-choice
3677 symbols. Doubles as a flag for whether a symbol is a choice symbol.
3678
3679 defaults:
3680 List of (default, cond) tuples for the symbol's 'default' properties. For
3681 example, 'default A && B if C || D' is represented as
3682 ((AND, A, B), (OR, C, D)). If no condition was given, 'cond' is
3683 self.kconfig.y.
3684
3685 Note that 'depends on' and parent dependencies are propagated to
3686 'default' conditions.
3687
3688 selects:
3689 List of (symbol, cond) tuples for the symbol's 'select' properties. For
3690 example, 'select A if B && C' is represented as (A, (AND, B, C)). If no
3691 condition was given, 'cond' is self.kconfig.y.
3692
3693 Note that 'depends on' and parent dependencies are propagated to 'select'
3694 conditions.
3695
3696 implies:
3697 Like 'selects', for imply.
3698
3699 ranges:
3700 List of (low, high, cond) tuples for the symbol's 'range' properties. For
3701 example, 'range 1 2 if A' is represented as (1, 2, A). If there is no
3702 condition, 'cond' is self.config.y.
3703
3704 Note that 'depends on' and parent dependencies are propagated to 'range'
3705 conditions.
3706
3707 Gotcha: 1 and 2 above will be represented as (undefined) Symbols rather
3708 than plain integers. Undefined symbols get their name as their string
3709 value, so this works out. The C tools work the same way.
3710
3711 rev_dep:
3712 Reverse dependency expression from other symbols selecting this symbol.
3713 Multiple selections get ORed together. A condition on a select is ANDed
3714 with the selecting symbol.
3715
3716 For example, if A has 'select FOO' and B has 'select FOO if C', then
3717 FOO's rev_dep will be (OR, A, (AND, B, C)).
3718
3719 weak_rev_dep:
3720 Like rev_dep, for imply.
3721
3722 direct_dep:
3723 The 'depends on' dependencies. If a symbol is defined in multiple
3724 locations, the dependencies at each location are ORed together.
3725
Carles Cufi81da97c2018-02-06 11:43:05 +01003726 Internally, this is used to implement 'imply', which only applies if the
3727 implied symbol has expr_value(self.direct_dep) != 0. 'depends on' and
Carles Cufi591eb572018-01-07 15:54:57 +01003728 parent dependencies are automatically propagated to the conditions of
3729 properties, so normally it's redundant to check the direct dependencies.
3730
Ulf Magnussond317a0e2018-06-22 07:08:56 +02003731 referenced:
3732 A set() with all symbols and choices referenced in the properties and
3733 property conditions of the symbol.
3734
3735 Also includes dependencies inherited from surrounding menus and if's.
3736 Choices appear in the dependencies of choice symbols.
3737
Carles Cufi591eb572018-01-07 15:54:57 +01003738 env_var:
3739 If the Symbol has an 'option env="FOO"' option, this contains the name
Ulf Magnusson4dc9e5b2018-05-16 20:24:03 +02003740 ("FOO") of the environment variable. None for symbols without no
3741 'option env'.
Carles Cufi591eb572018-01-07 15:54:57 +01003742
Ulf Magnusson4dc9e5b2018-05-16 20:24:03 +02003743 'option env="FOO"' acts like a 'default' property whose value is the
3744 value of $FOO.
Carles Cufi591eb572018-01-07 15:54:57 +01003745
Ulf Magnusson4dc9e5b2018-05-16 20:24:03 +02003746 Symbols with 'option env' are never written out to .config files, even if
3747 they are visible. env_var corresponds to a flag called SYMBOL_AUTO in the
3748 C implementation.
Carles Cufi591eb572018-01-07 15:54:57 +01003749
3750 is_allnoconfig_y:
3751 True if the symbol has 'option allnoconfig_y' set on it. This has no
3752 effect internally (except when printing symbols), but can be checked by
3753 scripts.
3754
3755 is_constant:
3756 True if the symbol is a constant (quoted) symbol.
3757
3758 kconfig:
3759 The Kconfig instance this symbol is from.
3760 """
3761 __slots__ = (
3762 "_cached_assignable",
3763 "_cached_str_val",
3764 "_cached_tri_val",
3765 "_cached_vis",
3766 "_dependents",
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003767 "_old_val",
Ulf Magnussond67095b2018-08-21 22:01:07 +02003768 "_visited",
Carles Cufi591eb572018-01-07 15:54:57 +01003769 "_was_set",
3770 "_write_to_conf",
Carles Cufi591eb572018-01-07 15:54:57 +01003771 "choice",
3772 "defaults",
3773 "direct_dep",
3774 "env_var",
3775 "implies",
3776 "is_allnoconfig_y",
3777 "is_constant",
3778 "kconfig",
3779 "name",
3780 "nodes",
3781 "orig_type",
3782 "ranges",
3783 "rev_dep",
3784 "selects",
3785 "user_value",
3786 "weak_rev_dep",
3787 )
3788
3789 #
3790 # Public interface
3791 #
3792
3793 @property
3794 def type(self):
3795 """
3796 See the class documentation.
3797 """
Ulf Magnusson213a88f2018-09-05 12:24:45 +02003798 if self.orig_type is TRISTATE and \
Carles Cufi591eb572018-01-07 15:54:57 +01003799 ((self.choice and self.choice.tri_value == 2) or
3800 not self.kconfig.modules.tri_value):
Ulf Magnusson905e65d2018-09-27 17:28:00 +02003801
Carles Cufi591eb572018-01-07 15:54:57 +01003802 return BOOL
3803
3804 return self.orig_type
3805
3806 @property
3807 def str_value(self):
3808 """
3809 See the class documentation.
3810 """
3811 if self._cached_str_val is not None:
3812 return self._cached_str_val
3813
3814 if self.orig_type in (BOOL, TRISTATE):
3815 # Also calculates the visibility, so invalidation safe
3816 self._cached_str_val = TRI_TO_STR[self.tri_value]
3817 return self._cached_str_val
3818
3819 # As a quirk of Kconfig, undefined symbols get their name as their
3820 # string value. This is why things like "FOO = bar" work for seeing if
3821 # FOO has the value "bar".
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01003822 if not self.orig_type: # UNKNOWN
Carles Cufi591eb572018-01-07 15:54:57 +01003823 self._cached_str_val = self.name
3824 return self.name
3825
3826 val = ""
3827 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
3828 # function call (property magic)
3829 vis = self.visibility
3830
3831 self._write_to_conf = (vis != 0)
3832
3833 if self.orig_type in (INT, HEX):
3834 # The C implementation checks the user value against the range in a
3835 # separate code path (post-processing after loading a .config).
3836 # Checking all values here instead makes more sense for us. It
3837 # requires that we check for a range first.
3838
3839 base = _TYPE_TO_BASE[self.orig_type]
3840
3841 # Check if a range is in effect
3842 for low_expr, high_expr, cond in self.ranges:
3843 if expr_value(cond):
3844 has_active_range = True
3845
3846 # The zeros are from the C implementation running strtoll()
3847 # on empty strings
3848 low = int(low_expr.str_value, base) if \
3849 _is_base_n(low_expr.str_value, base) else 0
3850 high = int(high_expr.str_value, base) if \
3851 _is_base_n(high_expr.str_value, base) else 0
3852
3853 break
3854 else:
3855 has_active_range = False
3856
Ulf Magnusson4b358752018-03-28 22:26:43 +02003857 # Defaults are used if the symbol is invisible, lacks a user value,
3858 # or has an out-of-range user value.
3859 use_defaults = True
Carles Cufi591eb572018-01-07 15:54:57 +01003860
Ulf Magnusson4b358752018-03-28 22:26:43 +02003861 if vis and self.user_value:
3862 user_val = int(self.user_value, base)
3863 if has_active_range and not low <= user_val <= high:
3864 num2str = str if base == 10 else hex
3865 self.kconfig._warn(
3866 "user value {} on the {} symbol {} ignored due to "
3867 "being outside the active range ([{}, {}]) -- falling "
3868 "back on defaults"
3869 .format(num2str(user_val), TYPE_TO_STR[self.orig_type],
3870 _name_and_loc(self),
3871 num2str(low), num2str(high)))
3872 else:
3873 # If the user value is well-formed and satisfies range
3874 # contraints, it is stored in exactly the same form as
3875 # specified in the assignment (with or without "0x", etc.)
3876 val = self.user_value
3877 use_defaults = False
Carles Cufi591eb572018-01-07 15:54:57 +01003878
Ulf Magnusson4b358752018-03-28 22:26:43 +02003879 if use_defaults:
Carles Cufi591eb572018-01-07 15:54:57 +01003880 # No user value or invalid user value. Look at defaults.
Carles Cufi591eb572018-01-07 15:54:57 +01003881
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02003882 # Used to implement the warning below
3883 has_default = False
3884
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02003885 for val_sym, cond in self.defaults:
3886 if expr_value(cond):
3887 has_default = self._write_to_conf = True
3888
3889 val = val_sym.str_value
Carles Cufi591eb572018-01-07 15:54:57 +01003890
3891 if _is_base_n(val, base):
3892 val_num = int(val, base)
3893 else:
3894 val_num = 0 # strtoll() on empty string
Ulf Magnussonec3eff52018-07-30 10:57:47 +02003895
3896 break
3897 else:
Carles Cufi591eb572018-01-07 15:54:57 +01003898 val_num = 0 # strtoll() on empty string
3899
3900 # This clamping procedure runs even if there's no default
3901 if has_active_range:
3902 clamp = None
3903 if val_num < low:
3904 clamp = low
3905 elif val_num > high:
3906 clamp = high
3907
3908 if clamp is not None:
3909 # The value is rewritten to a standard form if it is
3910 # clamped
3911 val = str(clamp) \
Ulf Magnusson213a88f2018-09-05 12:24:45 +02003912 if self.orig_type is INT else \
Carles Cufi591eb572018-01-07 15:54:57 +01003913 hex(clamp)
3914
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02003915 if has_default:
3916 num2str = str if base == 10 else hex
3917 self.kconfig._warn(
3918 "default value {} on {} clamped to {} due to "
3919 "being outside the active range ([{}, {}])"
3920 .format(val_num, _name_and_loc(self),
3921 num2str(clamp), num2str(low),
3922 num2str(high)))
3923
Ulf Magnusson213a88f2018-09-05 12:24:45 +02003924 elif self.orig_type is STRING:
Carles Cufi591eb572018-01-07 15:54:57 +01003925 if vis and self.user_value is not None:
3926 # If the symbol is visible and has a user value, use that
3927 val = self.user_value
3928 else:
3929 # Otherwise, look at defaults
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02003930 for val_sym, cond in self.defaults:
Carles Cufi591eb572018-01-07 15:54:57 +01003931 if expr_value(cond):
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02003932 val = val_sym.str_value
Carles Cufi81da97c2018-02-06 11:43:05 +01003933 self._write_to_conf = True
Ulf Magnussonec3eff52018-07-30 10:57:47 +02003934 break
Carles Cufi591eb572018-01-07 15:54:57 +01003935
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003936 # env_var corresponds to SYMBOL_AUTO in the C implementation, and is
3937 # also set on the defconfig_list symbol there. Test for the
3938 # defconfig_list symbol explicitly instead here, to avoid a nonsensical
3939 # env_var setting and the defconfig_list symbol being printed
3940 # incorrectly. This code is pretty cold anyway.
3941 if self.env_var is not None or self is self.kconfig.defconfig_list:
Carles Cufi591eb572018-01-07 15:54:57 +01003942 self._write_to_conf = False
3943
3944 self._cached_str_val = val
3945 return val
3946
3947 @property
3948 def tri_value(self):
3949 """
3950 See the class documentation.
3951 """
3952 if self._cached_tri_val is not None:
3953 return self._cached_tri_val
3954
3955 if self.orig_type not in (BOOL, TRISTATE):
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01003956 if self.orig_type: # != UNKNOWN
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02003957 # Would take some work to give the location here
3958 self.kconfig._warn(
3959 "The {} symbol {} is being evaluated in a logical context "
3960 "somewhere. It will always evaluate to n."
3961 .format(TYPE_TO_STR[self.orig_type], _name_and_loc(self)))
3962
Carles Cufi591eb572018-01-07 15:54:57 +01003963 self._cached_tri_val = 0
Carles Cufi81da97c2018-02-06 11:43:05 +01003964 return 0
Carles Cufi591eb572018-01-07 15:54:57 +01003965
Carles Cufi591eb572018-01-07 15:54:57 +01003966 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
3967 # function call (property magic)
3968 vis = self.visibility
3969 self._write_to_conf = (vis != 0)
3970
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003971 val = 0
3972
Carles Cufi591eb572018-01-07 15:54:57 +01003973 if not self.choice:
3974 # Non-choice symbol
3975
3976 if vis and self.user_value is not None:
3977 # If the symbol is visible and has a user value, use that
3978 val = min(self.user_value, vis)
3979
3980 else:
3981 # Otherwise, look at defaults and weak reverse dependencies
3982 # (implies)
3983
3984 for default, cond in self.defaults:
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02003985 dep_val = expr_value(cond)
3986 if dep_val:
3987 val = min(expr_value(default), dep_val)
Sebastian Bøe46239ba2018-03-14 10:36:59 +01003988 if val:
3989 self._write_to_conf = True
Ulf Magnussonec3eff52018-07-30 10:57:47 +02003990 break
Carles Cufi591eb572018-01-07 15:54:57 +01003991
3992 # Weak reverse dependencies are only considered if our
3993 # direct dependencies are met
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02003994 dep_val = expr_value(self.weak_rev_dep)
3995 if dep_val and expr_value(self.direct_dep):
3996 val = max(dep_val, val)
Carles Cufi591eb572018-01-07 15:54:57 +01003997 self._write_to_conf = True
3998
3999 # Reverse (select-related) dependencies take precedence
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02004000 dep_val = expr_value(self.rev_dep)
4001 if dep_val:
4002 if expr_value(self.direct_dep) < dep_val:
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02004003 self._warn_select_unsatisfied_deps()
4004
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02004005 val = max(dep_val, val)
Carles Cufi591eb572018-01-07 15:54:57 +01004006 self._write_to_conf = True
4007
Carles Cufi591eb572018-01-07 15:54:57 +01004008 # m is promoted to y for (1) bool symbols and (2) symbols with a
4009 # weak_rev_dep (from imply) of y
4010 if val == 1 and \
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004011 (self.type is BOOL or expr_value(self.weak_rev_dep) == 2):
Carles Cufi591eb572018-01-07 15:54:57 +01004012 val = 2
4013
4014 elif vis == 2:
4015 # Visible choice symbol in y-mode choice. The choice mode limits
4016 # the visibility of choice symbols, so it's sufficient to just
4017 # check the visibility of the choice symbols themselves.
4018 val = 2 if self.choice.selection is self else 0
4019
4020 elif vis and self.user_value:
4021 # Visible choice symbol in m-mode choice, with set non-0 user value
4022 val = 1
4023
4024 self._cached_tri_val = val
4025 return val
4026
4027 @property
4028 def assignable(self):
4029 """
4030 See the class documentation.
4031 """
Carles Cufi81da97c2018-02-06 11:43:05 +01004032 if self._cached_assignable is None:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004033 self._cached_assignable = self._assignable()
Carles Cufi591eb572018-01-07 15:54:57 +01004034
Carles Cufi591eb572018-01-07 15:54:57 +01004035 return self._cached_assignable
4036
4037 @property
4038 def visibility(self):
4039 """
4040 See the class documentation.
4041 """
Carles Cufi81da97c2018-02-06 11:43:05 +01004042 if self._cached_vis is None:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004043 self._cached_vis = _visibility(self)
Carles Cufi591eb572018-01-07 15:54:57 +01004044
Carles Cufi591eb572018-01-07 15:54:57 +01004045 return self._cached_vis
4046
4047 @property
4048 def config_string(self):
4049 """
4050 See the class documentation.
4051 """
4052 # Note: _write_to_conf is determined when the value is calculated. This
4053 # is a hidden function call due to property magic.
4054 val = self.str_value
4055 if not self._write_to_conf:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004056 return ""
Carles Cufi591eb572018-01-07 15:54:57 +01004057
4058 if self.orig_type in (BOOL, TRISTATE):
4059 return "{}{}={}\n" \
4060 .format(self.kconfig.config_prefix, self.name, val) \
4061 if val != "n" else \
4062 "# {}{} is not set\n" \
4063 .format(self.kconfig.config_prefix, self.name)
4064
4065 if self.orig_type in (INT, HEX):
4066 return "{}{}={}\n" \
4067 .format(self.kconfig.config_prefix, self.name, val)
4068
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004069 if self.orig_type is STRING:
Carles Cufi591eb572018-01-07 15:54:57 +01004070 return '{}{}="{}"\n' \
4071 .format(self.kconfig.config_prefix, self.name, escape(val))
4072
4073 _internal_error("Internal error while creating .config: unknown "
4074 'type "{}".'.format(self.orig_type))
4075
4076 def set_value(self, value):
4077 """
4078 Sets the user value of the symbol.
4079
4080 Equal in effect to assigning the value to the symbol within a .config
4081 file. For bool and tristate symbols, use the 'assignable' attribute to
4082 check which values can currently be assigned. Setting values outside
Carles Cufi81da97c2018-02-06 11:43:05 +01004083 'assignable' will cause Symbol.user_value to differ from
Carles Cufi591eb572018-01-07 15:54:57 +01004084 Symbol.str/tri_value (be truncated down or up).
4085
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004086 Setting a choice symbol to 2 (y) sets Choice.user_selection to the
4087 choice symbol in addition to setting Symbol.user_value.
Carles Cufi591eb572018-01-07 15:54:57 +01004088 Choice.user_selection is considered when the choice is in y mode (the
4089 "normal" mode).
4090
4091 Other symbols that depend (possibly indirectly) on this symbol are
4092 automatically recalculated to reflect the assigned value.
4093
4094 value:
4095 The user value to give to the symbol. For bool and tristate symbols,
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004096 n/m/y can be specified either as 0/1/2 (the usual format for tristate
4097 values in Kconfiglib) or as one of the strings "n"/"m"/"y". For other
4098 symbol types, pass a string.
Carles Cufi591eb572018-01-07 15:54:57 +01004099
4100 Values that are invalid for the type (such as "foo" or 1 (m) for a
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004101 BOOL or "0x123" for an INT) are ignored and won't be stored in
4102 Symbol.user_value. Kconfiglib will print a warning by default for
4103 invalid assignments, and set_value() will return False.
Carles Cufi591eb572018-01-07 15:54:57 +01004104
4105 Returns True if the value is valid for the type of the symbol, and
4106 False otherwise. This only looks at the form of the value. For BOOL and
4107 TRISTATE symbols, check the Symbol.assignable attribute to see what
4108 values are currently in range and would actually be reflected in the
4109 value of the symbol. For other symbol types, check whether the
4110 visibility is non-n.
4111 """
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004112 # If the new user value matches the old, nothing changes, and we can
4113 # save some work.
4114 #
4115 # This optimization is skipped for choice symbols: Setting a choice
4116 # symbol's user value to y might change the state of the choice, so it
4117 # wouldn't be safe (symbol user values always match the values set in a
4118 # .config file or via set_value(), and are never implicitly updated).
4119 if value == self.user_value and not self.choice:
Carles Cufi591eb572018-01-07 15:54:57 +01004120 self._was_set = True
4121 return True
4122
4123 # Check if the value is valid for our type
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004124 if not (self.orig_type is BOOL and value in (0, 2, "n", "y") or
4125 self.orig_type is TRISTATE and value in (0, 1, 2, "n", "m", "y") or
Ulf Magnusson6686efb2018-08-10 06:04:23 +02004126 (isinstance(value, str) and
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004127 (self.orig_type is STRING or
4128 self.orig_type is INT and _is_base_n(value, 10) or
4129 self.orig_type is HEX and _is_base_n(value, 16)
Ulf Magnusson6686efb2018-08-10 06:04:23 +02004130 and int(value, 16) >= 0))):
Carles Cufi591eb572018-01-07 15:54:57 +01004131
4132 # Display tristate values as n, m, y in the warning
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004133 self.kconfig._warn(
4134 "the value {} is invalid for {}, which has type {} -- "
4135 "assignment ignored"
4136 .format(TRI_TO_STR[value] if value in (0, 1, 2) else
4137 "'{}'".format(value),
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004138 _name_and_loc(self), TYPE_TO_STR[self.orig_type]))
Carles Cufi591eb572018-01-07 15:54:57 +01004139
4140 return False
4141
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004142 if self.orig_type in (BOOL, TRISTATE) and value in ("n", "m", "y"):
4143 value = STR_TO_TRI[value]
4144
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004145 self.user_value = value
4146 self._was_set = True
4147
Carles Cufi591eb572018-01-07 15:54:57 +01004148 if self.choice and value == 2:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004149 # Setting a choice symbol to y makes it the user selection of the
4150 # choice. Like for symbol user values, the user selection is not
4151 # guaranteed to match the actual selection of the choice, as
4152 # dependencies come into play.
Carles Cufi591eb572018-01-07 15:54:57 +01004153 self.choice.user_selection = self
4154 self.choice._was_set = True
Carles Cufi81da97c2018-02-06 11:43:05 +01004155 self.choice._rec_invalidate()
Carles Cufi591eb572018-01-07 15:54:57 +01004156 else:
Carles Cufi81da97c2018-02-06 11:43:05 +01004157 self._rec_invalidate_if_has_prompt()
Carles Cufi591eb572018-01-07 15:54:57 +01004158
4159 return True
4160
4161 def unset_value(self):
4162 """
4163 Resets the user value of the symbol, as if the symbol had never gotten
4164 a user value via Kconfig.load_config() or Symbol.set_value().
4165 """
4166 if self.user_value is not None:
4167 self.user_value = None
Carles Cufi81da97c2018-02-06 11:43:05 +01004168 self._rec_invalidate_if_has_prompt()
Carles Cufi591eb572018-01-07 15:54:57 +01004169
Ulf Magnussond317a0e2018-06-22 07:08:56 +02004170 @property
4171 def referenced(self):
4172 """
4173 See the class documentation.
4174 """
4175 res = set()
4176 for node in self.nodes:
4177 res |= node.referenced
4178
4179 return res
4180
Carles Cufi591eb572018-01-07 15:54:57 +01004181 def __repr__(self):
4182 """
4183 Returns a string with information about the symbol (including its name,
4184 value, visibility, and location(s)) when it is evaluated on e.g. the
4185 interactive Python prompt.
4186 """
4187 fields = []
4188
4189 fields.append("symbol " + self.name)
4190 fields.append(TYPE_TO_STR[self.type])
4191
4192 for node in self.nodes:
4193 if node.prompt:
4194 fields.append('"{}"'.format(node.prompt[0]))
4195
4196 # Only add quotes for non-bool/tristate symbols
4197 fields.append("value " +
4198 (self.str_value
4199 if self.orig_type in (BOOL, TRISTATE) else
4200 '"{}"'.format(self.str_value)))
4201
4202 if not self.is_constant:
4203 # These aren't helpful to show for constant symbols
4204
4205 if self.user_value is not None:
4206 # Only add quotes for non-bool/tristate symbols
4207 fields.append("user value " +
4208 (TRI_TO_STR[self.user_value]
4209 if self.orig_type in (BOOL, TRISTATE) else
4210 '"{}"'.format(self.user_value)))
4211
4212 fields.append("visibility " + TRI_TO_STR[self.visibility])
4213
4214 if self.choice:
4215 fields.append("choice symbol")
4216
4217 if self.is_allnoconfig_y:
4218 fields.append("allnoconfig_y")
4219
4220 if self is self.kconfig.defconfig_list:
4221 fields.append("is the defconfig_list symbol")
4222
4223 if self.env_var is not None:
4224 fields.append("from environment variable " + self.env_var)
4225
4226 if self is self.kconfig.modules:
4227 fields.append("is the modules symbol")
4228
4229 fields.append("direct deps " +
4230 TRI_TO_STR[expr_value(self.direct_dep)])
4231
4232 if self.nodes:
4233 for node in self.nodes:
4234 fields.append("{}:{}".format(node.filename, node.linenr))
4235 else:
4236 if self.is_constant:
4237 fields.append("constant")
4238 else:
4239 fields.append("undefined")
4240
4241 return "<{}>".format(", ".join(fields))
4242
4243 def __str__(self):
4244 """
4245 Returns a string representation of the symbol when it is printed,
Ulf Magnussone307ba32018-05-16 20:42:40 +02004246 matching the Kconfig format, with parent dependencies propagated.
Carles Cufi591eb572018-01-07 15:54:57 +01004247
Ulf Magnussone307ba32018-05-16 20:42:40 +02004248 The string is constructed by joining the strings returned by
4249 MenuNode.__str__() for each of the symbol's menu nodes, so symbols
4250 defined in multiple locations will return a string with all
4251 definitions.
Carles Cufi591eb572018-01-07 15:54:57 +01004252
4253 An empty string is returned for undefined and constant symbols.
4254 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +02004255 return self.custom_str(standard_sc_expr_str)
4256
4257 def custom_str(self, sc_expr_str_fn):
4258 """
4259 Works like Symbol.__str__(), but allows a custom format to be used for
4260 all symbol/choice references. See expr_str().
4261 """
4262 return "\n".join(node.custom_str(sc_expr_str_fn)
4263 for node in self.nodes)
Carles Cufi591eb572018-01-07 15:54:57 +01004264
4265 #
4266 # Private methods
4267 #
4268
4269 def __init__(self):
4270 """
4271 Symbol constructor -- not intended to be called directly by Kconfiglib
4272 clients.
4273 """
4274 # These attributes are always set on the instance from outside and
4275 # don't need defaults:
Carles Cufi591eb572018-01-07 15:54:57 +01004276 # kconfig
4277 # direct_dep
4278 # is_constant
4279 # name
4280 # rev_dep
4281 # weak_rev_dep
4282
4283 self.orig_type = UNKNOWN
4284 self.defaults = []
4285 self.selects = []
4286 self.implies = []
4287 self.ranges = []
4288
4289 self.nodes = []
4290
4291 self.user_value = \
4292 self.choice = \
4293 self.env_var = \
4294 self._cached_str_val = self._cached_tri_val = self._cached_vis = \
4295 self._cached_assignable = None
4296
4297 # _write_to_conf is calculated along with the value. If True, the
4298 # Symbol gets a .config entry.
4299
4300 self.is_allnoconfig_y = \
4301 self._was_set = \
4302 self._write_to_conf = False
4303
4304 # See Kconfig._build_dep()
4305 self._dependents = set()
4306
Ulf Magnussond67095b2018-08-21 22:01:07 +02004307 # Used during dependency loop detection and (independently) in
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02004308 # node_iter()
Ulf Magnussond67095b2018-08-21 22:01:07 +02004309 self._visited = 0
Ulf Magnusson54a59972018-06-20 00:07:51 +02004310
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004311 def _assignable(self):
4312 # Worker function for the 'assignable' attribute
4313
Carles Cufi591eb572018-01-07 15:54:57 +01004314 if self.orig_type not in (BOOL, TRISTATE):
4315 return ()
4316
4317 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4318 # function call (property magic)
4319 vis = self.visibility
4320
4321 if not vis:
4322 return ()
4323
4324 rev_dep_val = expr_value(self.rev_dep)
4325
4326 if vis == 2:
4327 if self.choice:
4328 return (2,)
4329
4330 if not rev_dep_val:
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004331 if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
Carles Cufi591eb572018-01-07 15:54:57 +01004332 return (0, 2)
4333 return (0, 1, 2)
4334
4335 if rev_dep_val == 2:
4336 return (2,)
4337
4338 # rev_dep_val == 1
4339
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004340 if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
Carles Cufi591eb572018-01-07 15:54:57 +01004341 return (2,)
4342 return (1, 2)
4343
4344 # vis == 1
4345
4346 # Must be a tristate here, because bool m visibility gets promoted to y
4347
4348 if not rev_dep_val:
4349 return (0, 1) if expr_value(self.weak_rev_dep) != 2 else (0, 2)
4350
4351 if rev_dep_val == 2:
4352 return (2,)
4353
4354 # vis == rev_dep_val == 1
4355
4356 return (1,)
4357
Carles Cufi591eb572018-01-07 15:54:57 +01004358 def _invalidate(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004359 # Marks the symbol as needing to be recalculated
4360
Carles Cufi591eb572018-01-07 15:54:57 +01004361 self._cached_str_val = self._cached_tri_val = self._cached_vis = \
4362 self._cached_assignable = None
4363
4364 def _rec_invalidate(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004365 # Invalidates the symbol and all items that (possibly) depend on it
4366
Carles Cufi591eb572018-01-07 15:54:57 +01004367 if self is self.kconfig.modules:
4368 # Invalidating MODULES has wide-ranging effects
4369 self.kconfig._invalidate_all()
4370 else:
4371 self._invalidate()
4372
4373 for item in self._dependents:
4374 # _cached_vis doubles as a flag that tells us whether 'item'
4375 # has cached values, because it's calculated as a side effect
4376 # of calculating all other (non-constant) cached values.
4377 #
4378 # If item._cached_vis is None, it means there can't be cached
4379 # values on other items that depend on 'item', because if there
4380 # were, some value on 'item' would have been calculated and
4381 # item._cached_vis set as a side effect. It's therefore safe to
4382 # stop the invalidation at symbols with _cached_vis None.
4383 #
4384 # This approach massively speeds up scripts that set a lot of
4385 # values, vs simply invalidating all possibly dependent symbols
4386 # (even when you already have a list of all the dependent
4387 # symbols, because some symbols get huge dependency trees).
4388 #
4389 # This gracefully handles dependency loops too, which is nice
4390 # for choices, where the choice depends on the choice symbols
4391 # and vice versa.
4392 if item._cached_vis is not None:
4393 item._rec_invalidate()
4394
Carles Cufi81da97c2018-02-06 11:43:05 +01004395 def _rec_invalidate_if_has_prompt(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004396 # Invalidates the symbol and its dependent symbols, but only if the
4397 # symbol has a prompt. User values never have an effect on promptless
4398 # symbols, so we skip invalidation for them as an optimization.
4399 #
4400 # This also prevents constant (quoted) symbols from being invalidated
4401 # if set_value() is called on them, which would cause them to lose
4402 # their value and break things.
4403 #
4404 # Prints a warning if the symbol has no prompt. In some contexts (e.g.
4405 # when loading a .config files) assignments to promptless symbols are
4406 # normal and expected, so the warning can be disabled.
Carles Cufi81da97c2018-02-06 11:43:05 +01004407
Carles Cufi81da97c2018-02-06 11:43:05 +01004408 for node in self.nodes:
4409 if node.prompt:
4410 self._rec_invalidate()
4411 return
4412
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02004413 if self.kconfig._warn_for_no_prompt:
Ulf Magnusson4b358752018-03-28 22:26:43 +02004414 self.kconfig._warn(_name_and_loc(self) + " has no prompt, meaning "
4415 "user values have no effect on it")
Carles Cufi81da97c2018-02-06 11:43:05 +01004416
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004417 def _str_default(self):
4418 # write_min_config() helper function. Returns the value the symbol
4419 # would get from defaults if it didn't have a user value. Uses exactly
4420 # the same algorithm as the C implementation (though a bit cleaned up),
4421 # for compatibility.
4422
4423 if self.orig_type in (BOOL, TRISTATE):
4424 val = 0
4425
4426 # Defaults, selects, and implies do not affect choice symbols
4427 if not self.choice:
4428 for default, cond in self.defaults:
4429 cond_val = expr_value(cond)
4430 if cond_val:
4431 val = min(expr_value(default), cond_val)
4432 break
4433
4434 val = max(expr_value(self.rev_dep),
4435 expr_value(self.weak_rev_dep),
4436 val)
4437
4438 # Transpose mod to yes if type is bool (possibly due to modules
4439 # being disabled)
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004440 if val == 1 and self.type is BOOL:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004441 val = 2
4442
4443 return TRI_TO_STR[val]
4444
4445 if self.orig_type in (STRING, INT, HEX):
4446 for default, cond in self.defaults:
4447 if expr_value(cond):
4448 return default.str_value
4449
4450 return ""
4451
Carles Cufi81da97c2018-02-06 11:43:05 +01004452 def _warn_select_unsatisfied_deps(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004453 # Helper for printing an informative warning when a symbol with
4454 # unsatisfied direct dependencies (dependencies from 'depends on', ifs,
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02004455 # and menus) is selected by some other symbol. Also warn if a symbol
4456 # whose direct dependencies evaluate to m is selected to y.
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004457
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02004458 msg = "{} has direct dependencies {} with value {}, but is " \
4459 "currently being {}-selected by the following symbols:" \
4460 .format(_name_and_loc(self), expr_str(self.direct_dep),
Ulf Magnussona56be6f2018-08-17 22:27:01 +02004461 TRI_TO_STR[expr_value(self.direct_dep)],
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02004462 TRI_TO_STR[expr_value(self.rev_dep)])
Ulf Magnusson4b358752018-03-28 22:26:43 +02004463
Ulf Magnussonb742b622018-04-11 22:01:59 +02004464 # The reverse dependencies from each select are ORed together
4465 for select in split_expr(self.rev_dep, OR):
Ulf Magnussona56be6f2018-08-17 22:27:01 +02004466 if expr_value(select) <= expr_value(self.direct_dep):
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02004467 # Only include selects that exceed the direct dependencies
Ulf Magnussonb742b622018-04-11 22:01:59 +02004468 continue
Carles Cufi81da97c2018-02-06 11:43:05 +01004469
Ulf Magnussonb742b622018-04-11 22:01:59 +02004470 # - 'select A if B' turns into A && B
4471 # - 'select A' just turns into A
4472 #
4473 # In both cases, we can split on AND and pick the first operand
4474 selecting_sym = split_expr(select, AND)[0]
Carles Cufi81da97c2018-02-06 11:43:05 +01004475
Ulf Magnussonb742b622018-04-11 22:01:59 +02004476 msg += "\n - {}, with value {}, direct dependencies {} " \
4477 "(value: {})" \
4478 .format(_name_and_loc(selecting_sym),
4479 selecting_sym.str_value,
4480 expr_str(selecting_sym.direct_dep),
4481 TRI_TO_STR[expr_value(selecting_sym.direct_dep)])
Carles Cufi81da97c2018-02-06 11:43:05 +01004482
4483 if isinstance(select, tuple):
4484 msg += ", and select condition {} (value: {})" \
4485 .format(expr_str(select[2]),
4486 TRI_TO_STR[expr_value(select[2])])
4487
Ulf Magnussonb742b622018-04-11 22:01:59 +02004488 self.kconfig._warn(msg)
Carles Cufi81da97c2018-02-06 11:43:05 +01004489
Carles Cufi591eb572018-01-07 15:54:57 +01004490class Choice(object):
4491 """
4492 Represents a choice statement:
4493
4494 choice
4495 ...
4496 endchoice
4497
4498 The following attributes are available on Choice instances. They should be
4499 treated as read-only, and some are implemented through @property magic (but
4500 are still efficient to access due to internal caching).
4501
4502 Note: Prompts, help texts, and locations are stored in the Choice's
4503 MenuNode(s) rather than in the Choice itself. Check the MenuNode class and
4504 the Choice.nodes attribute. This organization matches the C tools.
4505
4506 name:
4507 The name of the choice, e.g. "FOO" for 'choice FOO', or None if the
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02004508 Choice has no name.
Carles Cufi591eb572018-01-07 15:54:57 +01004509
4510 type:
4511 The type of the choice. One of BOOL, TRISTATE, UNKNOWN. UNKNOWN is for
4512 choices defined without a type where none of the contained symbols have a
4513 type either (otherwise the choice inherits the type of the first symbol
4514 defined with a type).
4515
4516 When running without modules (CONFIG_MODULES=n), TRISTATE choices
4517 magically change type to BOOL. This matches the C tools, and makes sense
4518 for menuconfig-like functionality.
4519
4520 orig_type:
4521 The type as given in the Kconfig file, without any magic applied. Used
4522 when printing the choice.
4523
4524 tri_value:
4525 The tristate value (mode) of the choice. A choice can be in one of three
4526 modes:
4527
4528 0 (n) - The choice is disabled and no symbols can be selected. For
4529 visible choices, this mode is only possible for choices with
4530 the 'optional' flag set (see kconfig-language.txt).
4531
4532 1 (m) - Any number of choice symbols can be set to m, the rest will
4533 be n.
4534
4535 2 (y) - One symbol will be y, the rest n.
4536
4537 Only tristate choices can be in m mode. The visibility of the choice is
4538 an upper bound on the mode, and the mode in turn is an upper bound on the
4539 visibility of the choice symbols.
4540
4541 To change the mode, use Choice.set_value().
4542
4543 Implementation note:
4544 The C tools internally represent choices as a type of symbol, with
4545 special-casing in many code paths. This is why there is a lot of
4546 similarity to Symbol. The value (mode) of a choice is really just a
4547 normal symbol value, and an implicit reverse dependency forces its
4548 lower bound to m for visible non-optional choices (the reverse
4549 dependency is 'm && <visibility>').
4550
4551 Symbols within choices get the choice propagated as a dependency to
4552 their properties. This turns the mode of the choice into an upper bound
4553 on e.g. the visibility of choice symbols, and explains the gotcha
4554 related to printing choice symbols mentioned in the module docstring.
4555
4556 Kconfiglib uses a separate Choice class only because it makes the code
4557 and interface less confusing (especially in a user-facing interface).
4558 Corresponding attributes have the same name in the Symbol and Choice
4559 classes, for consistency and compatibility.
4560
4561 assignable:
4562 See the symbol class documentation. Gives the assignable values (modes).
4563
4564 visibility:
4565 See the Symbol class documentation. Acts on the value (mode).
4566
4567 selection:
4568 The Symbol instance of the currently selected symbol. None if the Choice
4569 is not in y mode or has no selected symbol (due to unsatisfied
4570 dependencies on choice symbols).
4571
4572 WARNING: Do not assign directly to this. It will break things. Call
4573 sym.set_value(2) on the choice symbol you want to select instead.
4574
4575 user_value:
4576 The value (mode) selected by the user through Choice.set_value(). Either
4577 0, 1, or 2, or None if the user hasn't selected a mode. See
4578 Symbol.user_value.
4579
4580 WARNING: Do not assign directly to this. It will break things. Use
4581 Choice.set_value() instead.
4582
4583 user_selection:
4584 The symbol selected by the user (by setting it to y). Ignored if the
4585 choice is not in y mode, but still remembered so that the choice "snaps
4586 back" to the user selection if the mode is changed back to y. This might
4587 differ from 'selection' due to unsatisfied dependencies.
4588
4589 WARNING: Do not assign directly to this. It will break things. Call
4590 sym.set_value(2) on the choice symbol to be selected instead.
4591
4592 syms:
4593 List of symbols contained in the choice.
4594
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02004595 Obscure gotcha: If a symbol depends on the previous symbol within a
4596 choice so that an implicit menu is created, it won't be a choice symbol,
4597 and won't be included in 'syms'.
Carles Cufi591eb572018-01-07 15:54:57 +01004598
4599 nodes:
4600 A list of MenuNodes for this choice. In practice, the list will probably
4601 always contain a single MenuNode, but it is possible to give a choice a
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02004602 name and define it in multiple locations.
Carles Cufi591eb572018-01-07 15:54:57 +01004603
4604 defaults:
4605 List of (symbol, cond) tuples for the choice's 'defaults' properties. For
4606 example, 'default A if B && C' is represented as (A, (AND, B, C)). If
4607 there is no condition, 'cond' is self.config.y.
4608
4609 Note that 'depends on' and parent dependencies are propagated to
4610 'default' conditions.
4611
Ulf Magnussond3bfbfe2018-04-24 11:41:47 +02004612 direct_dep:
4613 See Symbol.direct_dep.
4614
Ulf Magnussond317a0e2018-06-22 07:08:56 +02004615 referenced:
4616 A set() with all symbols referenced in the properties and property
4617 conditions of the choice.
4618
4619 Also includes dependencies inherited from surrounding menus and if's.
4620
Carles Cufi591eb572018-01-07 15:54:57 +01004621 is_optional:
4622 True if the choice has the 'optional' flag set on it and can be in
4623 n mode.
4624
4625 kconfig:
4626 The Kconfig instance this choice is from.
4627 """
4628 __slots__ = (
4629 "_cached_assignable",
4630 "_cached_selection",
4631 "_cached_vis",
4632 "_dependents",
Ulf Magnussond67095b2018-08-21 22:01:07 +02004633 "_visited",
Carles Cufi591eb572018-01-07 15:54:57 +01004634 "_was_set",
4635 "defaults",
Ulf Magnussond3bfbfe2018-04-24 11:41:47 +02004636 "direct_dep",
Carles Cufi591eb572018-01-07 15:54:57 +01004637 "is_constant",
4638 "is_optional",
4639 "kconfig",
4640 "name",
4641 "nodes",
4642 "orig_type",
4643 "syms",
4644 "user_selection",
4645 "user_value",
4646 )
4647
4648 #
4649 # Public interface
4650 #
4651
4652 @property
4653 def type(self):
4654 """
4655 Returns the type of the choice. See Symbol.type.
4656 """
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004657 if self.orig_type is TRISTATE and not self.kconfig.modules.tri_value:
Carles Cufi591eb572018-01-07 15:54:57 +01004658 return BOOL
4659
4660 return self.orig_type
4661
4662 @property
4663 def str_value(self):
4664 """
4665 See the class documentation.
4666 """
4667 return TRI_TO_STR[self.tri_value]
4668
4669 @property
4670 def tri_value(self):
4671 """
4672 See the class documentation.
4673 """
4674 # This emulates a reverse dependency of 'm && visibility' for
4675 # non-optional choices, which is how the C implementation does it
4676
4677 val = 0 if self.is_optional else 1
4678
4679 if self.user_value is not None:
4680 val = max(val, self.user_value)
4681
4682 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4683 # function call (property magic)
4684 val = min(val, self.visibility)
4685
4686 # Promote m to y for boolean choices
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004687 return 2 if val == 1 and self.type is BOOL else val
Carles Cufi591eb572018-01-07 15:54:57 +01004688
4689 @property
4690 def assignable(self):
4691 """
4692 See the class documentation.
4693 """
Carles Cufi81da97c2018-02-06 11:43:05 +01004694 if self._cached_assignable is None:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004695 self._cached_assignable = self._assignable()
Carles Cufi591eb572018-01-07 15:54:57 +01004696
Carles Cufi591eb572018-01-07 15:54:57 +01004697 return self._cached_assignable
4698
4699 @property
4700 def visibility(self):
4701 """
4702 See the class documentation.
4703 """
Carles Cufi81da97c2018-02-06 11:43:05 +01004704 if self._cached_vis is None:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004705 self._cached_vis = _visibility(self)
Carles Cufi591eb572018-01-07 15:54:57 +01004706
Carles Cufi591eb572018-01-07 15:54:57 +01004707 return self._cached_vis
4708
4709 @property
4710 def selection(self):
4711 """
4712 See the class documentation.
4713 """
Carles Cufi81da97c2018-02-06 11:43:05 +01004714 if self._cached_selection is _NO_CACHED_SELECTION:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004715 self._cached_selection = self._selection()
Carles Cufi591eb572018-01-07 15:54:57 +01004716
Carles Cufi591eb572018-01-07 15:54:57 +01004717 return self._cached_selection
4718
4719 def set_value(self, value):
4720 """
4721 Sets the user value (mode) of the choice. Like for Symbol.set_value(),
4722 the visibility might truncate the value. Choices without the 'optional'
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004723 attribute (is_optional) can never be in n mode, but 0/"n" is still
4724 accepted since it's not a malformed value (though it will have no
4725 effect).
Carles Cufi591eb572018-01-07 15:54:57 +01004726
4727 Returns True if the value is valid for the type of the choice, and
4728 False otherwise. This only looks at the form of the value. Check the
4729 Choice.assignable attribute to see what values are currently in range
4730 and would actually be reflected in the mode of the choice.
4731 """
4732 if value == self.user_value:
4733 # We know the value must be valid if it was successfully set
4734 # previously
4735 self._was_set = True
4736 return True
4737
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004738 if not ((self.orig_type is BOOL and value in (0, 2, "n", "y") ) or
4739 (self.orig_type is TRISTATE and value in (0, 1, 2, "n", "m", "y"))):
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004740
4741 # Display tristate values as n, m, y in the warning
4742 self.kconfig._warn(
4743 "the value {} is invalid for {}, which has type {} -- "
4744 "assignment ignored"
4745 .format(TRI_TO_STR[value] if value in (0, 1, 2) else
4746 "'{}'".format(value),
Ulf Magnusson4b358752018-03-28 22:26:43 +02004747 _name_and_loc(self),
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004748 TYPE_TO_STR[self.orig_type]))
4749
Carles Cufi591eb572018-01-07 15:54:57 +01004750 return False
4751
Carles Cufi8f7fdad2018-02-07 11:32:09 +01004752 if value in ("n", "m", "y"):
4753 value = STR_TO_TRI[value]
4754
Carles Cufi591eb572018-01-07 15:54:57 +01004755 self.user_value = value
4756 self._was_set = True
4757 self._rec_invalidate()
4758
4759 return True
4760
4761 def unset_value(self):
4762 """
4763 Resets the user value (mode) and user selection of the Choice, as if
4764 the user had never touched the mode or any of the choice symbols.
4765 """
4766 if self.user_value is not None or self.user_selection:
4767 self.user_value = self.user_selection = None
4768 self._rec_invalidate()
4769
Ulf Magnussond317a0e2018-06-22 07:08:56 +02004770 @property
4771 def referenced(self):
4772 """
4773 See the class documentation.
4774 """
4775 res = set()
4776 for node in self.nodes:
4777 res |= node.referenced
4778
4779 return res
4780
Carles Cufi591eb572018-01-07 15:54:57 +01004781 def __repr__(self):
4782 """
4783 Returns a string with information about the choice when it is evaluated
4784 on e.g. the interactive Python prompt.
4785 """
4786 fields = []
4787
Ulf Magnusson6686efb2018-08-10 06:04:23 +02004788 fields.append("choice " + self.name if self.name else "choice")
Carles Cufi591eb572018-01-07 15:54:57 +01004789 fields.append(TYPE_TO_STR[self.type])
4790
4791 for node in self.nodes:
4792 if node.prompt:
4793 fields.append('"{}"'.format(node.prompt[0]))
4794
4795 fields.append("mode " + self.str_value)
4796
4797 if self.user_value is not None:
4798 fields.append('user mode {}'.format(TRI_TO_STR[self.user_value]))
4799
4800 if self.selection:
4801 fields.append("{} selected".format(self.selection.name))
4802
4803 if self.user_selection:
4804 user_sel_str = "{} selected by user" \
4805 .format(self.user_selection.name)
4806
4807 if self.selection is not self.user_selection:
4808 user_sel_str += " (overridden)"
4809
4810 fields.append(user_sel_str)
4811
4812 fields.append("visibility " + TRI_TO_STR[self.visibility])
4813
4814 if self.is_optional:
4815 fields.append("optional")
4816
4817 for node in self.nodes:
4818 fields.append("{}:{}".format(node.filename, node.linenr))
4819
4820 return "<{}>".format(", ".join(fields))
4821
4822 def __str__(self):
4823 """
4824 Returns a string representation of the choice when it is printed,
4825 matching the Kconfig format (though without the contained choice
Ulf Magnussone307ba32018-05-16 20:42:40 +02004826 symbols).
Carles Cufi591eb572018-01-07 15:54:57 +01004827
4828 See Symbol.__str__() as well.
4829 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +02004830 return self.custom_str(standard_sc_expr_str)
4831
4832 def custom_str(self, sc_expr_str_fn):
4833 """
4834 Works like Choice.__str__(), but allows a custom format to be used for
4835 all symbol/choice references. See expr_str().
4836 """
4837 return "\n".join(node.custom_str(sc_expr_str_fn)
4838 for node in self.nodes)
Carles Cufi591eb572018-01-07 15:54:57 +01004839
4840 #
4841 # Private methods
4842 #
4843
4844 def __init__(self):
4845 """
4846 Choice constructor -- not intended to be called directly by Kconfiglib
4847 clients.
4848 """
4849 # These attributes are always set on the instance from outside and
4850 # don't need defaults:
Ulf Magnussond3bfbfe2018-04-24 11:41:47 +02004851 # direct_dep
Carles Cufi591eb572018-01-07 15:54:57 +01004852 # kconfig
4853
4854 self.orig_type = UNKNOWN
4855 self.syms = []
4856 self.defaults = []
4857
4858 self.nodes = []
4859
4860 self.name = \
4861 self.user_value = self.user_selection = \
4862 self._cached_vis = self._cached_assignable = None
4863
4864 self._cached_selection = _NO_CACHED_SELECTION
4865
4866 # is_constant is checked by _make_depend_on(). Just set it to avoid
4867 # having to special-case choices.
4868 self.is_constant = self.is_optional = False
4869
4870 # See Kconfig._build_dep()
4871 self._dependents = set()
4872
Ulf Magnusson54a59972018-06-20 00:07:51 +02004873 # Used during dependency loop detection
Ulf Magnussond67095b2018-08-21 22:01:07 +02004874 self._visited = 0
Ulf Magnusson54a59972018-06-20 00:07:51 +02004875
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004876 def _assignable(self):
4877 # Worker function for the 'assignable' attribute
4878
Carles Cufi591eb572018-01-07 15:54:57 +01004879 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4880 # function call (property magic)
4881 vis = self.visibility
4882
4883 if not vis:
4884 return ()
4885
4886 if vis == 2:
4887 if not self.is_optional:
Ulf Magnusson213a88f2018-09-05 12:24:45 +02004888 return (2,) if self.type is BOOL else (1, 2)
4889 return (0, 2) if self.type is BOOL else (0, 1, 2)
Carles Cufi591eb572018-01-07 15:54:57 +01004890
4891 # vis == 1
4892
4893 return (0, 1) if self.is_optional else (1,)
4894
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004895 def _selection(self):
4896 # Worker function for the 'selection' attribute
4897
Carles Cufi591eb572018-01-07 15:54:57 +01004898 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4899 # function call (property magic)
4900 if self.tri_value != 2:
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004901 # Not in y mode, so no selection
Carles Cufi591eb572018-01-07 15:54:57 +01004902 return None
4903
4904 # Use the user selection if it's visible
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004905 if self.user_selection and self.user_selection.visibility:
Carles Cufi591eb572018-01-07 15:54:57 +01004906 return self.user_selection
4907
4908 # Otherwise, check if we have a default
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004909 return self._get_selection_from_defaults()
4910
4911 def _get_selection_from_defaults(self):
4912 # Check if we have a default
Carles Cufi591eb572018-01-07 15:54:57 +01004913 for sym, cond in self.defaults:
4914 # The default symbol must be visible too
4915 if expr_value(cond) and sym.visibility:
4916 return sym
4917
4918 # Otherwise, pick the first visible symbol, if any
4919 for sym in self.syms:
4920 if sym.visibility:
4921 return sym
4922
4923 # Couldn't find a selection
4924 return None
4925
4926 def _invalidate(self):
4927 self._cached_vis = self._cached_assignable = None
4928 self._cached_selection = _NO_CACHED_SELECTION
4929
4930 def _rec_invalidate(self):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01004931 # See Symbol._rec_invalidate()
4932
Carles Cufi591eb572018-01-07 15:54:57 +01004933 self._invalidate()
4934
4935 for item in self._dependents:
4936 if item._cached_vis is not None:
4937 item._rec_invalidate()
4938
4939class MenuNode(object):
4940 """
4941 Represents a menu node in the configuration. This corresponds to an entry
4942 in e.g. the 'make menuconfig' interface, though non-visible choices, menus,
4943 and comments also get menu nodes. If a symbol or choice is defined in
4944 multiple locations, it gets one menu node for each location.
4945
4946 The top-level menu node, corresponding to the implicit top-level menu, is
4947 available in Kconfig.top_node.
4948
4949 The menu nodes for a Symbol or Choice can be found in the
4950 Symbol/Choice.nodes attribute. Menus and comments are represented as plain
4951 menu nodes, with their text stored in the prompt attribute (prompt[0]).
4952 This mirrors the C implementation.
4953
4954 The following attributes are available on MenuNode instances. They should
4955 be viewed as read-only.
4956
4957 item:
4958 Either a Symbol, a Choice, or one of the constants MENU and COMMENT.
4959 Menus and comments are represented as plain menu nodes. Ifs are collapsed
4960 (matching the C implementation) and do not appear in the final menu tree.
4961
4962 next:
4963 The following menu node. None if there is no following node.
4964
4965 list:
4966 The first child menu node. None if there are no children.
4967
4968 Choices and menus naturally have children, but Symbols can also have
4969 children because of menus created automatically from dependencies (see
4970 kconfig-language.txt).
4971
4972 parent:
4973 The parent menu node. None if there is no parent.
4974
4975 prompt:
4976 A (string, cond) tuple with the prompt for the menu node and its
4977 conditional expression (which is self.kconfig.y if there is no
4978 condition). None if there is no prompt.
4979
4980 For symbols and choices, the prompt is stored in the MenuNode rather than
4981 the Symbol or Choice instance. For menus and comments, the prompt holds
4982 the text.
4983
Ulf Magnussone307ba32018-05-16 20:42:40 +02004984 defaults:
4985 The 'default' properties for this particular menu node. See
4986 symbol.defaults.
4987
4988 When evaluating defaults, you should use Symbol/Choice.defaults instead,
4989 as it include properties from all menu nodes (a symbol/choice can have
4990 multiple definition locations/menu nodes). MenuNode.defaults is meant for
4991 documentation generation.
4992
4993 selects:
4994 Like MenuNode.defaults, for selects.
4995
4996 implies:
4997 Like MenuNode.defaults, for implies.
4998
4999 ranges:
5000 Like MenuNode.defaults, for ranges.
5001
Carles Cufi591eb572018-01-07 15:54:57 +01005002 help:
5003 The help text for the menu node for Symbols and Choices. None if there is
5004 no help text. Always stored in the node rather than the Symbol or Choice.
5005 It is possible to have a separate help text at each location if a symbol
5006 is defined in multiple locations.
5007
5008 dep:
5009 The 'depends on' dependencies for the menu node, or self.kconfig.y if
5010 there are no dependencies. Parent dependencies are propagated to this
5011 attribute, and this attribute is then in turn propagated to the
5012 properties of symbols and choices.
5013
Ulf Magnussone307ba32018-05-16 20:42:40 +02005014 If a symbol or choice is defined in multiple locations, only the
5015 properties defined at a particular location get the corresponding
5016 MenuNode.dep dependencies propagated to them.
Carles Cufi591eb572018-01-07 15:54:57 +01005017
5018 visibility:
5019 The 'visible if' dependencies for the menu node (which must represent a
5020 menu), or self.kconfig.y if there are no 'visible if' dependencies.
5021 'visible if' dependencies are recursively propagated to the prompts of
5022 symbols and choices within the menu.
5023
Ulf Magnussond317a0e2018-06-22 07:08:56 +02005024 referenced:
5025 A set() with all symbols and choices referenced in the properties and
5026 property conditions of the menu node.
5027
5028 Also includes dependencies inherited from surrounding menus and if's.
5029 Choices appear in the dependencies of choice symbols.
5030
Carles Cufi591eb572018-01-07 15:54:57 +01005031 is_menuconfig:
Ulf Magnusson46a172a2018-04-04 17:13:34 +02005032 Set to True if the children of the menu node should be displayed in a
5033 separate menu. This is the case for the following items:
5034
5035 - Menus (node.item == MENU)
5036
5037 - Choices
5038
5039 - Symbols defined with the 'menuconfig' keyword. The children come from
5040 implicitly created submenus, and should be displayed in a separate
5041 menu rather than being indented.
5042
5043 'is_menuconfig' is just a hint on how to display the menu node. It's
5044 ignored internally by Kconfiglib, except when printing symbols.
Carles Cufi591eb572018-01-07 15:54:57 +01005045
5046 filename/linenr:
Ulf Magnussond67095b2018-08-21 22:01:07 +02005047 The location where the menu node appears. The filename is relative to
5048 $srctree (or to the current directory if $srctree isn't set), except
5049 absolute paths passed to 'source' and Kconfig.__init__() are preserved.
Carles Cufi591eb572018-01-07 15:54:57 +01005050
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02005051 include_path:
5052 A tuple of (filename, linenr) tuples, giving the locations of the
5053 'source' statements via which the Kconfig file containing this menu node
5054 was included. The first element is the location of the 'source' statement
5055 in the top-level Kconfig file passed to Kconfig.__init__(), etc.
5056
5057 Note that the Kconfig file of the menu node itself isn't included. Check
5058 'filename' and 'linenr' for that.
5059
Carles Cufi591eb572018-01-07 15:54:57 +01005060 kconfig:
5061 The Kconfig instance the menu node is from.
5062 """
5063 __slots__ = (
5064 "dep",
5065 "filename",
5066 "help",
Ulf Magnussonc1f54cc2018-08-24 01:31:41 +02005067 "include_path",
Carles Cufi591eb572018-01-07 15:54:57 +01005068 "is_menuconfig",
5069 "item",
5070 "kconfig",
5071 "linenr",
5072 "list",
5073 "next",
5074 "parent",
5075 "prompt",
5076 "visibility",
Ulf Magnussone307ba32018-05-16 20:42:40 +02005077
5078 # Properties
5079 "defaults",
5080 "selects",
5081 "implies",
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02005082 "ranges",
Carles Cufi591eb572018-01-07 15:54:57 +01005083 )
5084
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005085 def __init__(self):
5086 # Properties defined on this particular menu node. A local 'depends on'
5087 # only applies to these, in case a symbol is defined in multiple
5088 # locations.
5089 self.defaults = []
5090 self.selects = []
5091 self.implies = []
5092 self.ranges = []
5093
Ulf Magnussond317a0e2018-06-22 07:08:56 +02005094 @property
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005095 def referenced(self):
5096 """
Ulf Magnussond317a0e2018-06-22 07:08:56 +02005097 See the class documentation.
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005098 """
Ulf Magnussond317a0e2018-06-22 07:08:56 +02005099 # self.dep is included to catch dependencies from a lone 'depends on'
5100 # when there are no properties to propagate it to
5101 res = expr_items(self.dep)
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005102
5103 if self.prompt:
5104 res |= expr_items(self.prompt[1])
5105
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005106 if self.item is MENU:
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005107 res |= expr_items(self.visibility)
5108
5109 for value, cond in self.defaults:
5110 res |= expr_items(value)
5111 res |= expr_items(cond)
5112
5113 for value, cond in self.selects:
5114 res.add(value)
5115 res |= expr_items(cond)
5116
5117 for value, cond in self.implies:
5118 res.add(value)
5119 res |= expr_items(cond)
5120
5121 for low, high, cond in self.ranges:
5122 res.add(low)
5123 res.add(high)
5124 res |= expr_items(cond)
5125
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005126 return res
5127
Carles Cufi591eb572018-01-07 15:54:57 +01005128 def __repr__(self):
5129 """
5130 Returns a string with information about the menu node when it is
5131 evaluated on e.g. the interactive Python prompt.
5132 """
5133 fields = []
5134
5135 if isinstance(self.item, Symbol):
5136 fields.append("menu node for symbol " + self.item.name)
5137
5138 elif isinstance(self.item, Choice):
5139 s = "menu node for choice"
5140 if self.item.name is not None:
5141 s += " " + self.item.name
5142 fields.append(s)
5143
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005144 elif self.item is MENU:
Carles Cufi591eb572018-01-07 15:54:57 +01005145 fields.append("menu node for menu")
5146
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005147 elif self.item is COMMENT:
Carles Cufi591eb572018-01-07 15:54:57 +01005148 fields.append("menu node for comment")
5149
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005150 elif not self.item:
Carles Cufi591eb572018-01-07 15:54:57 +01005151 fields.append("menu node for if (should not appear in the final "
5152 " tree)")
5153
5154 else:
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005155 _internal_error("unable to determine type in MenuNode.__repr__()")
Carles Cufi591eb572018-01-07 15:54:57 +01005156
5157 if self.prompt:
5158 fields.append('prompt "{}" (visibility {})'
5159 .format(self.prompt[0],
5160 TRI_TO_STR[expr_value(self.prompt[1])]))
5161
5162 if isinstance(self.item, Symbol) and self.is_menuconfig:
5163 fields.append("is menuconfig")
5164
5165 fields.append("deps " + TRI_TO_STR[expr_value(self.dep)])
5166
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005167 if self.item is MENU:
Ulf Magnusson905e65d2018-09-27 17:28:00 +02005168 fields.append("'visible if' deps " +
Carles Cufi591eb572018-01-07 15:54:57 +01005169 TRI_TO_STR[expr_value(self.visibility)])
5170
5171 if isinstance(self.item, (Symbol, Choice)) and self.help is not None:
5172 fields.append("has help")
5173
5174 if self.list:
5175 fields.append("has child")
5176
5177 if self.next:
5178 fields.append("has next")
5179
5180 fields.append("{}:{}".format(self.filename, self.linenr))
5181
5182 return "<{}>".format(", ".join(fields))
5183
5184 def __str__(self):
5185 """
Ulf Magnussone307ba32018-05-16 20:42:40 +02005186 Returns a string representation of the menu node, matching the Kconfig
Carles Cufi591eb572018-01-07 15:54:57 +01005187 format.
5188
Ulf Magnussone307ba32018-05-16 20:42:40 +02005189 The output could (almost) be fed back into a Kconfig parser to redefine
5190 the object associated with the menu node. See the module documentation
5191 for a gotcha related to choice symbols.
5192
5193 For symbols and choices with multiple menu nodes (multiple definition
5194 locations), properties that aren't associated with a particular menu
5195 node are shown on all menu nodes ('option env=...', 'optional' for
5196 choices, etc.).
Carles Cufi591eb572018-01-07 15:54:57 +01005197 """
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005198 return self.custom_str(standard_sc_expr_str)
Ulf Magnussone307ba32018-05-16 20:42:40 +02005199
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005200 def custom_str(self, sc_expr_str_fn):
5201 """
5202 Works like MenuNode.__str__(), but allows a custom format to be used
5203 for all symbol/choice references. See expr_str().
5204 """
5205 return self._menu_comment_node_str(sc_expr_str_fn) \
Ulf Magnussone307ba32018-05-16 20:42:40 +02005206 if self.item in (MENU, COMMENT) else \
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005207 self._sym_choice_node_str(sc_expr_str_fn)
Ulf Magnussone307ba32018-05-16 20:42:40 +02005208
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005209 def _menu_comment_node_str(self, sc_expr_str_fn):
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005210 s = '{} "{}"\n'.format("menu" if self.item is MENU else "comment",
Ulf Magnussone307ba32018-05-16 20:42:40 +02005211 self.prompt[0])
5212
5213 if self.dep is not self.kconfig.y:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005214 s += "\tdepends on {}\n".format(expr_str(self.dep, sc_expr_str_fn))
Ulf Magnussone307ba32018-05-16 20:42:40 +02005215
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005216 if self.item is MENU and self.visibility is not self.kconfig.y:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005217 s += "\tvisible if {}\n".format(expr_str(self.visibility,
5218 sc_expr_str_fn))
Ulf Magnussone307ba32018-05-16 20:42:40 +02005219
5220 return s
5221
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005222 def _sym_choice_node_str(self, sc_expr_str_fn):
Ulf Magnussone307ba32018-05-16 20:42:40 +02005223 lines = []
5224
5225 def indent_add(s):
5226 lines.append("\t" + s)
5227
5228 def indent_add_cond(s, cond):
5229 if cond is not self.kconfig.y:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005230 s += " if " + expr_str(cond, sc_expr_str_fn)
Ulf Magnussone307ba32018-05-16 20:42:40 +02005231 indent_add(s)
5232
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005233 sc = self.item
Carles Cufi591eb572018-01-07 15:54:57 +01005234
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005235 if isinstance(sc, Symbol):
5236 lines.append(
5237 ("menuconfig " if self.is_menuconfig else "config ")
5238 + sc.name)
5239 else:
5240 lines.append("choice " + sc.name if sc.name else "choice")
Carles Cufi591eb572018-01-07 15:54:57 +01005241
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005242 if sc.orig_type: # != UNKNOWN
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005243 indent_add(TYPE_TO_STR[sc.orig_type])
Carles Cufi591eb572018-01-07 15:54:57 +01005244
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005245 if self.prompt:
5246 indent_add_cond(
5247 'prompt "{}"'.format(escape(self.prompt[0])),
5248 self.prompt[1])
5249
5250 if isinstance(sc, Symbol):
5251 if sc.is_allnoconfig_y:
5252 indent_add("option allnoconfig_y")
5253
5254 if sc is sc.kconfig.defconfig_list:
5255 indent_add("option defconfig_list")
5256
5257 if sc.env_var is not None:
5258 indent_add('option env="{}"'.format(sc.env_var))
5259
5260 if sc is sc.kconfig.modules:
5261 indent_add("option modules")
5262
5263 for low, high, cond in self.ranges:
Ulf Magnussone307ba32018-05-16 20:42:40 +02005264 indent_add_cond(
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005265 "range {} {}".format(sc_expr_str_fn(low),
5266 sc_expr_str_fn(high)),
5267 cond)
Carles Cufi591eb572018-01-07 15:54:57 +01005268
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005269 for default, cond in self.defaults:
5270 indent_add_cond("default " + expr_str(default, sc_expr_str_fn),
5271 cond)
Carles Cufi591eb572018-01-07 15:54:57 +01005272
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005273 if isinstance(sc, Choice) and sc.is_optional:
5274 indent_add("optional")
Ulf Magnussone307ba32018-05-16 20:42:40 +02005275
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005276 if isinstance(sc, Symbol):
5277 for select, cond in self.selects:
5278 indent_add_cond("select " + sc_expr_str_fn(select), cond)
Ulf Magnussone307ba32018-05-16 20:42:40 +02005279
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005280 for imply, cond in self.implies:
5281 indent_add_cond("imply " + sc_expr_str_fn(imply), cond)
Ulf Magnussone307ba32018-05-16 20:42:40 +02005282
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005283 if self.dep is not sc.kconfig.y:
5284 indent_add("depends on " + expr_str(self.dep, sc_expr_str_fn))
Ulf Magnussone307ba32018-05-16 20:42:40 +02005285
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005286 if self.help is not None:
5287 indent_add("help")
5288 for line in self.help.splitlines():
5289 indent_add(" " + line)
Ulf Magnussone307ba32018-05-16 20:42:40 +02005290
5291 return "\n".join(lines) + "\n"
Carles Cufi591eb572018-01-07 15:54:57 +01005292
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005293class Variable(object):
5294 """
5295 Represents a preprocessor variable/function.
5296
5297 The following attributes are available:
5298
5299 name:
5300 The name of the variable.
5301
5302 value:
5303 The unexpanded value of the variable.
5304
5305 expanded_value:
5306 The expanded value of the variable. For simple variables (those defined
5307 with :=), this will equal 'value'. Accessing this property will raise a
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02005308 KconfigError if the expansion seems to be stuck in a loop.
5309
5310 Note: Accessing this field is the same as calling expanded_value_w_args()
5311 with no arguments. I hadn't considered function arguments when adding it.
5312 It is retained for backwards compatibility though.
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005313
5314 is_recursive:
5315 True if the variable is recursive (defined with =).
5316 """
5317 __slots__ = (
5318 "_n_expansions",
5319 "is_recursive",
5320 "kconfig",
5321 "name",
5322 "value",
5323 )
5324
5325 @property
5326 def expanded_value(self):
5327 """
5328 See the class documentation.
5329 """
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02005330 return self.expanded_value_w_args()
5331
5332 def expanded_value_w_args(self, *args):
5333 """
5334 Returns the expanded value of the variable/function. Any arguments
5335 passed will be substituted for $(1), $(2), etc.
5336
5337 Raises a KconfigError if the expansion seems to be stuck in a loop.
5338 """
5339 return self.kconfig._fn_val((self.name,) + args)
5340
5341 def __repr__(self):
5342 return "<variable {}, {}, value '{}'>" \
5343 .format(self.name,
5344 "recursive" if self.is_recursive else "immediate",
5345 self.value)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005346
Ulf Magnusson54a59972018-06-20 00:07:51 +02005347class KconfigError(Exception):
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005348 "Exception raised for Kconfig-related errors"
Carles Cufi591eb572018-01-07 15:54:57 +01005349
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005350KconfigSyntaxError = KconfigError # Backwards compatibility
Ulf Magnusson54a59972018-06-20 00:07:51 +02005351
Carles Cufi591eb572018-01-07 15:54:57 +01005352class InternalError(Exception):
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005353 "Exception raised for internal errors"
5354
5355# Workaround:
5356#
5357# If 'errno' and 'strerror' are set on IOError, then __str__() always returns
5358# "[Errno <errno>] <strerror>", ignoring any custom message passed to the
5359# constructor. By defining our own subclass, we can use a custom message while
5360# also providing 'errno', 'strerror', and 'filename' to scripts.
5361class _KconfigIOError(IOError):
5362 def __init__(self, ioerror, msg):
5363 self.msg = msg
5364 super(_KconfigIOError, self).__init__(
5365 ioerror.errno, ioerror.strerror, ioerror.filename)
5366
5367 def __str__(self):
5368 return self.msg
Carles Cufi591eb572018-01-07 15:54:57 +01005369
5370#
5371# Public functions
5372#
5373
5374def expr_value(expr):
5375 """
5376 Evaluates the expression 'expr' to a tristate value. Returns 0 (n), 1 (m),
5377 or 2 (y).
5378
5379 'expr' must be an already-parsed expression from a Symbol, Choice, or
5380 MenuNode property. To evaluate an expression represented as a string, use
5381 Kconfig.eval_string().
5382
5383 Passing subexpressions of expressions to this function works as expected.
5384 """
5385 if not isinstance(expr, tuple):
5386 return expr.tri_value
5387
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005388 if expr[0] is AND:
Carles Cufi591eb572018-01-07 15:54:57 +01005389 v1 = expr_value(expr[1])
5390 # Short-circuit the n case as an optimization (~5% faster
5391 # allnoconfig.py and allyesconfig.py, as of writing)
5392 return 0 if not v1 else min(v1, expr_value(expr[2]))
5393
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005394 if expr[0] is OR:
Carles Cufi591eb572018-01-07 15:54:57 +01005395 v1 = expr_value(expr[1])
5396 # Short-circuit the y case as an optimization
5397 return 2 if v1 == 2 else max(v1, expr_value(expr[2]))
5398
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005399 if expr[0] is NOT:
Carles Cufi591eb572018-01-07 15:54:57 +01005400 return 2 - expr_value(expr[1])
5401
5402 if expr[0] in _RELATIONS:
5403 # Implements <, <=, >, >= comparisons as well. These were added to
5404 # kconfig in 31847b67 (kconfig: allow use of relations other than
5405 # (in)equality).
5406
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02005407 rel, v1, v2 = expr
Carles Cufi591eb572018-01-07 15:54:57 +01005408
5409 # If both operands are strings...
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02005410 if v1.orig_type is STRING and v2.orig_type is STRING:
Carles Cufi591eb572018-01-07 15:54:57 +01005411 # ...then compare them lexicographically
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02005412 comp = _strcmp(v1.str_value, v2.str_value)
Carles Cufi591eb572018-01-07 15:54:57 +01005413 else:
Carles Cufi81da97c2018-02-06 11:43:05 +01005414 # Otherwise, try to compare them as numbers
Carles Cufi591eb572018-01-07 15:54:57 +01005415 try:
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02005416 comp = _sym_to_num(v1) - _sym_to_num(v2)
Carles Cufi591eb572018-01-07 15:54:57 +01005417 except ValueError:
5418 # Fall back on a lexicographic comparison if the operands don't
5419 # parse as numbers
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02005420 comp = _strcmp(v1.str_value, v2.str_value)
Carles Cufi591eb572018-01-07 15:54:57 +01005421
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02005422 if rel is EQUAL: return 2*(comp == 0)
5423 if rel is UNEQUAL: return 2*(comp != 0)
5424 if rel is LESS: return 2*(comp < 0)
5425 if rel is LESS_EQUAL: return 2*(comp <= 0)
5426 if rel is GREATER: return 2*(comp > 0)
5427 if rel is GREATER_EQUAL: return 2*(comp >= 0)
Carles Cufi591eb572018-01-07 15:54:57 +01005428
5429 _internal_error("Internal error while evaluating expression: "
5430 "unknown operation {}.".format(expr[0]))
5431
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005432def standard_sc_expr_str(sc):
5433 """
5434 Standard symbol/choice printing function. Uses plain Kconfig syntax, and
5435 displays choices as <choice> (or <choice NAME>, for named choices).
5436
5437 See expr_str().
5438 """
5439 if isinstance(sc, Symbol):
5440 return '"{}"'.format(escape(sc.name)) if sc.is_constant else sc.name
5441
5442 # Choice
5443 return "<choice {}>".format(sc.name) if sc.name else "<choice>"
5444
5445def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
Carles Cufi591eb572018-01-07 15:54:57 +01005446 """
5447 Returns the string representation of the expression 'expr', as in a Kconfig
5448 file.
5449
5450 Passing subexpressions of expressions to this function works as expected.
Carles Cufi591eb572018-01-07 15:54:57 +01005451
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005452 sc_expr_str_fn (default: standard_sc_expr_str):
5453 This function is called for every symbol/choice (hence "sc") appearing in
5454 the expression, with the symbol/choice as the argument. It is expected to
5455 return a string to be used for the symbol/choice.
5456
5457 This can be used e.g. to turn symbols/choices into links when generating
5458 documentation, or for printing the value of each symbol/choice after it.
5459
5460 Note that quoted values are represented as constants symbols
5461 (Symbol.is_constant == True).
5462 """
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02005463 if not isinstance(expr, tuple):
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005464 return sc_expr_str_fn(expr)
Ulf Magnusson4b358752018-03-28 22:26:43 +02005465
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005466 if expr[0] is AND:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005467 return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn),
5468 _parenthesize(expr[2], OR, sc_expr_str_fn))
Carles Cufi591eb572018-01-07 15:54:57 +01005469
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005470 if expr[0] is OR:
Ulf Magnusson4b358752018-03-28 22:26:43 +02005471 # This turns A && B || C && D into "(A && B) || (C && D)", which is
5472 # redundant, but more readable
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005473 return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn),
5474 _parenthesize(expr[2], AND, sc_expr_str_fn))
Carles Cufi591eb572018-01-07 15:54:57 +01005475
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005476 if expr[0] is NOT:
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02005477 if isinstance(expr[1], tuple):
5478 return "!({})".format(expr_str(expr[1], sc_expr_str_fn))
5479 return "!" + sc_expr_str_fn(expr[1]) # Symbol
5480
Carles Cufi591eb572018-01-07 15:54:57 +01005481 # Relation
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005482 #
5483 # Relation operands are always symbols (quoted strings are constant
5484 # symbols)
5485 return "{} {} {}".format(sc_expr_str_fn(expr[1]), _REL_TO_STR[expr[0]],
5486 sc_expr_str_fn(expr[2]))
Carles Cufi591eb572018-01-07 15:54:57 +01005487
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005488def expr_items(expr):
5489 """
5490 Returns a set() of all items (symbols and choices) that appear in the
5491 expression 'expr'.
5492 """
5493
5494 res = set()
5495
5496 def rec(subexpr):
5497 if isinstance(subexpr, tuple):
5498 # AND, OR, NOT, or relation
5499
5500 rec(subexpr[1])
5501
5502 # NOTs only have a single operand
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005503 if subexpr[0] is not NOT:
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005504 rec(subexpr[2])
5505
5506 else:
5507 # Symbol or choice
5508 res.add(subexpr)
5509
5510 rec(expr)
5511 return res
5512
Ulf Magnussonb742b622018-04-11 22:01:59 +02005513def split_expr(expr, op):
5514 """
5515 Returns a list containing the top-level AND or OR operands in the
5516 expression 'expr', in the same (left-to-right) order as they appear in
5517 the expression.
5518
5519 This can be handy e.g. for splitting (weak) reverse dependencies
5520 from 'select' and 'imply' into individual selects/implies.
5521
5522 op:
5523 Either AND to get AND operands, or OR to get OR operands.
5524
5525 (Having this as an operand might be more future-safe than having two
5526 hardcoded functions.)
5527
5528
5529 Pseudo-code examples:
5530
5531 split_expr( A , OR ) -> [A]
5532 split_expr( A && B , OR ) -> [A && B]
5533 split_expr( A || B , OR ) -> [A, B]
5534 split_expr( A || B , AND ) -> [A || B]
5535 split_expr( A || B || (C && D) , OR ) -> [A, B, C && D]
5536
5537 # Second || is not at the top level
5538 split_expr( A || (B && (C || D)) , OR ) -> [A, B && (C || D)]
5539
5540 # Parentheses don't matter as long as we stay at the top level (don't
5541 # encounter any non-'op' nodes)
5542 split_expr( (A || B) || C , OR ) -> [A, B, C]
5543 split_expr( A || (B || C) , OR ) -> [A, B, C]
5544 """
5545 res = []
5546
5547 def rec(subexpr):
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005548 if isinstance(subexpr, tuple) and subexpr[0] is op:
Ulf Magnussonb742b622018-04-11 22:01:59 +02005549 rec(subexpr[1])
5550 rec(subexpr[2])
5551 else:
5552 res.append(subexpr)
5553
5554 rec(expr)
5555 return res
5556
Carles Cufi591eb572018-01-07 15:54:57 +01005557def escape(s):
5558 r"""
5559 Escapes the string 's' in the same fashion as is done for display in
5560 Kconfig format and when writing strings to a .config file. " and \ are
5561 replaced by \" and \\, respectively.
5562 """
Carles Cufi81da97c2018-02-06 11:43:05 +01005563 # \ must be escaped before " to avoid double escaping
5564 return s.replace("\\", r"\\").replace('"', r'\"')
5565
5566# unescape() helper
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005567_unescape_sub = re.compile(r"\\(.)").sub
Carles Cufi591eb572018-01-07 15:54:57 +01005568
5569def unescape(s):
5570 r"""
5571 Unescapes the string 's'. \ followed by any character is replaced with just
5572 that character. Used internally when reading .config files.
5573 """
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005574 return _unescape_sub(r"\1", s)
Carles Cufi591eb572018-01-07 15:54:57 +01005575
Ulf Magnussoncb95ea02018-06-07 12:27:37 +02005576def standard_kconfig():
5577 """
5578 Helper for tools. Loads the top-level Kconfig specified as the first
5579 command-line argument, or "Kconfig" if there are no command-line arguments.
5580 Returns the Kconfig instance.
5581
5582 Exits with sys.exit() (which raises a SystemExit exception) and prints a
5583 usage note to stderr if more than one command-line argument is passed.
5584 """
5585 if len(sys.argv) > 2:
5586 sys.exit("usage: {} [Kconfig]".format(sys.argv[0]))
5587
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005588 # Only show backtraces for unexpected exceptions
5589 try:
5590 return Kconfig("Kconfig" if len(sys.argv) < 2 else sys.argv[1])
5591 except (IOError, KconfigError) as e:
5592 # Some long exception messages have extra newlines for better
5593 # formatting when reported as an unhandled exception. Strip them here.
5594 sys.exit(str(e).strip())
Ulf Magnussoncb95ea02018-06-07 12:27:37 +02005595
5596def standard_config_filename():
5597 """
5598 Helper for tools. Returns the value of KCONFIG_CONFIG (which specifies the
5599 .config file to load/save) if it is set, and ".config" otherwise.
5600 """
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005601 return os.environ.get("KCONFIG_CONFIG", ".config")
Ulf Magnussoncb95ea02018-06-07 12:27:37 +02005602
Carles Cufi591eb572018-01-07 15:54:57 +01005603#
5604# Internal functions
5605#
5606
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005607def _visibility(sc):
5608 # Symbols and Choices have a "visibility" that acts as an upper bound on
5609 # the values a user can set for them, corresponding to the visibility in
5610 # e.g. 'make menuconfig'. This function calculates the visibility for the
5611 # Symbol or Choice 'sc' -- the logic is nearly identical.
5612
Carles Cufi591eb572018-01-07 15:54:57 +01005613 vis = 0
5614
5615 for node in sc.nodes:
5616 if node.prompt:
5617 vis = max(vis, expr_value(node.prompt[1]))
5618
5619 if isinstance(sc, Symbol) and sc.choice:
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005620 if sc.choice.orig_type is TRISTATE and \
5621 sc.orig_type is not TRISTATE and sc.choice.tri_value != 2:
Carles Cufi591eb572018-01-07 15:54:57 +01005622 # Non-tristate choice symbols are only visible in y mode
5623 return 0
5624
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005625 if sc.orig_type is TRISTATE and vis == 1 and sc.choice.tri_value == 2:
Carles Cufi591eb572018-01-07 15:54:57 +01005626 # Choice symbols with m visibility are not visible in y mode
5627 return 0
5628
5629 # Promote m to y if we're dealing with a non-tristate (possibly due to
5630 # modules being disabled)
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005631 if vis == 1 and sc.type is not TRISTATE:
Carles Cufi591eb572018-01-07 15:54:57 +01005632 return 2
5633
5634 return vis
5635
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005636def _make_depend_on(sc, expr):
5637 # Adds 'sc' (symbol or choice) as a "dependee" to all symbols in 'expr'.
5638 # Constant symbols in 'expr' are skipped as they can never change value
5639 # anyway.
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005640
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005641 if isinstance(expr, tuple):
5642 # AND, OR, NOT, or relation
Carles Cufi591eb572018-01-07 15:54:57 +01005643
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005644 _make_depend_on(sc, expr[1])
Carles Cufi591eb572018-01-07 15:54:57 +01005645
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005646 # NOTs only have a single operand
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005647 if expr[0] is not NOT:
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005648 _make_depend_on(sc, expr[2])
Carles Cufi591eb572018-01-07 15:54:57 +01005649
Ulf Magnusson59c8ae82018-06-14 18:47:49 +02005650 elif not expr.is_constant:
5651 # Non-constant symbol, or choice
5652 expr._dependents.add(sc)
Carles Cufi591eb572018-01-07 15:54:57 +01005653
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005654def _parenthesize(expr, type_, sc_expr_str_fn):
Ulf Magnusson4b358752018-03-28 22:26:43 +02005655 # expr_str() helper. Adds parentheses around expressions of type 'type_'.
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005656
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005657 if isinstance(expr, tuple) and expr[0] is type_:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02005658 return "({})".format(expr_str(expr, sc_expr_str_fn))
5659 return expr_str(expr, sc_expr_str_fn)
Carles Cufi591eb572018-01-07 15:54:57 +01005660
5661def _indentation(line):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005662 # Returns the length of the line's leading whitespace, treating tab stops
5663 # as being spaced 8 characters apart.
5664
Carles Cufi591eb572018-01-07 15:54:57 +01005665 line = line.expandtabs()
5666 return len(line) - len(line.lstrip())
5667
Ulf Magnussond67095b2018-08-21 22:01:07 +02005668def _ordered_unique(lst):
5669 # Returns 'lst' with any duplicates removed, preserving order. This hacky
5670 # version seems to be a common idiom. It relies on short-circuit evaluation
5671 # and set.add() returning None, which is falsy.
5672
5673 seen = set()
5674 seen_add = seen.add
5675 return [x for x in lst if x not in seen and not seen_add(x)]
5676
Carles Cufi591eb572018-01-07 15:54:57 +01005677def _is_base_n(s, n):
5678 try:
5679 int(s, n)
5680 return True
5681 except ValueError:
5682 return False
5683
5684def _strcmp(s1, s2):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005685 # strcmp()-alike that returns -1, 0, or 1
5686
Carles Cufi591eb572018-01-07 15:54:57 +01005687 return (s1 > s2) - (s1 < s2)
5688
Carles Cufi81da97c2018-02-06 11:43:05 +01005689def _sym_to_num(sym):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005690 # expr_value() helper for converting a symbol to a number. Raises
5691 # ValueError for symbols that can't be converted.
5692
Carles Cufi81da97c2018-02-06 11:43:05 +01005693 # For BOOL and TRISTATE, n/m/y count as 0/1/2. This mirrors 9059a3493ef
5694 # ("kconfig: fix relational operators for bool and tristate symbols") in
5695 # the C implementation.
5696 return sym.tri_value if sym.orig_type in (BOOL, TRISTATE) else \
5697 int(sym.str_value, _TYPE_TO_BASE[sym.orig_type])
5698
Carles Cufi591eb572018-01-07 15:54:57 +01005699def _internal_error(msg):
5700 raise InternalError(
5701 msg +
5702 "\nSorry! You may want to send an email to ulfalizer a.t Google's "
5703 "email service to tell me about this. Include the message above and "
5704 "the stack trace and describe what you were doing.")
5705
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005706def _decoding_error(e, filename, macro_linenr=None):
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02005707 # Gives the filename and context for UnicodeDecodeError's, which are a pain
5708 # to debug otherwise. 'e' is the UnicodeDecodeError object.
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005709 #
5710 # If the decoding error is for the output of a $(shell,...) command,
5711 # macro_linenr holds the line number where it was run (the exact line
5712 # number isn't available for decoding errors in files).
5713
5714 if macro_linenr is None:
5715 loc = filename
5716 else:
5717 loc = "output from macro at {}:{}".format(filename, macro_linenr)
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02005718
Ulf Magnusson54a59972018-06-20 00:07:51 +02005719 raise KconfigError(
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02005720 "\n"
5721 "Malformed {} in {}\n"
5722 "Context: {}\n"
5723 "Problematic data: {}\n"
5724 "Reason: {}".format(
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02005725 e.encoding, loc,
Ulf Magnussoncfb3c922018-04-26 18:34:32 +02005726 e.object[max(e.start - 40, 0):e.end + 40],
5727 e.object[e.start:e.end],
5728 e.reason))
5729
Ulf Magnusson4b358752018-03-28 22:26:43 +02005730def _name_and_loc(sc):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005731 # Helper for giving the symbol/choice name and location(s) in e.g. warnings
5732
Ulf Magnusson85f8c0d2018-10-15 02:05:45 +02005733 # Reuse the expression format. That way choices show up as
5734 # '<choice (name, if any)>'
5735 name = standard_sc_expr_str(sc)
Carles Cufi81da97c2018-02-06 11:43:05 +01005736
5737 if not sc.nodes:
5738 return name + " (undefined)"
5739
5740 return "{} (defined at {})".format(
5741 name,
5742 ", ".join("{}:{}".format(node.filename, node.linenr)
5743 for node in sc.nodes))
5744
5745
Carles Cufi591eb572018-01-07 15:54:57 +01005746# Menu manipulation
5747
5748def _expr_depends_on(expr, sym):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005749 # Reimplementation of expr_depends_symbol() from mconf.c. Used to determine
5750 # if a submenu should be implicitly created. This also influences which
5751 # items inside choice statements are considered choice items.
5752
Carles Cufi591eb572018-01-07 15:54:57 +01005753 if not isinstance(expr, tuple):
5754 return expr is sym
5755
5756 if expr[0] in (EQUAL, UNEQUAL):
5757 # Check for one of the following:
5758 # sym = m/y, m/y = sym, sym != n, n != sym
5759
5760 left, right = expr[1:]
5761
5762 if right is sym:
5763 left, right = right, left
Ulf Magnusson4b358752018-03-28 22:26:43 +02005764 elif left is not sym:
Carles Cufi591eb572018-01-07 15:54:57 +01005765 return False
5766
Ulf Magnusson905e65d2018-09-27 17:28:00 +02005767 return (expr[0] is EQUAL and right is sym.kconfig.m or
Carles Cufi591eb572018-01-07 15:54:57 +01005768 right is sym.kconfig.y) or \
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005769 (expr[0] is UNEQUAL and right is sym.kconfig.n)
Carles Cufi591eb572018-01-07 15:54:57 +01005770
Ulf Magnusson213a88f2018-09-05 12:24:45 +02005771 return expr[0] is AND and \
Ulf Magnusson4b358752018-03-28 22:26:43 +02005772 (_expr_depends_on(expr[1], sym) or
5773 _expr_depends_on(expr[2], sym))
Carles Cufi591eb572018-01-07 15:54:57 +01005774
Ulf Magnusson4b358752018-03-28 22:26:43 +02005775def _auto_menu_dep(node1, node2):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005776 # Returns True if node2 has an "automatic menu dependency" on node1. If
5777 # node2 has a prompt, we check its condition. Otherwise, we look directly
5778 # at node2.dep.
5779
Ulf Magnusson4b358752018-03-28 22:26:43 +02005780 # If node2 has no prompt, use its menu node dependencies instead
5781 return _expr_depends_on(node2.prompt[1] if node2.prompt else node2.dep,
5782 node1.item)
Carles Cufi591eb572018-01-07 15:54:57 +01005783
Carles Cufi591eb572018-01-07 15:54:57 +01005784def _flatten(node):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005785 # "Flattens" menu nodes without prompts (e.g. 'if' nodes and non-visible
5786 # symbols with children from automatic menu creation) so that their
5787 # children appear after them instead. This gives a clean menu structure
5788 # with no unexpected "jumps" in the indentation.
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02005789 #
5790 # Do not flatten promptless choices (which can appear "legitimitely" if a
5791 # named choice is defined in multiple locations to add on symbols). It
5792 # looks confusing, and the menuconfig already shows all choice symbols if
5793 # you enter the choice at some location with a prompt.
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005794
Carles Cufi591eb572018-01-07 15:54:57 +01005795 while node:
Ulf Magnusson9f8d4292018-08-29 10:16:51 +02005796 if node.list and not node.prompt and \
5797 not isinstance(node.item, Choice):
5798
Carles Cufi591eb572018-01-07 15:54:57 +01005799 last_node = node.list
5800 while 1:
5801 last_node.parent = node.parent
5802 if not last_node.next:
5803 break
5804 last_node = last_node.next
5805
5806 last_node.next = node.next
5807 node.next = node.list
5808 node.list = None
5809
5810 node = node.next
5811
5812def _remove_ifs(node):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005813 # Removes 'if' nodes (which can be recognized by MenuNode.item being None),
5814 # which are assumed to already have been flattened. The C implementation
5815 # doesn't bother to do this, but we expose the menu tree directly, and it
5816 # makes it nicer to work with.
5817
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005818 cur = node.list
5819 while cur and not cur.item:
Carles Cufi591eb572018-01-07 15:54:57 +01005820 cur = cur.next
5821
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005822 node.list = cur
5823
5824 while cur:
5825 next = cur.next
5826 while next and not next.item:
5827 next = next.next
5828
5829 # Equivalent to
5830 #
5831 # cur.next = next
5832 # cur = next
5833 #
5834 # due to tricky Python semantics. The order matters.
5835 cur.next = cur = next
Carles Cufi591eb572018-01-07 15:54:57 +01005836
5837def _finalize_choice(node):
Sebastian Bøe46239ba2018-03-14 10:36:59 +01005838 # Finalizes a choice, marking each symbol whose menu node has the choice as
5839 # the parent as a choice symbol, and automatically determining types if not
5840 # specified.
5841
Carles Cufi591eb572018-01-07 15:54:57 +01005842 choice = node.item
5843
5844 cur = node.list
5845 while cur:
5846 if isinstance(cur.item, Symbol):
5847 cur.item.choice = choice
5848 choice.syms.append(cur.item)
5849 cur = cur.next
5850
5851 # If no type is specified for the choice, its type is that of
5852 # the first choice item with a specified type
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005853 if not choice.orig_type:
Carles Cufi591eb572018-01-07 15:54:57 +01005854 for item in choice.syms:
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005855 if item.orig_type:
Carles Cufi591eb572018-01-07 15:54:57 +01005856 choice.orig_type = item.orig_type
5857 break
5858
5859 # Each choice item of UNKNOWN type gets the type of the choice
5860 for sym in choice.syms:
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01005861 if not sym.orig_type:
Carles Cufi591eb572018-01-07 15:54:57 +01005862 sym.orig_type = choice.orig_type
5863
Ulf Magnusson54a59972018-06-20 00:07:51 +02005864def _check_dep_loop_sym(sym, ignore_choice):
5865 # Detects dependency loops using depth-first search on the dependency graph
5866 # (which is calculated earlier in Kconfig._build_dep()).
5867 #
5868 # Algorithm:
5869 #
Ulf Magnussond67095b2018-08-21 22:01:07 +02005870 # 1. Symbols/choices start out with _visited = 0, meaning unvisited.
Ulf Magnusson54a59972018-06-20 00:07:51 +02005871 #
Ulf Magnussond67095b2018-08-21 22:01:07 +02005872 # 2. When a symbol/choice is first visited, _visited is set to 1, meaning
Ulf Magnusson54a59972018-06-20 00:07:51 +02005873 # "visited, potentially part of a dependency loop". The recursive
5874 # search then continues from the symbol/choice.
5875 #
Ulf Magnussond67095b2018-08-21 22:01:07 +02005876 # 3. If we run into a symbol/choice X with _visited already set to 1,
Ulf Magnusson54a59972018-06-20 00:07:51 +02005877 # there's a dependency loop. The loop is found on the call stack by
5878 # recording symbols while returning ("on the way back") until X is seen
5879 # again.
5880 #
5881 # 4. Once a symbol/choice and all its dependencies (or dependents in this
5882 # case) have been checked recursively without detecting any loops, its
Ulf Magnussond67095b2018-08-21 22:01:07 +02005883 # _visited is set to 2, meaning "visited, not part of a dependency
Ulf Magnusson54a59972018-06-20 00:07:51 +02005884 # loop".
5885 #
5886 # This saves work if we run into the symbol/choice again in later calls
5887 # to _check_dep_loop_sym(). We just return immediately.
5888 #
5889 # Choices complicate things, as every choice symbol depends on every other
5890 # choice symbol in a sense. When a choice is "entered" via a choice symbol
5891 # X, we visit all choice symbols from the choice except X, and prevent
5892 # immediately revisiting the choice with a flag (ignore_choice).
5893 #
5894 # Maybe there's a better way to handle this (different flags or the
5895 # like...)
5896
Ulf Magnussond67095b2018-08-21 22:01:07 +02005897 if not sym._visited:
5898 # sym._visited == 0, unvisited
Ulf Magnusson54a59972018-06-20 00:07:51 +02005899
Ulf Magnussond67095b2018-08-21 22:01:07 +02005900 sym._visited = 1
Ulf Magnusson54a59972018-06-20 00:07:51 +02005901
5902 for dep in sym._dependents:
5903 # Choices show up in Symbol._dependents when the choice has the
5904 # symbol in a 'prompt' or 'default' condition (e.g.
5905 # 'default ... if SYM').
5906 #
5907 # Since we aren't entering the choice via a choice symbol, all
5908 # choice symbols need to be checked, hence the None.
5909 loop = _check_dep_loop_choice(dep, None) \
5910 if isinstance(dep, Choice) \
5911 else _check_dep_loop_sym(dep, False)
5912
5913 if loop:
5914 # Dependency loop found
5915 return _found_dep_loop(loop, sym)
5916
5917 if sym.choice and not ignore_choice:
5918 loop = _check_dep_loop_choice(sym.choice, sym)
5919 if loop:
5920 # Dependency loop found
5921 return _found_dep_loop(loop, sym)
5922
5923 # The symbol is not part of a dependency loop
Ulf Magnussond67095b2018-08-21 22:01:07 +02005924 sym._visited = 2
Ulf Magnusson54a59972018-06-20 00:07:51 +02005925
5926 # No dependency loop found
5927 return None
5928
Ulf Magnussond67095b2018-08-21 22:01:07 +02005929 if sym._visited == 2:
Ulf Magnusson54a59972018-06-20 00:07:51 +02005930 # The symbol was checked earlier and is already known to not be part of
5931 # a dependency loop
5932 return None
5933
Ulf Magnussond67095b2018-08-21 22:01:07 +02005934 # sym._visited == 1, found a dependency loop. Return the symbol as the
Ulf Magnusson54a59972018-06-20 00:07:51 +02005935 # first element in it.
5936 return (sym,)
5937
5938def _check_dep_loop_choice(choice, skip):
Ulf Magnussond67095b2018-08-21 22:01:07 +02005939 if not choice._visited:
5940 # choice._visited == 0, unvisited
Ulf Magnusson54a59972018-06-20 00:07:51 +02005941
Ulf Magnussond67095b2018-08-21 22:01:07 +02005942 choice._visited = 1
Ulf Magnusson54a59972018-06-20 00:07:51 +02005943
5944 # Check for loops involving choice symbols. If we came here via a
5945 # choice symbol, skip that one, as we'd get a false positive
5946 # '<sym FOO> -> <choice> -> <sym FOO>' loop otherwise.
5947 for sym in choice.syms:
5948 if sym is not skip:
5949 # Prevent the choice from being immediately re-entered via the
5950 # "is a choice symbol" path by passing True
5951 loop = _check_dep_loop_sym(sym, True)
5952 if loop:
5953 # Dependency loop found
5954 return _found_dep_loop(loop, choice)
5955
5956 # The choice is not part of a dependency loop
Ulf Magnussond67095b2018-08-21 22:01:07 +02005957 choice._visited = 2
Ulf Magnusson54a59972018-06-20 00:07:51 +02005958
5959 # No dependency loop found
5960 return None
5961
Ulf Magnussond67095b2018-08-21 22:01:07 +02005962 if choice._visited == 2:
Ulf Magnusson54a59972018-06-20 00:07:51 +02005963 # The choice was checked earlier and is already known to not be part of
5964 # a dependency loop
5965 return None
5966
Ulf Magnussond67095b2018-08-21 22:01:07 +02005967 # choice._visited == 1, found a dependency loop. Return the choice as the
Ulf Magnusson54a59972018-06-20 00:07:51 +02005968 # first element in it.
5969 return (choice,)
5970
5971def _found_dep_loop(loop, cur):
5972 # Called "on the way back" when we know we have a loop
5973
5974 # Is the symbol/choice 'cur' where the loop started?
5975 if cur is not loop[0]:
5976 # Nope, it's just a part of the loop
5977 return loop + (cur,)
5978
5979 # Yep, we have the entire loop. Throw an exception that shows it.
5980
5981 msg = "\nDependency loop\n" \
5982 "===============\n\n"
5983
5984 for item in loop:
5985 if item is not loop[0]:
5986 msg += "...depends on "
5987 if isinstance(item, Symbol) and item.choice:
5988 msg += "the choice symbol "
5989
5990 msg += "{}, with definition...\n\n{}\n" \
5991 .format(_name_and_loc(item), item)
5992
5993 # Small wart: Since we reuse the already calculated
5994 # Symbol/Choice._dependents sets for recursive dependency detection, we
5995 # lose information on whether a dependency came from a 'select'/'imply'
5996 # condition or e.g. a 'depends on'.
5997 #
5998 # This might cause selecting symbols to "disappear". For example,
5999 # a symbol B having 'select A if C' gives a direct dependency from A to
6000 # C, since it corresponds to a reverse dependency of B && C.
6001 #
6002 # Always print reverse dependencies for symbols that have them to make
6003 # sure information isn't lost. I wonder if there's some neat way to
6004 # improve this.
6005
6006 if isinstance(item, Symbol):
6007 if item.rev_dep is not item.kconfig.n:
6008 msg += "(select-related dependencies: {})\n\n" \
6009 .format(expr_str(item.rev_dep))
6010
6011 if item.weak_rev_dep is not item.kconfig.n:
6012 msg += "(imply-related dependencies: {})\n\n" \
6013 .format(expr_str(item.rev_dep))
6014
6015 msg += "...depends again on {}".format(_name_and_loc(loop[0]))
6016
6017 raise KconfigError(msg)
6018
Ulf Magnussond67095b2018-08-21 22:01:07 +02006019
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006020# Predefined preprocessor functions
6021
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006022def _filename_fn(kconf, _):
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006023 return kconf._filename
6024
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006025def _lineno_fn(kconf, _):
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006026 return str(kconf._linenr)
6027
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006028def _info_fn(kconf, _, msg):
6029 print("{}:{}: {}".format(kconf._filename, kconf._linenr, msg))
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006030
6031 return ""
6032
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006033def _warning_if_fn(kconf, _, cond, msg):
6034 if cond == "y":
6035 kconf._warn(msg, kconf._filename, kconf._linenr)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006036
6037 return ""
6038
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006039def _error_if_fn(kconf, _, cond, msg):
6040 if cond == "y":
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006041 raise KconfigError("{}:{}: {}".format(
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006042 kconf._filename, kconf._linenr, msg))
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006043
6044 return ""
6045
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006046def _shell_fn(kconf, _, command):
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006047 stdout, stderr = subprocess.Popen(
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006048 command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006049 ).communicate()
6050
6051 if not _IS_PY2:
6052 try:
6053 stdout = stdout.decode(kconf._encoding)
6054 stderr = stderr.decode(kconf._encoding)
6055 except UnicodeDecodeError as e:
6056 _decoding_error(e, kconf._filename, kconf._linenr)
6057
6058 if stderr:
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006059 kconf._warn("'{}' wrote to stderr: {}".format(
Ulf Magnusson905e65d2018-09-27 17:28:00 +02006060 command, "\n".join(stderr.splitlines())),
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006061 kconf._filename, kconf._linenr)
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006062
Ulf Magnusson5cfe06b2018-10-10 15:08:45 +02006063 # Universal newlines with splitlines() (to prevent e.g. stray \r's in
6064 # command output on Windows), trailing newline removal, and
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006065 # newline-to-space conversion.
6066 #
6067 # On Python 3 versions before 3.6, it's not possible to specify the
6068 # encoding when passing universal_newlines=True to Popen() (the 'encoding'
6069 # parameter was added in 3.6), so we do this manual version instead.
6070 return "\n".join(stdout.splitlines()).rstrip("\n").replace("\n", " ")
6071
Carles Cufi591eb572018-01-07 15:54:57 +01006072#
6073# Public global constants
6074#
6075
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006076# Integers representing symbol types. UNKNOWN is 0 (falsy) to simplify some
6077# checks, though client code shouldn't rely on it (it was non-zero in older
6078# versions).
Carles Cufi591eb572018-01-07 15:54:57 +01006079(
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006080 UNKNOWN,
Carles Cufi591eb572018-01-07 15:54:57 +01006081 BOOL,
Carles Cufi591eb572018-01-07 15:54:57 +01006082 TRISTATE,
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006083 STRING,
6084 INT,
6085 HEX,
Carles Cufi591eb572018-01-07 15:54:57 +01006086) = range(6)
6087
Carles Cufi591eb572018-01-07 15:54:57 +01006088# Converts a symbol/choice type to a string
6089TYPE_TO_STR = {
6090 UNKNOWN: "unknown",
6091 BOOL: "bool",
6092 TRISTATE: "tristate",
6093 STRING: "string",
Carles Cufi591eb572018-01-07 15:54:57 +01006094 INT: "int",
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006095 HEX: "hex",
Carles Cufi591eb572018-01-07 15:54:57 +01006096}
6097
6098TRI_TO_STR = {
6099 0: "n",
6100 1: "m",
6101 2: "y",
6102}
6103
6104STR_TO_TRI = {
6105 "n": 0,
6106 "m": 1,
6107 "y": 2,
6108}
6109
6110#
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006111# Internal global constants (plus public expression type
6112# constants)
Carles Cufi591eb572018-01-07 15:54:57 +01006113#
6114
Ulf Magnusson213a88f2018-09-05 12:24:45 +02006115# Note:
6116#
6117# The token and type constants below are safe to test with 'is', which is a bit
6118# faster (~30% faster in a microbenchmark with Python 3 on my machine, and a
6119# few % faster for total parsing time), even without assuming Python's small
6120# integer optimization (which caches small integer objects). The constants end
6121# up pointing to unique integer objects, and since we consistently refer to
6122# them via the names below, we always get the same object.
6123#
6124# Client code would also need to use the names below, because the integer
6125# values can change e.g. when tokens get added. Client code would usually test
6126# with == too, which would be safe even in super obscure cases involving e.g.
6127# pickling (where 'is' would be a bad idea anyway) and no small-integer
6128# optimization.
6129
Ulf Magnussondc97fc22018-05-02 09:14:18 +02006130# Are we running on Python 2?
6131_IS_PY2 = sys.version_info[0] < 3
6132
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006133# Tokens, with values 1, 2, ... . Avoiding 0 simplifies some checks by making
6134# all tokens except empty strings truthy.
Carles Cufi591eb572018-01-07 15:54:57 +01006135(
6136 _T_ALLNOCONFIG_Y,
6137 _T_AND,
6138 _T_BOOL,
6139 _T_CHOICE,
6140 _T_CLOSE_PAREN,
6141 _T_COMMENT,
6142 _T_CONFIG,
6143 _T_DEFAULT,
6144 _T_DEFCONFIG_LIST,
6145 _T_DEF_BOOL,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006146 _T_DEF_HEX,
6147 _T_DEF_INT,
6148 _T_DEF_STRING,
Carles Cufi591eb572018-01-07 15:54:57 +01006149 _T_DEF_TRISTATE,
6150 _T_DEPENDS,
6151 _T_ENDCHOICE,
6152 _T_ENDIF,
6153 _T_ENDMENU,
6154 _T_ENV,
6155 _T_EQUAL,
6156 _T_GREATER,
6157 _T_GREATER_EQUAL,
Carles Cufi591eb572018-01-07 15:54:57 +01006158 _T_HELP,
6159 _T_HEX,
6160 _T_IF,
6161 _T_IMPLY,
6162 _T_INT,
6163 _T_LESS,
6164 _T_LESS_EQUAL,
6165 _T_MAINMENU,
6166 _T_MENU,
6167 _T_MENUCONFIG,
6168 _T_MODULES,
6169 _T_NOT,
6170 _T_ON,
6171 _T_OPEN_PAREN,
6172 _T_OPTION,
6173 _T_OPTIONAL,
6174 _T_OR,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006175 _T_ORSOURCE,
6176 _T_OSOURCE,
Carles Cufi591eb572018-01-07 15:54:57 +01006177 _T_PROMPT,
6178 _T_RANGE,
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006179 _T_RSOURCE,
Carles Cufi591eb572018-01-07 15:54:57 +01006180 _T_SELECT,
6181 _T_SOURCE,
6182 _T_STRING,
6183 _T_TRISTATE,
6184 _T_UNEQUAL,
6185 _T_VISIBLE,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006186) = range(1, 51)
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006187
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006188# Public integers representing expression types and menu and comment menu
6189# nodes
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006190#
6191# Having these match the value of the corresponding tokens removes the need
6192# for conversion
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006193
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006194AND = _T_AND
6195OR = _T_OR
6196NOT = _T_NOT
6197EQUAL = _T_EQUAL
6198UNEQUAL = _T_UNEQUAL
6199LESS = _T_LESS
6200LESS_EQUAL = _T_LESS_EQUAL
6201GREATER = _T_GREATER
6202GREATER_EQUAL = _T_GREATER_EQUAL
Carles Cufi591eb572018-01-07 15:54:57 +01006203
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006204MENU = _T_MENU
6205COMMENT = _T_COMMENT
6206
Carles Cufi591eb572018-01-07 15:54:57 +01006207# Keyword to token map, with the get() method assigned directly as a small
6208# optimization
6209_get_keyword = {
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006210 "---help---": _T_HELP,
Carles Cufi591eb572018-01-07 15:54:57 +01006211 "allnoconfig_y": _T_ALLNOCONFIG_Y,
6212 "bool": _T_BOOL,
6213 "boolean": _T_BOOL,
6214 "choice": _T_CHOICE,
6215 "comment": _T_COMMENT,
6216 "config": _T_CONFIG,
6217 "def_bool": _T_DEF_BOOL,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006218 "def_hex": _T_DEF_HEX,
6219 "def_int": _T_DEF_INT,
6220 "def_string": _T_DEF_STRING,
Carles Cufi591eb572018-01-07 15:54:57 +01006221 "def_tristate": _T_DEF_TRISTATE,
6222 "default": _T_DEFAULT,
6223 "defconfig_list": _T_DEFCONFIG_LIST,
6224 "depends": _T_DEPENDS,
6225 "endchoice": _T_ENDCHOICE,
6226 "endif": _T_ENDIF,
6227 "endmenu": _T_ENDMENU,
6228 "env": _T_ENV,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006229 "grsource": _T_ORSOURCE, # Backwards compatibility
6230 "gsource": _T_OSOURCE, # Backwards compatibility
Carles Cufi591eb572018-01-07 15:54:57 +01006231 "help": _T_HELP,
6232 "hex": _T_HEX,
6233 "if": _T_IF,
6234 "imply": _T_IMPLY,
6235 "int": _T_INT,
6236 "mainmenu": _T_MAINMENU,
6237 "menu": _T_MENU,
6238 "menuconfig": _T_MENUCONFIG,
6239 "modules": _T_MODULES,
6240 "on": _T_ON,
6241 "option": _T_OPTION,
6242 "optional": _T_OPTIONAL,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006243 "orsource": _T_ORSOURCE,
6244 "osource": _T_OSOURCE,
Carles Cufi591eb572018-01-07 15:54:57 +01006245 "prompt": _T_PROMPT,
6246 "range": _T_RANGE,
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006247 "rsource": _T_RSOURCE,
Carles Cufi591eb572018-01-07 15:54:57 +01006248 "select": _T_SELECT,
Ulf Magnusson547ed9b2018-05-08 09:31:48 +02006249 "source": _T_SOURCE,
Carles Cufi591eb572018-01-07 15:54:57 +01006250 "string": _T_STRING,
6251 "tristate": _T_TRISTATE,
6252 "visible": _T_VISIBLE,
6253}.get
6254
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006255# Tokens after which strings are expected. This is used to tell strings from
6256# constant symbol references during tokenization, both of which are enclosed in
6257# quotes.
6258#
6259# Identifier-like lexemes ("missing quotes") are also treated as strings after
6260# these tokens. _T_CHOICE is included to avoid symbols being registered for
6261# named choices.
Carles Cufi591eb572018-01-07 15:54:57 +01006262_STRING_LEX = frozenset((
6263 _T_BOOL,
6264 _T_CHOICE,
6265 _T_COMMENT,
Carles Cufi591eb572018-01-07 15:54:57 +01006266 _T_HEX,
6267 _T_INT,
6268 _T_MAINMENU,
6269 _T_MENU,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006270 _T_ORSOURCE,
6271 _T_OSOURCE,
Carles Cufi591eb572018-01-07 15:54:57 +01006272 _T_PROMPT,
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006273 _T_RSOURCE,
Carles Cufi591eb572018-01-07 15:54:57 +01006274 _T_SOURCE,
6275 _T_STRING,
6276 _T_TRISTATE,
6277))
6278
6279# Tokens for types, excluding def_bool, def_tristate, etc., for quick
6280# checks during parsing
6281_TYPE_TOKENS = frozenset((
6282 _T_BOOL,
6283 _T_TRISTATE,
6284 _T_INT,
6285 _T_HEX,
6286 _T_STRING,
6287))
6288
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006289
6290# Helper functions for getting compiled regular expressions, with the needed
6291# matching function returned directly as a small optimization.
6292#
Carles Cufi81da97c2018-02-06 11:43:05 +01006293# Use ASCII regex matching on Python 3. It's already the default on Python 2.
Carles Cufi81da97c2018-02-06 11:43:05 +01006294
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006295def _re_match(regex):
6296 return re.compile(regex, 0 if _IS_PY2 else re.ASCII).match
Carles Cufi591eb572018-01-07 15:54:57 +01006297
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006298def _re_search(regex):
6299 return re.compile(regex, 0 if _IS_PY2 else re.ASCII).search
Carles Cufi591eb572018-01-07 15:54:57 +01006300
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006301
6302# Various regular expressions used during parsing
6303
6304# The initial token on a line. Also eats leading and trailing whitespace, so
6305# that we can jump straight to the next token (or to the end of the line if
6306# there is only one token).
6307#
6308# This regex will also fail to match for empty lines and comment lines.
6309#
Ulf Magnusson213a88f2018-09-05 12:24:45 +02006310# '$' is included to detect preprocessor variable assignments with macro
6311# expansions in the left-hand side.
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006312_command_match = _re_match(r"\s*([$A-Za-z0-9_-]+)\s*")
6313
6314# An identifier/keyword after the first token. Also eats trailing whitespace.
Ulf Magnusson213a88f2018-09-05 12:24:45 +02006315# '$' is included to detect identifiers containing macro expansions.
6316_id_keyword_match = _re_match(r"([$A-Za-z0-9_/.-]+)\s*")
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006317
6318# A fragment in the left-hand side of a preprocessor variable assignment. These
6319# are the portions between macro expansions ($(foo)). Macros are supported in
6320# the LHS (variable name).
6321_assignment_lhs_fragment_match = _re_match("[A-Za-z0-9_-]*")
6322
6323# The assignment operator and value (right-hand side) in a preprocessor
6324# variable assignment
6325_assignment_rhs_match = _re_match(r"\s*(=|:=|\+=)\s*(.*)")
6326
6327# Special characters/strings while expanding a macro (')', ',', and '$(')
6328_macro_special_search = _re_search(r"\)|,|\$\(")
6329
6330# Special characters/strings while expanding a string (quotes, '\', and '$(')
6331_string_special_search = _re_search(r'"|\'|\\|\$\(')
6332
Ulf Magnusson213a88f2018-09-05 12:24:45 +02006333# Special characters/strings while expanding a symbol name. Also includes
6334# end-of-line, in case the macro is the last thing on the line.
6335_name_special_search = _re_search(r'[^$A-Za-z0-9_/.-]|\$\(|$')
6336
Ulf Magnussonf6bf8972018-07-10 15:52:21 +02006337# A valid right-hand side for an assignment to a string symbol in a .config
6338# file, including escaped characters. Extracts the contents.
6339_conf_string_match = _re_match(r'"((?:[^\\"]|\\.)*)"')
6340
Carles Cufi591eb572018-01-07 15:54:57 +01006341
6342# Token to type mapping
6343_TOKEN_TO_TYPE = {
6344 _T_BOOL: BOOL,
6345 _T_DEF_BOOL: BOOL,
Ulf Magnusson6686efb2018-08-10 06:04:23 +02006346 _T_DEF_HEX: HEX,
6347 _T_DEF_INT: INT,
6348 _T_DEF_STRING: STRING,
Carles Cufi591eb572018-01-07 15:54:57 +01006349 _T_DEF_TRISTATE: TRISTATE,
6350 _T_HEX: HEX,
6351 _T_INT: INT,
6352 _T_STRING: STRING,
6353 _T_TRISTATE: TRISTATE,
6354}
6355
6356# Constant representing that there's no cached choice selection. This is
6357# distinct from a cached None (no selection). We create a unique object (any
6358# will do) for it so we can test with 'is'.
6359_NO_CACHED_SELECTION = object()
6360
6361# Used in comparisons. 0 means the base is inferred from the format of the
Carles Cufi81da97c2018-02-06 11:43:05 +01006362# string.
Carles Cufi591eb572018-01-07 15:54:57 +01006363_TYPE_TO_BASE = {
Carles Cufi591eb572018-01-07 15:54:57 +01006364 HEX: 16,
6365 INT: 10,
6366 STRING: 0,
Carles Cufi591eb572018-01-07 15:54:57 +01006367 UNKNOWN: 0,
6368}
6369
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006370# Note: These constants deliberately equal the corresponding tokens (_T_EQUAL,
6371# _T_UNEQUAL, etc.), which removes the need for conversion
Carles Cufi591eb572018-01-07 15:54:57 +01006372_RELATIONS = frozenset((
6373 EQUAL,
6374 UNEQUAL,
6375 LESS,
6376 LESS_EQUAL,
6377 GREATER,
6378 GREATER_EQUAL,
6379))
6380
Carles Cufi591eb572018-01-07 15:54:57 +01006381_REL_TO_STR = {
6382 EQUAL: "=",
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006383 UNEQUAL: "!=",
Carles Cufi591eb572018-01-07 15:54:57 +01006384 LESS: "<",
6385 LESS_EQUAL: "<=",
Sebastian Bøe46239ba2018-03-14 10:36:59 +01006386 GREATER: ">",
6387 GREATER_EQUAL: ">=",
Carles Cufi591eb572018-01-07 15:54:57 +01006388}
Ulf Magnussona56be6f2018-08-17 22:27:01 +02006389
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006390_INIT_SRCTREE_NOTE = """\
Ulf Magnussona56be6f2018-08-17 22:27:01 +02006391NOTE: Starting with Kconfiglib 10.0.0, the Kconfig filename passed to
Ulf Magnussond67095b2018-08-21 22:01:07 +02006392Kconfig.__init__() is looked up relative to $srctree (which is set to '{}')
Ulf Magnussona56be6f2018-08-17 22:27:01 +02006393instead of relative to the working directory. Previously, $srctree only applied
6394to files being source'd within Kconfig files. This change makes running scripts
6395out-of-tree work seamlessly, with no special coding required. Sorry for the
6396backwards compatibility break!
Ulf Magnussondc6b0c82018-11-04 01:58:08 +01006397"""