1 # Copyright (c) 2011-2019, Ulf Magnusson
2 # SPDX-License-Identifier: ISC
8 Kconfiglib is a Python 2/3 library for scripting and extracting information
9 from Kconfig (https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt)
10 configuration systems.
12 See the homepage at https://github.com/ulfalizer/Kconfiglib for a longer
15 Since Kconfiglib 12.0.0, the library version is available in
16 kconfiglib.VERSION, which is a (<major>, <minor>, <patch>) tuple, e.g.
20 Using Kconfiglib on the Linux kernel with the Makefile targets
21 ==============================================================
23 For the Linux kernel, a handy interface is provided by the
24 scripts/kconfig/Makefile patch, which can be applied with either 'git am' or
27 $ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | git am
28 $ wget -qO- https://raw.githubusercontent.com/ulfalizer/Kconfiglib/master/makefile.patch | patch -p1
30 Warning: Not passing -p1 to patch will cause the wrong file to be patched.
32 Please tell me if the patch does not apply. It should be trivial to apply
33 manually, as it's just a block of text that needs to be inserted near the other
34 *conf: targets in scripts/kconfig/Makefile.
36 Look further down for a motivation for the Makefile patch and for instructions
37 on how you can use Kconfiglib without it.
39 If you do not wish to install Kconfiglib via pip, the Makefile patch is set up
40 so that you can also just clone Kconfiglib into the kernel root:
42 $ git clone git://github.com/ulfalizer/Kconfiglib.git
43 $ git am Kconfiglib/makefile.patch (or 'patch -p1 < Kconfiglib/makefile.patch')
45 Warning: The directory name Kconfiglib/ is significant in this case, because
46 it's added to PYTHONPATH by the new targets in makefile.patch.
48 The targets added by the Makefile patch are described in the following
55 This target runs the curses menuconfig interface with Python 3. As of
56 Kconfiglib 12.2.0, both Python 2 and Python 3 are supported (previously, only
57 Python 3 was supported, so this was a backport).
63 This target runs the Tkinter menuconfig interface. Both Python 2 and Python 3
64 are supported. To change the Python interpreter used, pass
65 PYTHONCMD=<executable> to 'make'. The default is 'python'.
68 make [ARCH=<arch>] iscriptconfig
69 --------------------------------
71 This target gives an interactive Python prompt where a Kconfig instance has
72 been preloaded and is available in 'kconf'. To change the Python interpreter
73 used, pass PYTHONCMD=<executable> to 'make'. The default is 'python'.
75 To get a feel for the API, try evaluating and printing the symbols in
76 kconf.defined_syms, and explore the MenuNode menu tree starting at
77 kconf.top_node by following 'next' and 'list' pointers.
79 The item contained in a menu node is found in MenuNode.item (note that this can
80 be one of the constants kconfiglib.MENU and kconfiglib.COMMENT), and all
81 symbols and choices have a 'nodes' attribute containing their menu nodes
82 (usually only one). Printing a menu node will print its item, in Kconfig
85 If you want to look up a symbol by name, use the kconf.syms dictionary.
88 make scriptconfig SCRIPT=<script> [SCRIPT_ARG=<arg>]
89 ----------------------------------------------------
91 This target runs the Python script given by the SCRIPT parameter on the
92 configuration. sys.argv[1] holds the name of the top-level Kconfig file
93 (currently always "Kconfig" in practice), and sys.argv[2] holds the SCRIPT_ARG
96 See the examples/ subdirectory for example scripts.
102 This target prints a list of all environment variables referenced from the
103 Kconfig files, together with their values. See the
104 Kconfiglib/examples/dumpvars.py script.
106 Only environment variables that are referenced via the Kconfig preprocessor
107 $(FOO) syntax are included. The preprocessor was added in Linux 4.18.
110 Using Kconfiglib without the Makefile targets
111 =============================================
113 The make targets are only needed to pick up environment variables exported from
114 the Kbuild makefiles and referenced inside Kconfig files, via e.g.
115 'source "arch/$(SRCARCH)/Kconfig" and commands run via '$(shell,...)'.
117 These variables are referenced as of writing (Linux 4.18), together with sample
123 KERNELVERSION (4.18.0)
127 CC_VERSION_TEXT (gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0)
129 Older kernels only reference ARCH, SRCARCH, and KERNELVERSION.
131 If your kernel is recent enough (4.18+), you can get a list of referenced
132 environment variables via 'make dumpvarsconfig' (see above). Note that this
133 command is added by the Makefile patch.
135 To run Kconfiglib without the Makefile patch, set the environment variables
138 $ srctree=. ARCH=x86 SRCARCH=x86 KERNELVERSION=`make kernelversion` ... python(3)
139 >>> import kconfiglib
140 >>> kconf = kconfiglib.Kconfig() # filename defaults to "Kconfig"
142 Search the top-level Makefile for "Additional ARCH settings" to see other
143 possibilities for ARCH and SRCARCH.
146 Intro to symbol values
147 ======================
149 Kconfiglib has the same assignment semantics as the C implementation.
151 Any symbol can be assigned a value by the user (via Kconfig.load_config() or
152 Symbol.set_value()), but this user value is only respected if the symbol is
153 visible, which corresponds to it (currently) being visible in the menuconfig
156 For symbols with prompts, the visibility of the symbol is determined by the
157 condition on the prompt. Symbols without prompts are never visible, so setting
158 a user value on them is pointless. A warning will be printed by default if
159 Symbol.set_value() is called on a promptless symbol. Assignments to promptless
160 symbols are normal within a .config file, so no similar warning will be printed
163 Dependencies from parents and 'if'/'depends on' are propagated to properties,
164 including prompts, so these two configurations are logically equivalent:
188 tristate "foo" if A && B && C && D
189 default y if A && B && C
193 In this example, A && B && C && D (the prompt condition) needs to be non-n for
194 FOO to be visible (assignable). If its value is m, the symbol can only be
195 assigned the value m: The visibility sets an upper bound on the value that can
196 be assigned by the user, and any higher user value will be truncated down.
198 'default' properties are independent of the visibility, though a 'default' will
199 often get the same condition as the prompt due to dependency propagation.
200 'default' properties are used if the symbol is not visible or has no user
203 Symbols with no user value (or that have a user value but are not visible) and
204 no (active) 'default' default to n for bool/tristate symbols, and to the empty
205 string for other symbol types.
207 'select' works similarly to symbol visibility, but sets a lower bound on the
208 value of the symbol. The lower bound is determined by the value of the
209 select*ing* symbol. 'select' does not respect visibility, so non-visible
210 symbols can be forced to a particular (minimum) value by a select as well.
212 For non-bool/tristate symbols, it only matters whether the visibility is n or
213 non-n: m visibility acts the same as y visibility.
215 Conditions on 'default' and 'select' work in mostly intuitive ways. If the
216 condition is n, the 'default' or 'select' is disabled. If it is m, the
217 'default' or 'select' value (the value of the selecting symbol) is truncated
220 When writing a configuration with Kconfig.write_config(), only symbols that are
221 visible, have an (active) default, or are selected will get written out (note
222 that this includes all symbols that would accept user values). Kconfiglib
223 matches the .config format produced by the C implementations down to the
224 character. This eases testing.
226 For a visible bool/tristate symbol FOO with value n, this line is written to
229 # CONFIG_FOO is not set
231 The point is to remember the user n selection (which might differ from the
232 default value the symbol would get), while at the same sticking to the rule
233 that undefined corresponds to n (.config uses Makefile format, making the line
234 above a comment). When the .config file is read back in, this line will be
235 treated the same as the following assignment:
239 In Kconfiglib, the set of (currently) assignable values for a bool/tristate
240 symbol appear in Symbol.assignable. For other symbol types, just check if
241 sym.visibility is non-0 (non-n) to see whether the user value will have an
245 Intro to the menu tree
246 ======================
248 The menu structure, as seen in e.g. menuconfig, is represented by a tree of
249 MenuNode objects. The top node of the configuration corresponds to an implicit
250 top-level menu, the title of which is shown at the top in the standard
251 menuconfig interface. (The title is also available in Kconfig.mainmenu_text in
254 The top node is found in Kconfig.top_node. From there, you can visit child menu
255 nodes by following the 'list' pointer, and any following menu nodes by
256 following the 'next' pointer. Usually, a non-None 'list' pointer indicates a
257 menu or Choice, but menu nodes for symbols can sometimes have a non-None 'list'
258 pointer too due to submenus created implicitly from dependencies.
260 MenuNode.item is either a Symbol or a Choice object, or one of the constants
261 MENU and COMMENT. The prompt of the menu node can be found in MenuNode.prompt,
262 which also holds the title for menus and comments. For Symbol and Choice,
263 MenuNode.help holds the help text (if any, otherwise None).
265 Most symbols will only have a single menu node. A symbol defined in multiple
266 locations will have one menu node for each location. The list of menu nodes for
267 a Symbol or Choice can be found in the Symbol/Choice.nodes attribute.
269 Note that prompts and help texts for symbols and choices are stored in their
270 menu node(s) rather than in the Symbol or Choice objects themselves. This makes
271 it possible to define a symbol in multiple locations with a different prompt or
272 help text in each location. To get the help text or prompt for a symbol with a
273 single menu node, do sym.nodes[0].help and sym.nodes[0].prompt, respectively.
274 The prompt is a (text, condition) tuple, where condition determines the
275 visibility (see 'Intro to expressions' below).
277 This organization mirrors the C implementation. MenuNode is called
278 'struct menu' there, but I thought "menu" was a confusing name.
280 It is possible to give a Choice a name and define it in multiple locations,
281 hence why Choice.nodes is also a list.
283 As a convenience, the properties added at a particular definition location are
284 available on the MenuNode itself, in e.g. MenuNode.defaults. This is helpful
285 when generating documentation, so that symbols/choices defined in multiple
286 locations can be shown with the correct properties at each location.
292 Expressions can be evaluated with the expr_value() function and printed with
293 the expr_str() function (these are used internally as well). Evaluating an
294 expression always yields a tristate value, where n, m, and y are represented as
295 0, 1, and 2, respectively.
297 The following table should help you figure out how expressions are represented.
298 A, B, C, ... are symbols (Symbol instances), NOT is the kconfiglib.NOT
301 Expression Representation
302 ---------- --------------
304 "A" A (constant symbol)
307 A && B && C (AND, A, (AND, B, C))
309 A || (B && C && D) (OR, A, (AND, B, (AND, C, D)))
311 A != "foo" (UNEQUAL, A, foo (constant symbol))
312 A && B = C && D (AND, A, (AND, (EQUAL, B, C), D))
313 n Kconfig.n (constant symbol)
314 m Kconfig.m (constant symbol)
315 y Kconfig.y (constant symbol)
316 "y" Kconfig.y (constant symbol)
318 Strings like "foo" in 'default "foo"' or 'depends on SYM = "foo"' are
319 represented as constant symbols, so the only values that appear in expressions
320 are symbols***. This mirrors the C implementation.
322 ***For choice symbols, the parent Choice will appear in expressions as well,
323 but it's usually invisible as the value interfaces of Symbol and Choice are
324 identical. This mirrors the C implementation and makes different choice modes
327 Manual evaluation examples:
329 - The value of A && B is min(A.tri_value, B.tri_value)
331 - The value of A || B is max(A.tri_value, B.tri_value)
333 - The value of !A is 2 - A.tri_value
335 - The value of A = B is 2 (y) if A.str_value == B.str_value, and 0 (n)
336 otherwise. Note that str_value is used here instead of tri_value.
338 For constant (as well as undefined) symbols, str_value matches the name of
339 the symbol. This mirrors the C implementation and explains why
340 'depends on SYM = "foo"' above works as expected.
342 n/m/y are automatically converted to the corresponding constant symbols
343 "n"/"m"/"y" (Kconfig.n/m/y) during parsing.
345 Kconfig.const_syms is a dictionary like Kconfig.syms but for constant symbols.
347 If a condition is missing (e.g., <cond> when the 'if <cond>' is removed from
348 'default A if <cond>'), it is actually Kconfig.y. The standard __str__()
349 functions just avoid printing 'if y' conditions to give cleaner output.
355 Kconfiglib includes a couple of Kconfig extensions:
357 'source' with relative path
358 ---------------------------
360 The 'rsource' statement sources Kconfig files with a path relative to directory
361 of the Kconfig file containing the 'rsource' statement, instead of relative to
364 Consider following directory tree:
378 In this example, assume that src/SubSystem1/Kconfig wants to source
379 src/SubSystem1/ModuleA/Kconfig.
381 With 'source', this statement would be used:
383 source "src/SubSystem1/ModuleA/Kconfig"
385 With 'rsource', this turns into
387 rsource "ModuleA/Kconfig"
389 If an absolute path is given to 'rsource', it acts the same as 'source'.
391 'rsource' can be used to create "position-independent" Kconfig trees that can
392 be moved around freely.
398 'source' and 'rsource' accept glob patterns, sourcing all matching Kconfig
399 files. They require at least one matching file, raising a KconfigError
402 For example, the following statement might source sub1/foofoofoo and
405 source "sub[12]/foo*foo"
407 The glob patterns accepted are the same as for the standard glob.glob()
410 Two additional statements are provided for cases where it's acceptable for a
411 pattern to match no files: 'osource' and 'orsource' (the o is for "optional").
413 For example, the following statements will be no-ops if neither "foo" nor any
414 files matching "bar*" exist:
419 'orsource' does a relative optional source.
421 'source' and 'osource' are analogous to 'include' and '-include' in Make.
424 Generalized def_* keywords
425 --------------------------
427 def_int, def_hex, and def_string are available in addition to def_bool and
428 def_tristate, allowing int, hex, and string symbols to be given a type and a
429 default at the same time.
432 Extra optional warnings
433 -----------------------
435 Some optional warnings can be controlled via environment variables:
437 - KCONFIG_WARN_UNDEF: If set to 'y', warnings will be generated for all
438 references to undefined symbols within Kconfig files. The only gotcha is
439 that all hex literals must be prefixed with "0x" or "0X", to make it
440 possible to distinguish them from symbol references.
442 Some projects (e.g. the Linux kernel) use multiple Kconfig trees with many
443 shared Kconfig files, leading to some safe undefined symbol references.
444 KCONFIG_WARN_UNDEF is useful in projects that only have a single Kconfig
447 KCONFIG_STRICT is an older alias for this environment variable, supported
448 for backwards compatibility.
450 - KCONFIG_WARN_UNDEF_ASSIGN: If set to 'y', warnings will be generated for
451 all assignments to undefined symbols within .config files. By default, no
452 such warnings are generated.
454 This warning can also be enabled/disabled via the Kconfig.warn_assign_undef
458 Preprocessor user functions defined in Python
459 ---------------------------------------------
461 Preprocessor functions can be defined in Python, which makes it simple to
462 integrate information from existing Python tools into Kconfig (e.g. to have
463 Kconfig symbols depend on hardware information stored in some other format).
465 Putting a Python module named kconfigfunctions(.py) anywhere in sys.path will
466 cause it to be imported by Kconfiglib (in Kconfig.__init__()). Note that
467 sys.path can be customized via PYTHONPATH, and includes the directory of the
468 module being run by default, as well as installation directories.
470 If the KCONFIG_FUNCTIONS environment variable is set, it gives a different
471 module name to use instead of 'kconfigfunctions'.
473 The imported module is expected to define a global dictionary named 'functions'
474 that maps function names to Python functions, as follows:
476 def my_fn(kconf, name, arg_1, arg_2, ...):
481 # Name of the user-defined function ("my-fn"). Think argv[0].
484 # Arguments passed to the function from Kconfig (strings)
486 # Returns a string to be substituted as the result of calling the
490 def my_other_fn(kconf, name, arg_1, arg_2, ...):
494 "my-fn": (my_fn, <min.args>, <max.args>/None),
495 "my-other-fn": (my_other_fn, <min.args>, <max.args>/None),
501 <min.args> and <max.args> are the minimum and maximum number of arguments
502 expected by the function (excluding the implicit 'name' argument). If
503 <max.args> is None, there is no upper limit to the number of arguments. Passing
504 an invalid number of arguments will generate a KconfigError exception.
506 Functions can access the current parsing location as kconf.filename/linenr.
507 Accessing other fields of the Kconfig object is not safe. See the warning
510 Keep in mind that for a variable defined like 'foo = $(fn)', 'fn' will be
511 called only when 'foo' is expanded. If 'fn' uses the parsing location and the
512 intent is to use the location of the assignment, you want 'foo := $(fn)'
513 instead, which calls the function immediately.
515 Once defined, user functions can be called from Kconfig in the same way as
516 other preprocessor functions:
520 depends on $(my-fn,arg1,arg2)
522 If my_fn() returns "n", this will result in
531 User-defined preprocessor functions are called as they're encountered at parse
532 time, before all Kconfig files have been processed, and before the menu tree
533 has been finalized. There are no guarantees that accessing Kconfig symbols or
534 the menu tree via the 'kconf' parameter will work, and it could potentially
537 Preferably, user-defined functions should be stateless.
543 Send bug reports, suggestions, and questions to ulfalizer a.t Google's email
544 service, or open a ticket on the GitHub page.
552 # Get rid of some attribute lookups. These are obvious in context.
553 from glob import iglob
554 from os.path import dirname, exists, expandvars, islink, join, realpath
567 # Line length: 79 columns
575 class Kconfig(object):
577 Represents a Kconfig configuration, e.g. for x86 or ARM. This is the set of
578 symbols, choices, and menu nodes appearing in the configuration. Creating
579 any number of Kconfig objects (including for different architectures) is
580 safe. Kconfiglib doesn't keep any global state.
582 The following attributes are available. They should be treated as
583 read-only, and some are implemented through @property magic.
586 A dictionary with all symbols in the configuration, indexed by name. Also
587 includes all symbols that are referenced in expressions but never
588 defined, except for constant (quoted) symbols.
590 Undefined symbols can be recognized by Symbol.nodes being empty -- see
591 the 'Intro to the menu tree' section in the module docstring.
594 A dictionary like 'syms' for constant (quoted) symbols
597 A dictionary like 'syms' for named choices (choice FOO)
600 A list with all defined symbols, in the same order as they appear in the
601 Kconfig files. Symbols defined in multiple locations appear multiple
604 Note: You probably want to use 'unique_defined_syms' instead. This
605 attribute is mostly maintained for backwards compatibility.
608 A list like 'defined_syms', but with duplicates removed. Just the first
609 instance is kept for symbols defined in multiple locations. Kconfig order
610 is preserved otherwise.
612 Using this attribute instead of 'defined_syms' can save work, and
613 automatically gives reasonable behavior when writing configuration output
614 (symbols defined in multiple locations only generate output once, while
615 still preserving Kconfig order for readability).
618 A list with all choices, in the same order as they appear in the Kconfig
621 Note: You probably want to use 'unique_choices' instead. This attribute
622 is mostly maintained for backwards compatibility.
625 Analogous to 'unique_defined_syms', for choices. Named choices can have
626 multiple definition locations.
629 A list with all menus, in the same order as they appear in the Kconfig
633 A list with all comments, in the same order as they appear in the Kconfig
637 A list with the filenames of all Kconfig files included in the
638 configuration, relative to $srctree (or relative to the current directory
639 if $srctree isn't set), except absolute paths (e.g.
640 'source "/foo/Kconfig"') are kept as-is.
642 The files are listed in the order they are source'd, starting with the
643 top-level Kconfig file. If a file is source'd multiple times, it will
644 appear multiple times. Use set() to get unique filenames.
646 Note that Kconfig.sync_deps() already indirectly catches any file
647 modifications that change configuration output.
650 A set() with the names of all environment variables referenced in the
653 Only environment variables referenced with the preprocessor $(FOO) syntax
654 will be registered. The older $FOO syntax is only supported for backwards
657 Also note that $(FOO) won't be registered unless the environment variable
658 $FOO is actually set. If it isn't, $(FOO) is an expansion of an unset
659 preprocessor variable (which gives the empty string).
661 Another gotcha is that environment variables referenced in the values of
662 recursively expanded preprocessor variables (those defined with =) will
663 only be registered if the variable is actually used (expanded) somewhere.
665 The note from the 'kconfig_filenames' documentation applies here too.
668 The predefined constant symbols n/m/y. Also available in const_syms.
671 The Symbol instance for the modules symbol. Currently hardcoded to
672 MODULES, which is backwards compatible. Kconfiglib will warn if
673 'option modules' is set on some other symbol. Tell me if you need proper
674 'option modules' support.
676 'modules' is never None. If the MODULES symbol is not explicitly defined,
677 its tri_value will be 0 (n), as expected.
679 A simple way to enable modules is to do 'kconf.modules.set_value(2)'
680 (provided the MODULES symbol is defined and visible). Modules are
681 disabled by default in the kernel Kconfig files as of writing, though
682 nearly all defconfig files enable them (with 'CONFIG_MODULES=y').
685 The Symbol instance for the 'option defconfig_list' symbol, or None if no
686 defconfig_list symbol exists. The defconfig filename derived from this
687 symbol can be found in Kconfig.defconfig_filename.
690 The filename given by the defconfig_list symbol. This is taken from the
691 first 'default' with a satisfied condition where the specified file
692 exists (can be opened for reading). If a defconfig file foo/defconfig is
693 not found and $srctree was set when the Kconfig was created,
694 $srctree/foo/defconfig is looked up as well.
696 'defconfig_filename' is None if either no defconfig_list symbol exists,
697 or if the defconfig_list symbol has no 'default' with a satisfied
698 condition that specifies a file that exists.
700 Gotcha: scripts/kconfig/Makefile might pass --defconfig=<defconfig> to
701 scripts/kconfig/conf when running e.g. 'make defconfig'. This option
702 overrides the defconfig_list symbol, meaning defconfig_filename might not
703 always match what 'make defconfig' would use.
706 The menu node (see the MenuNode class) of the implicit top-level menu.
707 Acts as the root of the menu tree.
710 The prompt (title) of the top menu (top_node). Defaults to "Main menu".
711 Can be changed with the 'mainmenu' statement (see kconfig-language.txt).
714 A dictionary with all preprocessor variables, indexed by name. See the
718 Set this variable to True/False to enable/disable warnings. See
721 When 'warn' is False, the values of the other warning-related variables
724 This variable as well as the other warn* variables can be read to check
725 the current warning settings.
728 Set this variable to True/False to enable/disable warnings on stderr. See
732 Set this variable to True to generate warnings for assignments to
733 undefined symbols in configuration files.
735 This variable is False by default unless the KCONFIG_WARN_UNDEF_ASSIGN
736 environment variable was set to 'y' when the Kconfig instance was
739 warn_assign_override:
740 Set this variable to True to generate warnings for multiple assignments
741 to the same symbol in configuration files, where the assignments set
742 different values (e.g. CONFIG_FOO=m followed by CONFIG_FOO=y, where the
743 last value would get used).
745 This variable is True by default. Disabling it might be useful when
746 merging configurations.
749 Like warn_assign_override, but for multiple assignments setting a symbol
752 This variable is True by default. Disabling it might be useful when
753 merging configurations.
756 A list of strings containing all warnings that have been generated, for
757 cases where more flexibility is needed.
759 See the 'warn_to_stderr' parameter to Kconfig.__init__() and the
760 Kconfig.warn_to_stderr variable as well. Note that warnings still get
761 added to Kconfig.warnings when 'warn_to_stderr' is True.
763 Just as for warnings printed to stderr, only warnings that are enabled
764 will get added to Kconfig.warnings. See the various Kconfig.warn*
768 A list with (name, value) tuples for all assignments to undefined symbols
769 within the most recently loaded .config file(s). 'name' is the symbol
770 name without the 'CONFIG_' prefix. 'value' is a string that gives the
771 right-hand side of the assignment verbatim.
773 See Kconfig.load_config() as well.
776 The value the $srctree environment variable had when the Kconfig instance
777 was created, or the empty string if $srctree wasn't set. This gives nice
778 behavior with os.path.join(), which treats "" as the current directory,
781 Kconfig files are looked up relative to $srctree (unless absolute paths
782 are used), and .config files are looked up relative to $srctree if they
783 are not found in the current directory. This is used to support
784 out-of-tree builds. The C tools use this environment variable in the same
787 Changing $srctree after creating the Kconfig instance has no effect. Only
788 the value when the configuration is loaded matters. This avoids surprises
789 if multiple configurations are loaded with different values for $srctree.
792 The value the CONFIG_ environment variable had when the Kconfig instance
793 was created, or "CONFIG_" if CONFIG_ wasn't set. This is the prefix used
794 (and expected) on symbol names in .config files and C headers. Used in
795 the same way in the C tools.
798 The value the KCONFIG_CONFIG_HEADER environment variable had when the
799 Kconfig instance was created, or the empty string if
800 KCONFIG_CONFIG_HEADER wasn't set. This string is inserted verbatim at the
801 beginning of configuration files. See write_config().
804 The value the KCONFIG_AUTOHEADER_HEADER environment variable had when the
805 Kconfig instance was created, or the empty string if
806 KCONFIG_AUTOHEADER_HEADER wasn't set. This string is inserted verbatim at
807 the beginning of header files. See write_autoconf().
810 The current parsing location, for use in Python preprocessor functions.
811 See the module docstring.
819 "_warn_assign_no_prompt",
840 "unique_defined_syms",
843 "warn_assign_override",
867 def __init__(self, filename="Kconfig", warn=True, warn_to_stderr=True,
868 encoding="utf-8", suppress_traceback=False):
870 Creates a new Kconfig object by parsing Kconfig files.
871 Note that Kconfig files are not the same as .config files (which store
872 configuration symbol values).
874 See the module docstring for some environment variables that influence
875 default warning settings (KCONFIG_WARN_UNDEF and
876 KCONFIG_WARN_UNDEF_ASSIGN).
878 Raises KconfigError on syntax/semantic errors, and OSError or (possibly
879 a subclass of) IOError on IO errors ('errno', 'strerror', and
880 'filename' are available). Note that IOError is an alias for OSError on
881 Python 3, so it's enough to catch OSError there. If you need Python 2/3
882 compatibility, it's easiest to catch EnvironmentError, which is a
883 common base class of OSError/IOError on Python 2 and an alias for
886 filename (default: "Kconfig"):
887 The Kconfig file to load. For the Linux kernel, you'll want "Kconfig"
888 from the top-level directory, as environment variables will make sure
889 the right Kconfig is included from there (arch/$SRCARCH/Kconfig as of
892 If $srctree is set, 'filename' will be looked up relative to it.
893 $srctree is also used to look up source'd files within Kconfig files.
894 See the class documentation.
896 If you are using Kconfiglib via 'make scriptconfig', the filename of
897 the base base Kconfig file will be in sys.argv[1]. It's currently
898 always "Kconfig" in practice.
900 warn (default: True):
901 True if warnings related to this configuration should be generated.
902 This can be changed later by setting Kconfig.warn to True/False. It
903 is provided as a constructor argument since warnings might be
904 generated during parsing.
906 See the other Kconfig.warn_* variables as well, which enable or
907 suppress certain warnings when warnings are enabled.
909 All generated warnings are added to the Kconfig.warnings list. See
910 the class documentation.
912 warn_to_stderr (default: True):
913 True if warnings should be printed to stderr in addition to being
914 added to Kconfig.warnings.
916 This can be changed later by setting Kconfig.warn_to_stderr to
919 encoding (default: "utf-8"):
920 The encoding to use when reading and writing files, and when decoding
921 output from commands run via $(shell). If None, the encoding
922 specified in the current locale will be used.
924 The "utf-8" default avoids exceptions on systems that are configured
925 to use the C locale, which implies an ASCII encoding.
927 This parameter has no effect on Python 2, due to implementation
928 issues (regular strings turning into Unicode strings, which are
929 distinct in Python 2). Python 2 doesn't decode regular strings
932 Related PEP: https://www.python.org/dev/peps/pep-0538/
934 suppress_traceback (default: False):
935 Helper for tools. When True, any EnvironmentError or KconfigError
936 generated during parsing is caught, the exception message is printed
937 to stderr together with the command name, and sys.exit(1) is called
938 (which generates SystemExit).
940 This hides the Python traceback for "expected" errors like syntax
941 errors in Kconfig files.
943 Other exceptions besides EnvironmentError and KconfigError are still
944 propagated when suppress_traceback is True.
947 self._init(filename, warn, warn_to_stderr, encoding)
948 except (EnvironmentError, KconfigError) as e:
949 if suppress_traceback:
950 cmd = sys.argv[0] # Empty string if missing
953 # Some long exception messages have extra newlines for better
954 # formatting when reported as an unhandled exception. Strip
956 sys.exit(cmd + str(e).strip())
959 def _init(self, filename, warn, warn_to_stderr, encoding):
962 self._encoding = encoding
964 self.srctree = os.getenv("srctree", "")
965 # A prefix we can reliably strip from glob() results to get a filename
966 # relative to $srctree. relpath() can cause issues for symlinks,
967 # because it assumes symlink/../foo is the same as foo/.
968 self._srctree_prefix = realpath(self.srctree) + os.sep
971 self.warn_to_stderr = warn_to_stderr
972 self.warn_assign_undef = os.getenv("KCONFIG_WARN_UNDEF_ASSIGN") == "y"
973 self.warn_assign_override = True
974 self.warn_assign_redun = True
975 self._warn_assign_no_prompt = True
979 self.config_prefix = os.getenv("CONFIG_", "CONFIG_")
980 # Regular expressions for parsing .config files
981 self._set_match = _re_match(self.config_prefix + r"([^=]+)=(.*)")
982 self._unset_match = _re_match(r"# {}([^ ]+) is not set".format(
985 self.config_header = os.getenv("KCONFIG_CONFIG_HEADER", "")
986 self.header_header = os.getenv("KCONFIG_AUTOHEADER_HEADER", "")
990 self.defined_syms = []
991 self.missing_syms = []
992 self.named_choices = {}
997 for nmy in "n", "m", "y":
1001 sym.is_constant = True
1002 sym.orig_type = TRISTATE
1003 sym._cached_tri_val = STR_TO_TRI[nmy]
1005 self.const_syms[nmy] = sym
1007 self.n = self.const_syms["n"]
1008 self.m = self.const_syms["m"]
1009 self.y = self.const_syms["y"]
1011 # Make n/m/y well-formed symbols
1012 for nmy in "n", "m", "y":
1013 sym = self.const_syms[nmy]
1014 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
1016 # Maps preprocessor variables names to Variable instances
1019 # Predefined preprocessor functions, with min/max number of arguments
1021 "info": (_info_fn, 1, 1),
1022 "error-if": (_error_if_fn, 2, 2),
1023 "filename": (_filename_fn, 0, 0),
1024 "lineno": (_lineno_fn, 0, 0),
1025 "shell": (_shell_fn, 1, 1),
1026 "warning-if": (_warning_if_fn, 2, 2),
1029 # Add any user-defined preprocessor functions
1031 self._functions.update(
1032 importlib.import_module(
1033 os.getenv("KCONFIG_FUNCTIONS", "kconfigfunctions")
1038 # This determines whether previously unseen symbols are registered.
1039 # They shouldn't be if we parse expressions after parsing, as part of
1040 # Kconfig.eval_string().
1041 self._parsing_kconfigs = True
1043 self.modules = self._lookup_sym("MODULES")
1044 self.defconfig_list = None
1046 self.top_node = MenuNode()
1047 self.top_node.kconfig = self
1048 self.top_node.item = MENU
1049 self.top_node.is_menuconfig = True
1050 self.top_node.visibility = self.y
1051 self.top_node.prompt = ("Main menu", self.y)
1052 self.top_node.parent = None
1053 self.top_node.dep = self.y
1054 self.top_node.filename = filename
1055 self.top_node.linenr = 1
1056 self.top_node.include_path = ()
1058 # Parse the Kconfig files
1060 # Not used internally. Provided as a convenience.
1061 self.kconfig_filenames = [filename]
1062 self.env_vars = set()
1064 # Keeps track of the location in the parent Kconfig files. Kconfig
1065 # files usually source other Kconfig files. See _enter_file().
1066 self._filestack = []
1067 self._include_path = ()
1069 # The current parsing location
1070 self.filename = filename
1073 # Used to avoid retokenizing lines when we discover that they're not
1074 # part of the construct currently being parsed. This is kinda like an
1076 self._reuse_tokens = False
1078 # Open the top-level Kconfig file. Store the readline() method directly
1079 # as a small optimization.
1080 self._readline = self._open(join(self.srctree, filename), "r").readline
1083 # Parse the Kconfig files. Returns the last node, which we
1084 # terminate with '.next = None'.
1085 self._parse_block(None, self.top_node, self.top_node).next = None
1086 self.top_node.list = self.top_node.next
1087 self.top_node.next = None
1088 except UnicodeDecodeError as e:
1089 _decoding_error(e, self.filename)
1091 # Close the top-level Kconfig file. __self__ fetches the 'file' object
1093 self._readline.__self__.close()
1095 self._parsing_kconfigs = False
1097 # Do various menu tree post-processing
1098 self._finalize_node(self.top_node, self.y)
1100 self.unique_defined_syms = _ordered_unique(self.defined_syms)
1101 self.unique_choices = _ordered_unique(self.choices)
1103 # Do sanity checks. Some of these depend on everything being finalized.
1104 self._check_sym_sanity()
1105 self._check_choice_sanity()
1107 # KCONFIG_STRICT is an older alias for KCONFIG_WARN_UNDEF, supported
1108 # for backwards compatibility
1109 if os.getenv("KCONFIG_WARN_UNDEF") == "y" or \
1110 os.getenv("KCONFIG_STRICT") == "y":
1112 self._check_undef_syms()
1114 # Build Symbol._dependents for all symbols and choices
1117 # Check for dependency loops
1118 check_dep_loop_sym = _check_dep_loop_sym # Micro-optimization
1119 for sym in self.unique_defined_syms:
1120 check_dep_loop_sym(sym, False)
1122 # Add extra dependencies from choices to choice symbols that get
1123 # awkward during dependency loop detection
1124 self._add_choice_deps()
1127 def mainmenu_text(self):
1129 See the class documentation.
1131 return self.top_node.prompt[0]
1134 def defconfig_filename(self):
1136 See the class documentation.
1138 if self.defconfig_list:
1139 for filename, cond in self.defconfig_list.defaults:
1140 if expr_value(cond):
1142 with self._open_config(filename.str_value) as f:
1144 except EnvironmentError:
1149 def load_config(self, filename=None, replace=True, verbose=None):
1151 Loads symbol values from a file in the .config format. Equivalent to
1152 calling Symbol.set_value() to set each of the values.
1154 "# CONFIG_FOO is not set" within a .config file sets the user value of
1155 FOO to n. The C tools work the same way.
1157 For each symbol, the Symbol.user_value attribute holds the value the
1158 symbol was assigned in the .config file (if any). The user value might
1159 differ from Symbol.str/tri_value if there are unsatisfied dependencies.
1161 Calling this function also updates the Kconfig.missing_syms attribute
1162 with a list of all assignments to undefined symbols within the
1163 configuration file. Kconfig.missing_syms is cleared if 'replace' is
1164 True, and appended to otherwise. See the documentation for
1165 Kconfig.missing_syms as well.
1167 See the Kconfig.__init__() docstring for raised exceptions
1168 (OSError/IOError). KconfigError is never raised here.
1170 filename (default: None):
1171 Path to load configuration from (a string). Respects $srctree if set
1172 (see the class documentation).
1174 If 'filename' is None (the default), the configuration file to load
1175 (if any) is calculated automatically, giving the behavior you'd
1178 1. If the KCONFIG_CONFIG environment variable is set, it gives the
1179 path to the configuration file to load. Otherwise, ".config" is
1180 used. See standard_config_filename().
1182 2. If the path from (1.) doesn't exist, the configuration file
1183 given by kconf.defconfig_filename is loaded instead, which is
1184 derived from the 'option defconfig_list' symbol.
1186 3. If (1.) and (2.) fail to find a configuration file to load, no
1187 configuration file is loaded, and symbols retain their current
1188 values (e.g., their default values). This is not an error.
1190 See the return value as well.
1192 replace (default: True):
1193 If True, all existing user values will be cleared before loading the
1194 .config. Pass False to merge configurations.
1196 verbose (default: None):
1197 Limited backwards compatibility to prevent crashes. A warning is
1198 printed if anything but None is passed.
1200 Prior to Kconfiglib 12.0.0, this option enabled printing of messages
1201 to stdout when 'filename' was None. A message is (always) returned
1202 now instead, which is more flexible.
1204 Will probably be removed in some future version.
1206 Returns a string with a message saying which file got loaded (or
1207 possibly that no file got loaded, when 'filename' is None). This is
1208 meant to reduce boilerplate in tools, which can do e.g.
1209 print(kconf.load_config()). The returned message distinguishes between
1210 loading (replace == True) and merging (replace == False).
1212 if verbose is not None:
1213 _warn_verbose_deprecated("load_config")
1216 if filename is None:
1217 filename = standard_config_filename()
1218 if not exists(filename) and \
1219 not exists(join(self.srctree, filename)):
1220 defconfig = self.defconfig_filename
1221 if defconfig is None:
1222 return "Using default symbol values (no '{}')" \
1225 msg = " default configuration '{}' (no '{}')" \
1226 .format(defconfig, filename)
1227 filename = defconfig
1230 msg = " configuration '{}'".format(filename)
1232 # Disable the warning about assigning to symbols without prompts. This
1233 # is normal and expected within a .config file.
1234 self._warn_assign_no_prompt = False
1236 # This stub only exists to make sure _warn_assign_no_prompt gets
1239 self._load_config(filename, replace)
1240 except UnicodeDecodeError as e:
1241 _decoding_error(e, filename)
1243 self._warn_assign_no_prompt = True
1245 return ("Loaded" if replace else "Merged") + msg
1247 def _load_config(self, filename, replace):
1248 with self._open_config(filename) as f:
1250 self.missing_syms = []
1252 # If we're replacing the configuration, keep track of which
1253 # symbols and choices got set so that we can unset the rest
1254 # later. This avoids invalidating everything and is faster.
1255 # Another benefit is that invalidation must be rock solid for
1256 # it to work, making it a good test.
1258 for sym in self.unique_defined_syms:
1259 sym._was_set = False
1261 for choice in self.unique_choices:
1262 choice._was_set = False
1264 # Small optimizations
1265 set_match = self._set_match
1266 unset_match = self._unset_match
1267 get_sym = self.syms.get
1269 for linenr, line in enumerate(f, 1):
1270 # The C tools ignore trailing whitespace
1271 line = line.rstrip()
1273 match = set_match(line)
1275 name, val = match.groups()
1277 if not sym or not sym.nodes:
1278 self._undef_assign(name, val, filename, linenr)
1281 if sym.orig_type in _BOOL_TRISTATE:
1282 # The C implementation only checks the first character
1283 # to the right of '=', for whatever reason
1284 if not (sym.orig_type is BOOL
1285 and val.startswith(("y", "n")) or
1286 sym.orig_type is TRISTATE
1287 and val.startswith(("y", "m", "n"))):
1288 self._warn("'{}' is not a valid value for the {} "
1289 "symbol {}. Assignment ignored."
1290 .format(val, TYPE_TO_STR[sym.orig_type],
1297 if sym.choice and val != "n":
1298 # During .config loading, we infer the mode of the
1299 # choice from the kind of values that are assigned
1300 # to the choice symbols
1302 prev_mode = sym.choice.user_value
1303 if prev_mode is not None and \
1304 TRI_TO_STR[prev_mode] != val:
1306 self._warn("both m and y assigned to symbols "
1307 "within the same choice",
1310 # Set the choice's mode
1311 sym.choice.set_value(val)
1313 elif sym.orig_type is STRING:
1314 match = _conf_string_match(val)
1316 self._warn("malformed string literal in "
1317 "assignment to {}. Assignment ignored."
1318 .format(sym.name_and_loc),
1322 val = unescape(match.group(1))
1325 match = unset_match(line)
1327 # Print a warning for lines that match neither
1328 # set_match() nor unset_match() and that are not blank
1329 # lines or comments. 'line' has already been
1330 # rstrip()'d, so blank lines show up as "" here.
1331 if line and not line.lstrip().startswith("#"):
1332 self._warn("ignoring malformed line '{}'"
1338 name = match.group(1)
1340 if not sym or not sym.nodes:
1341 self._undef_assign(name, "n", filename, linenr)
1344 if sym.orig_type not in _BOOL_TRISTATE:
1349 # Done parsing the assignment. Set the value.
1352 self._assigned_twice(sym, val, filename, linenr)
1357 # If we're replacing the configuration, unset the symbols that
1360 for sym in self.unique_defined_syms:
1361 if not sym._was_set:
1364 for choice in self.unique_choices:
1365 if not choice._was_set:
1366 choice.unset_value()
1368 def _undef_assign(self, name, val, filename, linenr):
1369 # Called for assignments to undefined symbols during .config loading
1371 self.missing_syms.append((name, val))
1372 if self.warn_assign_undef:
1374 "attempt to assign the value '{}' to the undefined symbol {}"
1375 .format(val, name), filename, linenr)
1377 def _assigned_twice(self, sym, new_val, filename, linenr):
1378 # Called when a symbol is assigned more than once in a .config file
1380 # Use strings for bool/tristate user values in the warning
1381 if sym.orig_type in _BOOL_TRISTATE:
1382 user_val = TRI_TO_STR[sym.user_value]
1384 user_val = sym.user_value
1386 msg = '{} set more than once. Old value "{}", new value "{}".'.format(
1387 sym.name_and_loc, user_val, new_val)
1389 if user_val == new_val:
1390 if self.warn_assign_redun:
1391 self._warn(msg, filename, linenr)
1392 elif self.warn_assign_override:
1393 self._warn(msg, filename, linenr)
1395 def load_allconfig(self, filename):
1397 Helper for all*config. Loads (merges) the configuration file specified
1398 by KCONFIG_ALLCONFIG, if any. See Documentation/kbuild/kconfig.txt in
1401 Disables warnings for duplicated assignments within configuration files
1402 for the duration of the call
1403 (kconf.warn_assign_override/warn_assign_redun = False), and restores
1404 the previous warning settings at the end. The KCONFIG_ALLCONFIG
1405 configuration file is expected to override symbols.
1407 Exits with sys.exit() (which raises a SystemExit exception) and prints
1408 an error to stderr if KCONFIG_ALLCONFIG is set but the configuration
1409 file can't be opened.
1412 Command-specific configuration filename - "allyes.config",
1413 "allno.config", etc.
1415 load_allconfig(self, filename)
1417 def write_autoconf(self, filename=None, header=None):
1419 Writes out symbol values as a C header file, matching the format used
1420 by include/generated/autoconf.h in the kernel.
1422 The ordering of the #defines matches the one generated by
1423 write_config(). The order in the C implementation depends on the hash
1424 table implementation as of writing, and so won't match.
1426 If 'filename' exists and its contents is identical to what would get
1427 written out, it is left untouched. This avoids updating file metadata
1428 like the modification time and possibly triggering redundant work in
1431 filename (default: None):
1432 Path to write header to.
1434 If None (the default), the path in the environment variable
1435 KCONFIG_AUTOHEADER is used if set, and "include/generated/autoconf.h"
1436 otherwise. This is compatible with the C tools.
1438 header (default: None):
1439 Text inserted verbatim at the beginning of the file. You would
1440 usually want it enclosed in '/* */' to make it a C comment, and
1441 include a trailing newline.
1443 If None (the default), the value of the environment variable
1444 KCONFIG_AUTOHEADER_HEADER had when the Kconfig instance was created
1445 will be used if it was set, and no header otherwise. See the
1446 Kconfig.header_header attribute.
1448 Returns a string with a message saying that the header got saved, or
1449 that there were no changes to it. This is meant to reduce boilerplate
1450 in tools, which can do e.g. print(kconf.write_autoconf()).
1452 if filename is None:
1453 filename = os.getenv("KCONFIG_AUTOHEADER",
1454 "include/generated/autoconf.h")
1456 if self._write_if_changed(filename, self._autoconf_contents(header)):
1457 return "Kconfig header saved to '{}'".format(filename)
1458 return "No change to Kconfig header in '{}'".format(filename)
1460 def _autoconf_contents(self, header):
1461 # write_autoconf() helper. Returns the contents to write as a string,
1462 # with 'header' or KCONFIG_AUTOHEADER_HEADER at the beginning.
1465 header = self.header_header
1467 chunks = [header] # "".join()ed later
1470 for sym in self.unique_defined_syms:
1471 # _write_to_conf is determined when the value is calculated. This
1472 # is a hidden function call due to property magic.
1474 # Note: In client code, you can check if sym.config_string is empty
1475 # instead, to avoid accessing the internal _write_to_conf variable
1476 # (though it's likely to keep working).
1478 if not sym._write_to_conf:
1481 if sym.orig_type in _BOOL_TRISTATE:
1483 add("#define {}{} 1\n"
1484 .format(self.config_prefix, sym.name))
1486 add("#define {}{}_MODULE 1\n"
1487 .format(self.config_prefix, sym.name))
1489 elif sym.orig_type is STRING:
1490 add('#define {}{} "{}"\n'
1491 .format(self.config_prefix, sym.name, escape(val)))
1493 else: # sym.orig_type in _INT_HEX:
1494 if sym.orig_type is HEX and \
1495 not val.startswith(("0x", "0X")):
1498 add("#define {}{} {}\n"
1499 .format(self.config_prefix, sym.name, val))
1501 return "".join(chunks)
1503 def write_config(self, filename=None, header=None, save_old=True,
1506 Writes out symbol values in the .config format. The format matches the
1507 C implementation, including ordering.
1509 Symbols appear in the same order in generated .config files as they do
1510 in the Kconfig files. For symbols defined in multiple locations, a
1511 single assignment is written out corresponding to the first location
1512 where the symbol is defined.
1514 See the 'Intro to symbol values' section in the module docstring to
1515 understand which symbols get written out.
1517 If 'filename' exists and its contents is identical to what would get
1518 written out, it is left untouched. This avoids updating file metadata
1519 like the modification time and possibly triggering redundant work in
1522 See the Kconfig.__init__() docstring for raised exceptions
1523 (OSError/IOError). KconfigError is never raised here.
1525 filename (default: None):
1526 Path to write configuration to (a string).
1528 If None (the default), the path in the environment variable
1529 KCONFIG_CONFIG is used if set, and ".config" otherwise. See
1530 standard_config_filename().
1532 header (default: None):
1533 Text inserted verbatim at the beginning of the file. You would
1534 usually want each line to start with '#' to make it a comment, and
1535 include a trailing newline.
1537 if None (the default), the value of the environment variable
1538 KCONFIG_CONFIG_HEADER had when the Kconfig instance was created will
1539 be used if it was set, and no header otherwise. See the
1540 Kconfig.config_header attribute.
1542 save_old (default: True):
1543 If True and <filename> already exists, a copy of it will be saved to
1544 <filename>.old in the same directory before the new configuration is
1547 Errors are silently ignored if <filename>.old cannot be written (e.g.
1548 due to being a directory, or <filename> being something like
1551 verbose (default: None):
1552 Limited backwards compatibility to prevent crashes. A warning is
1553 printed if anything but None is passed.
1555 Prior to Kconfiglib 12.0.0, this option enabled printing of messages
1556 to stdout when 'filename' was None. A message is (always) returned
1557 now instead, which is more flexible.
1559 Will probably be removed in some future version.
1561 Returns a string with a message saying which file got saved. This is
1562 meant to reduce boilerplate in tools, which can do e.g.
1563 print(kconf.write_config()).
1565 if verbose is not None:
1566 _warn_verbose_deprecated("write_config")
1568 if filename is None:
1569 filename = standard_config_filename()
1571 contents = self._config_contents(header)
1572 if self._contents_eq(filename, contents):
1573 return "No change to configuration in '{}'".format(filename)
1578 with self._open(filename, "w") as f:
1581 return "Configuration saved to '{}'".format(filename)
1583 def _config_contents(self, header):
1584 # write_config() helper. Returns the contents to write as a string,
1585 # with 'header' or KCONFIG_CONFIG_HEADER at the beginning.
1587 # More memory friendly would be to 'yield' the strings and
1588 # "".join(_config_contents()), but it was a bit slower on my system.
1590 # node_iter() was used here before commit 3aea9f7 ("Add '# end of
1591 # <menu>' after menus in .config"). Those comments get tricky to
1592 # implement with it.
1594 for sym in self.unique_defined_syms:
1595 sym._visited = False
1598 header = self.config_header
1600 chunks = [header] # "".join()ed later
1603 # Did we just print an '# end of ...' comment?
1604 after_end_comment = False
1606 node = self.top_node
1608 # Jump to the next node with an iterative tree walk
1617 # Add a comment when leaving visible menus
1618 if node.item is MENU and expr_value(node.dep) and \
1619 expr_value(node.visibility) and \
1620 node is not self.top_node:
1621 add("# end of {}\n".format(node.prompt[0]))
1622 after_end_comment = True
1629 return "".join(chunks)
1631 # Generate configuration output for the node
1635 if item.__class__ is Symbol:
1638 item._visited = True
1640 conf_string = item.config_string
1644 if after_end_comment:
1645 # Add a blank line before the first symbol printed after an
1646 # '# end of ...' comment
1647 after_end_comment = False
1651 elif expr_value(node.dep) and \
1652 ((item is MENU and expr_value(node.visibility)) or
1655 add("\n#\n# {}\n#\n".format(node.prompt[0]))
1656 after_end_comment = False
1658 def write_min_config(self, filename, header=None):
1660 Writes out a "minimal" configuration file, omitting symbols whose value
1661 matches their default value. The format matches the one produced by
1662 'make savedefconfig'.
1664 The resulting configuration file is incomplete, but a complete
1665 configuration can be derived from it by loading it. Minimal
1666 configuration files can serve as a more manageable configuration format
1667 compared to a "full" .config file, especially when configurations files
1668 are merged or edited by hand.
1670 See the Kconfig.__init__() docstring for raised exceptions
1671 (OSError/IOError). KconfigError is never raised here.
1674 Path to write minimal configuration to.
1676 header (default: None):
1677 Text inserted verbatim at the beginning of the file. You would
1678 usually want each line to start with '#' to make it a comment, and
1679 include a final terminating newline.
1681 if None (the default), the value of the environment variable
1682 KCONFIG_CONFIG_HEADER had when the Kconfig instance was created will
1683 be used if it was set, and no header otherwise. See the
1684 Kconfig.config_header attribute.
1686 Returns a string with a message saying the minimal configuration got
1687 saved, or that there were no changes to it. This is meant to reduce
1688 boilerplate in tools, which can do e.g.
1689 print(kconf.write_min_config()).
1691 if self._write_if_changed(filename, self._min_config_contents(header)):
1692 return "Minimal configuration saved to '{}'".format(filename)
1693 return "No change to minimal configuration in '{}'".format(filename)
1695 def _min_config_contents(self, header):
1696 # write_min_config() helper. Returns the contents to write as a string,
1697 # with 'header' or KCONFIG_CONFIG_HEADER at the beginning.
1700 header = self.config_header
1702 chunks = [header] # "".join()ed later
1705 for sym in self.unique_defined_syms:
1706 # Skip symbols that cannot be changed. Only check
1707 # non-choice symbols, as selects don't affect choice
1709 if not sym.choice and \
1710 sym.visibility <= expr_value(sym.rev_dep):
1713 # Skip symbols whose value matches their default
1714 if sym.str_value == sym._str_default():
1717 # Skip symbols that would be selected by default in a
1718 # choice, unless the choice is optional or the symbol type
1719 # isn't bool (it might be possible to set the choice mode
1720 # to n or the symbol to m in those cases).
1722 not sym.choice.is_optional and \
1723 sym.choice._selection_from_defaults() is sym and \
1724 sym.orig_type is BOOL and \
1728 add(sym.config_string)
1730 return "".join(chunks)
1732 def sync_deps(self, path):
1734 Creates or updates a directory structure that can be used to avoid
1735 doing a full rebuild whenever the configuration is changed, mirroring
1736 include/config/ in the kernel.
1738 This function is intended to be called during each build, before
1739 compiling source files that depend on configuration symbols.
1741 See the Kconfig.__init__() docstring for raised exceptions
1742 (OSError/IOError). KconfigError is never raised here.
1747 sync_deps(path) does the following:
1749 1. If the directory <path> does not exist, it is created.
1751 2. If <path>/auto.conf exists, old symbol values are loaded from it,
1752 which are then compared against the current symbol values. If a
1753 symbol has changed value (would generate different output in
1754 autoconf.h compared to before), the change is signaled by
1755 touch'ing a file corresponding to the symbol.
1757 The first time sync_deps() is run on a directory, <path>/auto.conf
1758 won't exist, and no old symbol values will be available. This
1759 logically has the same effect as updating the entire
1762 The path to a symbol's file is calculated from the symbol's name
1763 by replacing all '_' with '/' and appending '.h'. For example, the
1764 symbol FOO_BAR_BAZ gets the file <path>/foo/bar/baz.h, and FOO
1765 gets the file <path>/foo.h.
1767 This scheme matches the C tools. The point is to avoid having a
1768 single directory with a huge number of files, which the underlying
1769 filesystem might not handle well.
1771 3. A new auto.conf with the current symbol values is written, to keep
1772 track of them for the next build.
1774 If auto.conf exists and its contents is identical to what would
1775 get written out, it is left untouched. This avoids updating file
1776 metadata like the modification time and possibly triggering
1777 redundant work in build tools.
1780 The last piece of the puzzle is knowing what symbols each source file
1781 depends on. Knowing that, dependencies can be added from source files
1782 to the files corresponding to the symbols they depends on. The source
1783 file will then get recompiled (only) when the symbol value changes
1784 (provided sync_deps() is run first during each build).
1786 The tool in the kernel that extracts symbol dependencies from source
1787 files is scripts/basic/fixdep.c. Missing symbol files also correspond
1788 to "not changed", which fixdep deals with by using the $(wildcard) Make
1789 function when adding symbol prerequisites to source files.
1791 In case you need a different scheme for your project, the sync_deps()
1792 implementation can be used as a template.
1794 if not exists(path):
1795 os.mkdir(path, 0o755)
1797 # Load old values from auto.conf, if any
1798 self._load_old_vals(path)
1800 for sym in self.unique_defined_syms:
1801 # _write_to_conf is determined when the value is calculated. This
1802 # is a hidden function call due to property magic.
1804 # Note: In client code, you can check if sym.config_string is empty
1805 # instead, to avoid accessing the internal _write_to_conf variable
1806 # (though it's likely to keep working).
1809 # n tristate values do not get written to auto.conf and autoconf.h,
1810 # making a missing symbol logically equivalent to n
1812 if sym._write_to_conf:
1813 if sym._old_val is None and \
1814 sym.orig_type in _BOOL_TRISTATE and \
1816 # No old value (the symbol was missing or n), new value n.
1820 if val == sym._old_val:
1821 # New value matches old. No change.
1824 elif sym._old_val is None:
1825 # The symbol wouldn't appear in autoconf.h (because
1826 # _write_to_conf is false), and it wouldn't have appeared in
1827 # autoconf.h previously either (because it didn't appear in
1828 # auto.conf). No change.
1831 # 'sym' has a new value. Flag it.
1832 _touch_dep_file(path, sym.name)
1834 # Remember the current values as the "new old" values.
1836 # This call could go anywhere after the call to _load_old_vals(), but
1837 # putting it last means _sync_deps() can be safely rerun if it fails
1838 # before this point.
1839 self._write_old_vals(path)
1841 def _load_old_vals(self, path):
1842 # Loads old symbol values from auto.conf into a dedicated
1843 # Symbol._old_val field. Mirrors load_config().
1845 # The extra field could be avoided with some trickery involving dumping
1846 # symbol values and restoring them later, but this is simpler and
1847 # faster. The C tools also use a dedicated field for this purpose.
1849 for sym in self.unique_defined_syms:
1853 auto_conf = self._open(join(path, "auto.conf"), "r")
1854 except EnvironmentError as e:
1855 if e.errno == errno.ENOENT:
1860 with auto_conf as f:
1862 match = self._set_match(line)
1864 # We only expect CONFIG_FOO=... (and possibly a header
1865 # comment) in auto.conf
1868 name, val = match.groups()
1869 if name in self.syms:
1870 sym = self.syms[name]
1872 if sym.orig_type is STRING:
1873 match = _conf_string_match(val)
1876 val = unescape(match.group(1))
1878 self.syms[name]._old_val = val
1880 # Flag that the symbol no longer exists, in
1881 # case something still depends on it
1882 _touch_dep_file(path, name)
1884 def _write_old_vals(self, path):
1885 # Helper for writing auto.conf. Basically just a simplified
1886 # write_config() that doesn't write any comments (including
1887 # '# CONFIG_FOO is not set' comments). The format matches the C
1888 # implementation, though the ordering is arbitrary there (depends on
1889 # the hash table implementation).
1891 # A separate helper function is neater than complicating write_config()
1892 # by passing a flag to it, plus we only need to look at symbols here.
1894 self._write_if_changed(
1895 os.path.join(path, "auto.conf"),
1896 self._old_vals_contents())
1898 def _old_vals_contents(self):
1899 # _write_old_vals() helper. Returns the contents to write as a string.
1901 # Temporary list instead of generator makes this a bit faster
1903 sym.config_string for sym in self.unique_defined_syms
1904 if not (sym.orig_type in _BOOL_TRISTATE and not sym.tri_value)
1907 def node_iter(self, unique_syms=False):
1909 Returns a generator for iterating through all MenuNode's in the Kconfig
1910 tree. The iteration is done in Kconfig definition order (each node is
1911 visited before its children, and the children of a node are visited
1912 before the next node).
1914 The Kconfig.top_node menu node is skipped. It contains an implicit menu
1915 that holds the top-level items.
1917 As an example, the following code will produce a list equal to
1918 Kconfig.defined_syms:
1920 defined_syms = [node.item for node in kconf.node_iter()
1921 if isinstance(node.item, Symbol)]
1923 unique_syms (default: False):
1924 If True, only the first MenuNode will be included for symbols defined
1925 in multiple locations.
1927 Using kconf.node_iter(True) in the example above would give a list
1928 equal to unique_defined_syms.
1931 for sym in self.unique_defined_syms:
1932 sym._visited = False
1934 node = self.top_node
1936 # Jump to the next node with an iterative tree walk
1951 if unique_syms and node.item.__class__ is Symbol:
1952 if node.item._visited:
1954 node.item._visited = True
1958 def eval_string(self, s):
1960 Returns the tristate value of the expression 's', represented as 0, 1,
1961 and 2 for n, m, and y, respectively. Raises KconfigError on syntax
1962 errors. Warns if undefined symbols are referenced.
1964 As an example, if FOO and BAR are tristate symbols at least one of
1965 which has the value y, then eval_string("y && (FOO || BAR)") returns
1968 To get the string value of non-bool/tristate symbols, use
1969 Symbol.str_value. eval_string() always returns a tristate value, and
1970 all non-bool/tristate symbols have the tristate value 0 (n).
1972 The expression parsing is consistent with how parsing works for
1973 conditional ('if ...') expressions in the configuration, and matches
1974 the C implementation. m is rewritten to 'm && MODULES', so
1975 eval_string("m") will return 0 (n) unless modules are enabled.
1977 # The parser is optimized to be fast when parsing Kconfig files (where
1978 # an expression can never appear at the beginning of a line). We have
1979 # to monkey-patch things a bit here to reuse it.
1981 self.filename = None
1983 self._tokens = self._tokenize("if " + s)
1984 # Strip "if " to avoid giving confusing error messages
1986 self._tokens_i = 1 # Skip the 'if' token
1988 return expr_value(self._expect_expr_and_eol())
1990 def unset_values(self):
1992 Removes any user values from all symbols, as if Kconfig.load_config()
1993 or Symbol.set_value() had never been called.
1995 self._warn_assign_no_prompt = False
1997 # set_value() already rejects undefined symbols, and they don't
1998 # need to be invalidated (because their value never changes), so we
1999 # can just iterate over defined symbols
2000 for sym in self.unique_defined_syms:
2003 for choice in self.unique_choices:
2004 choice.unset_value()
2006 self._warn_assign_no_prompt = True
2008 def enable_warnings(self):
2010 Do 'Kconfig.warn = True' instead. Maintained for backwards
2015 def disable_warnings(self):
2017 Do 'Kconfig.warn = False' instead. Maintained for backwards
2022 def enable_stderr_warnings(self):
2024 Do 'Kconfig.warn_to_stderr = True' instead. Maintained for backwards
2027 self.warn_to_stderr = True
2029 def disable_stderr_warnings(self):
2031 Do 'Kconfig.warn_to_stderr = False' instead. Maintained for backwards
2034 self.warn_to_stderr = False
2036 def enable_undef_warnings(self):
2038 Do 'Kconfig.warn_assign_undef = True' instead. Maintained for backwards
2041 self.warn_assign_undef = True
2043 def disable_undef_warnings(self):
2045 Do 'Kconfig.warn_assign_undef = False' instead. Maintained for
2046 backwards compatibility.
2048 self.warn_assign_undef = False
2050 def enable_override_warnings(self):
2052 Do 'Kconfig.warn_assign_override = True' instead. Maintained for
2053 backwards compatibility.
2055 self.warn_assign_override = True
2057 def disable_override_warnings(self):
2059 Do 'Kconfig.warn_assign_override = False' instead. Maintained for
2060 backwards compatibility.
2062 self.warn_assign_override = False
2064 def enable_redun_warnings(self):
2066 Do 'Kconfig.warn_assign_redun = True' instead. Maintained for backwards
2069 self.warn_assign_redun = True
2071 def disable_redun_warnings(self):
2073 Do 'Kconfig.warn_assign_redun = False' instead. Maintained for
2074 backwards compatibility.
2076 self.warn_assign_redun = False
2080 Returns a string with information about the Kconfig object when it is
2081 evaluated on e.g. the interactive Python prompt.
2084 return "enabled" if flag else "disabled"
2086 return "<{}>".format(", ".join((
2087 "configuration with {} symbols".format(len(self.syms)),
2088 'main menu prompt "{}"'.format(self.mainmenu_text),
2089 "srctree is current directory" if not self.srctree else
2090 'srctree "{}"'.format(self.srctree),
2091 'config symbol prefix "{}"'.format(self.config_prefix),
2092 "warnings " + status(self.warn),
2093 "printing of warnings to stderr " + status(self.warn_to_stderr),
2094 "undef. symbol assignment warnings " +
2095 status(self.warn_assign_undef),
2096 "overriding symbol assignment warnings " +
2097 status(self.warn_assign_override),
2098 "redundant symbol assignment warnings " +
2099 status(self.warn_assign_redun)
2111 def _open_config(self, filename):
2112 # Opens a .config file. First tries to open 'filename', then
2113 # '$srctree/filename' if $srctree was set when the configuration was
2117 return self._open(filename, "r")
2118 except EnvironmentError as e:
2119 # This will try opening the same file twice if $srctree is unset,
2120 # but it's not a big deal
2122 return self._open(join(self.srctree, filename), "r")
2123 except EnvironmentError as e2:
2124 # This is needed for Python 3, because e2 is deleted after
2127 # https://docs.python.org/3/reference/compound_stmts.html#the-try-statement
2130 raise _KconfigIOError(
2131 e, "Could not open '{}' ({}: {}). Check that the $srctree "
2132 "environment variable ({}) is set correctly."
2133 .format(filename, errno.errorcode[e.errno], e.strerror,
2134 "set to '{}'".format(self.srctree) if self.srctree
2135 else "unset or blank"))
2137 def _enter_file(self, filename):
2138 # Jumps to the beginning of a sourced Kconfig file, saving the previous
2139 # position and file object.
2142 # Absolute path to file
2144 # Path relative to $srctree, stored in e.g. self.filename (which makes
2145 # it indirectly show up in MenuNode.filename). Equals 'filename' for
2146 # absolute paths passed to 'source'.
2147 if filename.startswith(self._srctree_prefix):
2148 # Relative path (or a redundant absolute path to within $srctree,
2149 # but it's probably fine to reduce those too)
2150 rel_filename = filename[len(self._srctree_prefix):]
2153 rel_filename = filename
2155 self.kconfig_filenames.append(rel_filename)
2157 # The parent Kconfig files are represented as a list of
2158 # (<include path>, <Python 'file' object for Kconfig file>) tuples.
2160 # <include path> is immutable and holds a *tuple* of
2161 # (<filename>, <linenr>) tuples, giving the locations of the 'source'
2162 # statements in the parent Kconfig files. The current include path is
2163 # also available in Kconfig._include_path.
2165 # The point of this redundant setup is to allow Kconfig._include_path
2166 # to be assigned directly to MenuNode.include_path without having to
2167 # copy it, sharing it wherever possible.
2169 # Save include path and 'file' object (via its 'readline' function)
2170 # before entering the file
2171 self._filestack.append((self._include_path, self._readline))
2173 # _include_path is a tuple, so this rebinds the variable instead of
2174 # doing in-place modification
2175 self._include_path += ((self.filename, self.linenr),)
2177 # Check for recursive 'source'
2178 for name, _ in self._include_path:
2179 if name == rel_filename:
2181 "\n{}:{}: recursive 'source' of '{}' detected. Check that "
2182 "environment variables are set correctly.\n"
2184 .format(self.filename, self.linenr, rel_filename,
2185 "\n".join("{}:{}".format(name, linenr)
2186 for name, linenr in self._include_path)))
2189 self._readline = self._open(filename, "r").readline
2190 except EnvironmentError as e:
2191 # We already know that the file exists
2192 raise _KconfigIOError(
2193 e, "{}:{}: Could not open '{}' (in '{}') ({}: {})"
2194 .format(self.filename, self.linenr, filename,
2196 errno.errorcode[e.errno], e.strerror))
2198 self.filename = rel_filename
2201 def _leave_file(self):
2202 # Returns from a Kconfig file to the file that sourced it. See
2205 # Restore location from parent Kconfig file
2206 self.filename, self.linenr = self._include_path[-1]
2207 # Restore include path and 'file' object
2208 self._readline.__self__.close() # __self__ fetches the 'file' object
2209 self._include_path, self._readline = self._filestack.pop()
2211 def _next_line(self):
2212 # Fetches and tokenizes the next line from the current Kconfig file.
2213 # Returns False at EOF and True otherwise.
2215 # We might already have tokens from parsing a line and discovering that
2216 # it's part of a different construct
2217 if self._reuse_tokens:
2218 self._reuse_tokens = False
2219 # self._tokens_i is known to be 1 here, because _parse_props()
2220 # leaves it like that when it can't recognize a line (or parses a
2224 # readline() returns '' over and over at EOF, which we rely on for help
2225 # texts at the end of files (see _line_after_help())
2226 line = self._readline()
2231 # Handle line joining
2232 while line.endswith("\\\n"):
2233 line = line[:-2] + self._readline()
2236 self._tokens = self._tokenize(line)
2237 # Initialize to 1 instead of 0 to factor out code from _parse_block()
2238 # and _parse_props(). They immediately fetch self._tokens[0].
2243 def _line_after_help(self, line):
2244 # Tokenizes a line after a help text. This case is special in that the
2245 # line has already been fetched (to discover that it isn't part of the
2248 # An earlier version used a _saved_line variable instead that was
2249 # checked in _next_line(). This special-casing gets rid of it and makes
2250 # _reuse_tokens alone sufficient to handle unget.
2252 # Handle line joining
2253 while line.endswith("\\\n"):
2254 line = line[:-2] + self._readline()
2257 self._tokens = self._tokenize(line)
2258 self._reuse_tokens = True
2260 def _write_if_changed(self, filename, contents):
2261 # Writes 'contents' into 'filename', but only if it differs from the
2262 # current contents of the file.
2264 # Another variant would be write a temporary file on the same
2265 # filesystem, compare the files, and rename() the temporary file if it
2266 # differs, but it breaks stuff like write_config("/dev/null"), which is
2267 # used out there to force evaluation-related warnings to be generated.
2268 # This simple version is pretty failsafe and portable.
2270 # Returns True if the file has changed and is updated, and False
2273 if self._contents_eq(filename, contents):
2275 with self._open(filename, "w") as f:
2279 def _contents_eq(self, filename, contents):
2280 # Returns True if the contents of 'filename' is 'contents' (a string),
2281 # and False otherwise (including if 'filename' can't be opened/read)
2284 with self._open(filename, "r") as f:
2285 # Robust re. things like encoding and line endings (mmap()
2287 return f.read(len(contents) + 1) == contents
2288 except EnvironmentError:
2289 # If the error here would prevent writing the file as well, we'll
2297 def _lookup_sym(self, name):
2298 # Fetches the symbol 'name' from the symbol table, creating and
2299 # registering it if it does not exist. If '_parsing_kconfigs' is False,
2300 # it means we're in eval_string(), and new symbols won't be registered.
2302 if name in self.syms:
2303 return self.syms[name]
2308 sym.is_constant = False
2309 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
2311 if self._parsing_kconfigs:
2312 self.syms[name] = sym
2314 self._warn("no symbol {} in configuration".format(name))
2318 def _lookup_const_sym(self, name):
2319 # Like _lookup_sym(), for constant (quoted) symbols
2321 if name in self.const_syms:
2322 return self.const_syms[name]
2327 sym.is_constant = True
2328 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
2330 if self._parsing_kconfigs:
2331 self.const_syms[name] = sym
2335 def _tokenize(self, s):
2336 # Parses 's', returning a None-terminated list of tokens. Registers any
2337 # new symbols encountered with _lookup(_const)_sym().
2339 # Tries to be reasonably speedy by processing chunks of text via
2340 # regexes and string operations where possible. This is the biggest
2341 # hotspot during parsing.
2343 # It might be possible to rewrite this to 'yield' tokens instead,
2344 # working across multiple lines. Lookback and compatibility with old
2345 # janky versions of the C tools complicate things though.
2347 self._line = s # Used for error reporting
2349 # Initial token on the line
2350 match = _command_match(s)
2352 if s.isspace() or s.lstrip().startswith("#"):
2354 self._parse_error("unknown token at start of line")
2356 # Tricky implementation detail: While parsing a token, 'token' refers
2357 # to the previous token. See _STRING_LEX for why this is needed.
2358 token = _get_keyword(match.group(1))
2360 # Backwards compatibility with old versions of the C tools, which
2361 # (accidentally) accepted stuff like "--help--" and "-help---".
2362 # This was fixed in the C tools by commit c2264564 ("kconfig: warn
2363 # of unhandled characters in Kconfig commands"), committed in July
2364 # 2015, but it seems people still run Kconfiglib on older kernels.
2365 if s.strip(" \t\n-") == "help":
2366 return (_T_HELP, None)
2368 # If the first token is not a keyword (and not a weird help token),
2369 # we have a preprocessor variable assignment (or a bare macro on a
2371 self._parse_assignment(s)
2375 # The current index in the string being tokenized
2378 # Main tokenization loop (for tokens past the first one)
2380 # Test for an identifier/keyword first. This is the most common
2382 match = _id_keyword_match(s, i)
2384 # We have an identifier or keyword
2386 # Check what it is. lookup_sym() will take care of allocating
2387 # new symbols for us the first time we see them. Note that
2388 # 'token' still refers to the previous token.
2390 name = match.group(1)
2391 keyword = _get_keyword(name)
2398 elif token not in _STRING_LEX:
2399 # It's a non-const symbol, except we translate n, m, and y
2400 # into the corresponding constant symbols, like the C
2404 # Macro expansion within symbol name
2405 name, s, i = self._expand_name(s, i)
2409 token = self.const_syms[name] if name in STR_TO_TRI else \
2410 self._lookup_sym(name)
2413 # It's a case of missing quotes. For example, the
2414 # following is accepted:
2416 # menu unquoted_title
2419 # tristate unquoted_prompt
2423 # Named choices ('choice FOO') also end up here.
2425 if token is not _T_CHOICE:
2426 self._warn("style: quotes recommended around '{}' in '{}'"
2427 .format(name, self._line.strip()),
2428 self.filename, self.linenr)
2434 # Neither a keyword nor a non-const symbol
2436 # We always strip whitespace after tokens, so it is safe to
2437 # assume that s[i] is the start of a token here.
2441 if "$" not in s and "\\" not in s:
2442 # Fast path for lines without $ and \. Find the
2444 end_i = s.find(c, i + 1) + 1
2446 self._parse_error("unterminated string")
2447 val = s[i + 1:end_i - 1]
2451 s, end_i = self._expand_str(s, i)
2453 # os.path.expandvars() and the $UNAME_RELEASE replace()
2454 # is a backwards compatibility hack, which should be
2455 # reasonably safe as expandvars() leaves references to
2456 # undefined env. vars. as is.
2458 # The preprocessor functionality changed how
2459 # environment variables are referenced, to $(FOO).
2460 val = expandvars(s[i + 1:end_i - 1]
2461 .replace("$UNAME_RELEASE",
2466 # This is the only place where we don't survive with a
2467 # single token of lookback: 'option env="FOO"' does not
2468 # refer to a constant symbol named "FOO".
2470 val if token in _STRING_LEX or tokens[0] is _T_OPTION \
2471 else self._lookup_const_sym(val)
2473 elif s.startswith("&&", i):
2477 elif s.startswith("||", i):
2485 elif s.startswith("!=", i):
2494 token = _T_OPEN_PAREN
2498 token = _T_CLOSE_PAREN
2507 elif s.startswith("<=", i):
2508 token = _T_LESS_EQUAL
2515 elif s.startswith(">=", i):
2516 token = _T_GREATER_EQUAL
2525 self._parse_error("unknown tokens in line")
2528 # Skip trailing whitespace
2529 while i < len(s) and s[i].isspace():
2534 tokens.append(token)
2536 # None-terminating the token list makes token fetching simpler/faster
2541 # Helpers for syntax checking and token fetching. See the
2542 # 'Intro to expressions' section for what a constant symbol is.
2544 # More of these could be added, but the single-use cases are inlined as an
2547 def _expect_sym(self):
2548 token = self._tokens[self._tokens_i]
2551 if token.__class__ is not Symbol:
2552 self._parse_error("expected symbol")
2556 def _expect_nonconst_sym(self):
2557 # Used for 'select' and 'imply' only. We know the token indices.
2559 token = self._tokens[1]
2562 if token.__class__ is not Symbol or token.is_constant:
2563 self._parse_error("expected nonconstant symbol")
2567 def _expect_str_and_eol(self):
2568 token = self._tokens[self._tokens_i]
2571 if token.__class__ is not str:
2572 self._parse_error("expected string")
2574 if self._tokens[self._tokens_i] is not None:
2575 self._trailing_tokens_error()
2579 def _expect_expr_and_eol(self):
2580 expr = self._parse_expr(True)
2582 if self._tokens[self._tokens_i] is not None:
2583 self._trailing_tokens_error()
2587 def _check_token(self, token):
2588 # If the next token is 'token', removes it and returns True
2590 if self._tokens[self._tokens_i] is token:
2596 # Preprocessor logic
2599 def _parse_assignment(self, s):
2600 # Parses a preprocessor variable assignment, registering the variable
2601 # if it doesn't already exist. Also takes care of bare macros on lines
2602 # (which are allowed, and can be useful for their side effects).
2604 # Expand any macros in the left-hand side of the assignment (the
2609 i = _assignment_lhs_fragment_match(s, i).end()
2610 if s.startswith("$(", i):
2611 s, i = self._expand_macro(s, i, ())
2616 # We also accept a bare macro on a line (e.g.
2617 # $(warning-if,$(foo),ops)), provided it expands to a blank string
2624 # Extract assignment operator (=, :=, or +=) and value
2625 rhs_match = _assignment_rhs_match(s, i)
2627 self._parse_error("syntax error")
2629 op, val = rhs_match.groups()
2632 if name in self.variables:
2633 # Already seen variable
2634 var = self.variables[name]
2640 var._n_expansions = 0
2641 self.variables[name] = var
2643 # += acts like = on undefined variables (defines a recursive
2649 var.is_recursive = True
2652 var.is_recursive = False
2653 var.value = self._expand_whole(val, ())
2655 # += does immediate expansion if the variable was last set
2657 var.value += " " + (val if var.is_recursive else
2658 self._expand_whole(val, ()))
2660 def _expand_whole(self, s, args):
2661 # Expands preprocessor macros in all of 's'. Used whenever we don't
2662 # have to worry about delimiters. See _expand_macro() re. the 'args'
2665 # Returns the expanded string.
2672 s, i = self._expand_macro(s, i, args)
2675 def _expand_name(self, s, i):
2676 # Expands a symbol name starting at index 'i' in 's'.
2678 # Returns the expanded name, the expanded 's' (including the part
2679 # before the name), and the index of the first character in the next
2680 # token after the name.
2682 s, end_i = self._expand_name_iter(s, i)
2684 # isspace() is False for empty strings
2685 if not name.strip():
2686 # Avoid creating a Kconfig symbol with a blank name. It's almost
2687 # guaranteed to be an error.
2688 self._parse_error("macro expanded to blank string")
2690 # Skip trailing whitespace
2691 while end_i < len(s) and s[end_i].isspace():
2694 return name, s, end_i
2696 def _expand_name_iter(self, s, i):
2697 # Expands a symbol name starting at index 'i' in 's'.
2699 # Returns the expanded 's' (including the part before the name) and the
2700 # index of the first character after the expanded name in 's'.
2703 match = _name_special_search(s, i)
2705 if match.group() != "$(":
2706 return (s, match.start())
2707 s, i = self._expand_macro(s, match.start(), ())
2709 def _expand_str(self, s, i):
2710 # Expands a quoted string starting at index 'i' in 's'. Handles both
2711 # backslash escapes and macro expansion.
2713 # Returns the expanded 's' (including the part before the string) and
2714 # the index of the first character after the expanded string in 's'.
2717 i += 1 # Skip over initial "/'
2719 match = _string_special_search(s, i)
2721 self._parse_error("unterminated string")
2724 if match.group() == quote:
2725 # Found the end of the string
2726 return (s, match.end())
2728 elif match.group() == "\\":
2729 # Replace '\x' with 'x'. 'i' ends up pointing to the character
2730 # after 'x', which allows macros to be canceled with '\$(foo)'.
2732 s = s[:match.start()] + s[i:]
2734 elif match.group() == "$(":
2735 # A macro call within the string
2736 s, i = self._expand_macro(s, match.start(), ())
2739 # A ' quote within " quotes or vice versa
2742 def _expand_macro(self, s, i, args):
2743 # Expands a macro starting at index 'i' in 's'. If this macro resulted
2744 # from the expansion of another macro, 'args' holds the arguments
2745 # passed to that macro.
2747 # Returns the expanded 's' (including the part before the macro) and
2748 # the index of the first character after the expanded macro in 's'.
2751 i += 2 # Skip over "$("
2753 arg_start = i # Start of current macro argument
2754 new_args = [] # Arguments of this macro call
2755 nesting = 0 # Current parentheses nesting level
2758 match = _macro_special_search(s, i)
2760 self._parse_error("missing end parenthesis in macro expansion")
2763 if match.group() == "(":
2767 elif match.group() == ")":
2773 # Found the end of the macro
2775 new_args.append(s[arg_start:match.start()])
2777 # $(1) is replaced by the first argument to the function, etc.,
2778 # provided at least that many arguments were passed
2781 # Does the macro look like an integer, with a corresponding
2782 # argument? If so, expand it to the value of the argument.
2783 res += args[int(new_args[0])]
2784 except (ValueError, IndexError):
2785 # Regular variables are just functions without arguments,
2786 # and also go through the function value path
2787 res += self._fn_val(new_args)
2789 return (res + s[match.end():], len(res))
2791 elif match.group() == ",":
2796 # Found the end of a macro argument
2797 new_args.append(s[arg_start:match.start()])
2800 else: # match.group() == "$("
2801 # A nested macro call within the macro
2802 s, i = self._expand_macro(s, match.start(), args)
2804 def _fn_val(self, args):
2805 # Returns the result of calling the function args[0] with the arguments
2806 # args[1..len(args)-1]. Plain variables are treated as functions
2807 # without arguments.
2811 if fn in self.variables:
2812 var = self.variables[fn]
2816 if var._n_expansions:
2817 self._parse_error("Preprocessor variable {} recursively "
2818 "references itself".format(var.name))
2819 elif var._n_expansions > 100:
2820 # Allow functions to call themselves, but guess that functions
2821 # that are overly recursive are stuck
2822 self._parse_error("Preprocessor function {} seems stuck "
2823 "in infinite recursion".format(var.name))
2825 var._n_expansions += 1
2826 res = self._expand_whole(self.variables[fn].value, args)
2827 var._n_expansions -= 1
2830 if fn in self._functions:
2831 # Built-in or user-defined function
2833 py_fn, min_arg, max_arg = self._functions[fn]
2835 if len(args) - 1 < min_arg or \
2836 (max_arg is not None and len(args) - 1 > max_arg):
2838 if min_arg == max_arg:
2839 expected_args = min_arg
2840 elif max_arg is None:
2841 expected_args = "{} or more".format(min_arg)
2843 expected_args = "{}-{}".format(min_arg, max_arg)
2845 raise KconfigError("{}:{}: bad number of arguments in call "
2846 "to {}, expected {}, got {}"
2847 .format(self.filename, self.linenr, fn,
2848 expected_args, len(args) - 1))
2850 return py_fn(self, *args)
2852 # Environment variables are tried last
2853 if fn in os.environ:
2854 self.env_vars.add(fn)
2855 return os.environ[fn]
2863 def _make_and(self, e1, e2):
2864 # Constructs an AND (&&) expression. Performs trivial simplification.
2872 if e1 is self.n or e2 is self.n:
2875 return (AND, e1, e2)
2877 def _make_or(self, e1, e2):
2878 # Constructs an OR (||) expression. Performs trivial simplification.
2886 if e1 is self.y or e2 is self.y:
2891 def _parse_block(self, end_token, parent, prev):
2892 # Parses a block, which is the contents of either a file or an if,
2893 # menu, or choice statement.
2896 # The token that ends the block, e.g. _T_ENDIF ("endif") for ifs.
2900 # The parent menu node, corresponding to a menu, Choice, or 'if'.
2901 # 'if's are flattened after parsing.
2904 # The previous menu node. New nodes will be added after this one (by
2905 # modifying 'next' pointers).
2907 # 'prev' is reused to parse a list of child menu nodes (for a menu or
2908 # Choice): After parsing the children, the 'next' pointer is assigned
2909 # to the 'list' pointer to "tilt up" the children above the node.
2911 # Returns the final menu node in the block (or 'prev' if the block is
2912 # empty). This allows chaining.
2914 while self._next_line():
2915 t0 = self._tokens[0]
2917 if t0 is _T_CONFIG or t0 is _T_MENUCONFIG:
2918 # The tokenizer allocates Symbol objects for us
2919 sym = self._tokens[1]
2921 if sym.__class__ is not Symbol or sym.is_constant:
2922 self._parse_error("missing or bad symbol name")
2924 if self._tokens[2] is not None:
2925 self._trailing_tokens_error()
2927 self.defined_syms.append(sym)
2932 node.is_menuconfig = (t0 is _T_MENUCONFIG)
2933 node.prompt = node.help = node.list = None
2934 node.parent = parent
2935 node.filename = self.filename
2936 node.linenr = self.linenr
2937 node.include_path = self._include_path
2939 sym.nodes.append(node)
2941 self._parse_props(node)
2943 if node.is_menuconfig and not node.prompt:
2944 self._warn("the menuconfig symbol {} has no prompt"
2945 .format(sym.name_and_loc))
2952 # due to tricky Python semantics. The order matters.
2953 prev.next = prev = node
2959 elif t0 in _SOURCE_TOKENS:
2960 pattern = self._expect_str_and_eol()
2962 if t0 in _REL_SOURCE_TOKENS:
2964 pattern = join(dirname(self.filename), pattern)
2966 # - glob() doesn't support globbing relative to a directory, so
2967 # we need to prepend $srctree to 'pattern'. Use join()
2968 # instead of '+' so that an absolute path in 'pattern' is
2971 # - Sort the glob results to ensure a consistent ordering of
2972 # Kconfig symbols, which indirectly ensures a consistent
2973 # ordering in e.g. .config files
2974 filenames = sorted(iglob(join(self._srctree_prefix, pattern)))
2976 if not filenames and t0 in _OBL_SOURCE_TOKENS:
2978 "{}:{}: '{}' not found (in '{}'). Check that "
2979 "environment variables are set correctly (e.g. "
2980 "$srctree, which is {}). Also note that unset "
2981 "environment variables expand to the empty string."
2982 .format(self.filename, self.linenr, pattern,
2984 "set to '{}'".format(self.srctree)
2985 if self.srctree else "unset or blank"))
2987 for filename in filenames:
2988 self._enter_file(filename)
2989 prev = self._parse_block(None, parent, prev)
2992 elif t0 is end_token:
2993 # Reached the end of the block. Terminate the final node and
2996 if self._tokens[1] is not None:
2997 self._trailing_tokens_error()
3004 node.item = node.prompt = None
3005 node.parent = parent
3006 node.dep = self._expect_expr_and_eol()
3008 self._parse_block(_T_ENDIF, node, node)
3009 node.list = node.next
3011 prev.next = prev = node
3016 node.item = t0 # _T_MENU == MENU
3017 node.is_menuconfig = True
3018 node.prompt = (self._expect_str_and_eol(), self.y)
3019 node.visibility = self.y
3020 node.parent = parent
3021 node.filename = self.filename
3022 node.linenr = self.linenr
3023 node.include_path = self._include_path
3025 self.menus.append(node)
3027 self._parse_props(node)
3028 self._parse_block(_T_ENDMENU, node, node)
3029 node.list = node.next
3031 prev.next = prev = node
3033 elif t0 is _T_COMMENT:
3036 node.item = t0 # _T_COMMENT == COMMENT
3037 node.is_menuconfig = False
3038 node.prompt = (self._expect_str_and_eol(), self.y)
3040 node.parent = parent
3041 node.filename = self.filename
3042 node.linenr = self.linenr
3043 node.include_path = self._include_path
3045 self.comments.append(node)
3047 self._parse_props(node)
3049 prev.next = prev = node
3051 elif t0 is _T_CHOICE:
3052 if self._tokens[1] is None:
3054 choice.direct_dep = self.n
3057 name = self._expect_str_and_eol()
3058 choice = self.named_choices.get(name)
3062 choice.direct_dep = self.n
3063 self.named_choices[name] = choice
3065 self.choices.append(choice)
3068 node.kconfig = choice.kconfig = self
3070 node.is_menuconfig = True
3071 node.prompt = node.help = None
3072 node.parent = parent
3073 node.filename = self.filename
3074 node.linenr = self.linenr
3075 node.include_path = self._include_path
3077 choice.nodes.append(node)
3079 self._parse_props(node)
3080 self._parse_block(_T_ENDCHOICE, node, node)
3081 node.list = node.next
3083 prev.next = prev = node
3085 elif t0 is _T_MAINMENU:
3086 self.top_node.prompt = (self._expect_str_and_eol(), self.y)
3089 # A valid endchoice/endif/endmenu is caught by the 'end_token'
3092 "no corresponding 'choice'" if t0 is _T_ENDCHOICE else
3093 "no corresponding 'if'" if t0 is _T_ENDIF else
3094 "no corresponding 'menu'" if t0 is _T_ENDMENU else
3095 "unrecognized construct")
3097 # End of file reached. Return the last node.
3101 "error: expected '{}' at end of '{}'"
3102 .format("endchoice" if end_token is _T_ENDCHOICE else
3103 "endif" if end_token is _T_ENDIF else
3109 def _parse_cond(self):
3110 # Parses an optional 'if <expr>' construct and returns the parsed
3111 # <expr>, or self.y if the next token is not _T_IF
3113 expr = self._parse_expr(True) if self._check_token(_T_IF) else self.y
3115 if self._tokens[self._tokens_i] is not None:
3116 self._trailing_tokens_error()
3120 def _parse_props(self, node):
3121 # Parses and adds properties to the MenuNode 'node' (type, 'prompt',
3122 # 'default's, etc.) Properties are later copied up to symbols and
3123 # choices in a separate pass after parsing, in e.g.
3124 # _add_props_to_sym().
3126 # An older version of this code added properties directly to symbols
3127 # and choices instead of to their menu nodes (and handled dependency
3128 # propagation simultaneously), but that loses information on where a
3129 # property is added when a symbol or choice is defined in multiple
3130 # locations. Some Kconfig configuration systems rely heavily on such
3131 # symbols, and better docs can be generated by keeping track of where
3132 # properties are added.
3135 # The menu node we're parsing properties on
3137 # Dependencies from 'depends on'. Will get propagated to the properties
3141 while self._next_line():
3142 t0 = self._tokens[0]
3144 if t0 in _TYPE_TOKENS:
3145 # Relies on '_T_BOOL is BOOL', etc., to save a conversion
3146 self._set_type(node.item, t0)
3147 if self._tokens[1] is not None:
3148 self._parse_prompt(node)
3150 elif t0 is _T_DEPENDS:
3151 if not self._check_token(_T_ON):
3152 self._parse_error("expected 'on' after 'depends'")
3154 node.dep = self._make_and(node.dep,
3155 self._expect_expr_and_eol())
3158 self._parse_help(node)
3160 elif t0 is _T_SELECT:
3161 if node.item.__class__ is not Symbol:
3162 self._parse_error("only symbols can select")
3164 node.selects.append((self._expect_nonconst_sym(),
3165 self._parse_cond()))
3171 elif t0 is _T_DEFAULT:
3172 node.defaults.append((self._parse_expr(False),
3173 self._parse_cond()))
3175 elif t0 in _DEF_TOKEN_TO_TYPE:
3176 self._set_type(node.item, _DEF_TOKEN_TO_TYPE[t0])
3177 node.defaults.append((self._parse_expr(False),
3178 self._parse_cond()))
3180 elif t0 is _T_PROMPT:
3181 self._parse_prompt(node)
3183 elif t0 is _T_RANGE:
3184 node.ranges.append((self._expect_sym(), self._expect_sym(),
3185 self._parse_cond()))
3187 elif t0 is _T_IMPLY:
3188 if node.item.__class__ is not Symbol:
3189 self._parse_error("only symbols can imply")
3191 node.implies.append((self._expect_nonconst_sym(),
3192 self._parse_cond()))
3194 elif t0 is _T_VISIBLE:
3195 if not self._check_token(_T_IF):
3196 self._parse_error("expected 'if' after 'visible'")
3198 node.visibility = self._make_and(node.visibility,
3199 self._expect_expr_and_eol())
3201 elif t0 is _T_OPTION:
3202 if self._check_token(_T_ENV):
3203 if not self._check_token(_T_EQUAL):
3204 self._parse_error("expected '=' after 'env'")
3206 env_var = self._expect_str_and_eol()
3207 node.item.env_var = env_var
3209 if env_var in os.environ:
3210 node.defaults.append(
3211 (self._lookup_const_sym(os.environ[env_var]),
3214 self._warn("{1} has 'option env=\"{0}\"', "
3215 "but the environment variable {0} is not "
3216 "set".format(node.item.name, env_var),
3217 self.filename, self.linenr)
3219 if env_var != node.item.name:
3220 self._warn("Kconfiglib expands environment variables "
3221 "in strings directly, meaning you do not "
3222 "need 'option env=...' \"bounce\" symbols. "
3223 "For compatibility with the C tools, "
3224 "rename {} to {} (so that the symbol name "
3225 "matches the environment variable name)."
3226 .format(node.item.name, env_var),
3227 self.filename, self.linenr)
3229 elif self._check_token(_T_DEFCONFIG_LIST):
3230 if not self.defconfig_list:
3231 self.defconfig_list = node.item
3233 self._warn("'option defconfig_list' set on multiple "
3234 "symbols ({0} and {1}). Only {0} will be "
3235 "used.".format(self.defconfig_list.name,
3237 self.filename, self.linenr)
3239 elif self._check_token(_T_MODULES):
3240 # To reduce warning spam, only warn if 'option modules' is
3241 # set on some symbol that isn't MODULES, which should be
3242 # safe. I haven't run into any projects that make use
3243 # modules besides the kernel yet, and there it's likely to
3244 # keep being called "MODULES".
3245 if node.item is not self.modules:
3246 self._warn("the 'modules' option is not supported. "
3247 "Let me know if this is a problem for you, "
3248 "as it wouldn't be that hard to implement. "
3249 "Note that modules are supported -- "
3250 "Kconfiglib just assumes the symbol name "
3251 "MODULES, like older versions of the C "
3252 "implementation did when 'option modules' "
3254 self.filename, self.linenr)
3256 elif self._check_token(_T_ALLNOCONFIG_Y):
3257 if node.item.__class__ is not Symbol:
3258 self._parse_error("the 'allnoconfig_y' option is only "
3259 "valid for symbols")
3261 node.item.is_allnoconfig_y = True
3264 self._parse_error("unrecognized option")
3266 elif t0 is _T_OPTIONAL:
3267 if node.item.__class__ is not Choice:
3268 self._parse_error('"optional" is only valid for choices')
3270 node.item.is_optional = True
3273 # Reuse the tokens for the non-property line later
3274 self._reuse_tokens = True
3277 def _set_type(self, sc, new_type):
3278 # Sets the type of 'sc' (symbol or choice) to 'new_type'
3281 if sc.orig_type and sc.orig_type is not new_type:
3282 self._warn("{} defined with multiple types, {} will be used"
3283 .format(sc.name_and_loc, TYPE_TO_STR[new_type]))
3285 sc.orig_type = new_type
3287 def _parse_prompt(self, node):
3288 # 'prompt' properties override each other within a single definition of
3289 # a symbol, but additional prompts can be added by defining the symbol
3293 self._warn(node.item.name_and_loc +
3294 " defined with multiple prompts in single location")
3296 prompt = self._tokens[1]
3299 if prompt.__class__ is not str:
3300 self._parse_error("expected prompt string")
3302 if prompt != prompt.strip():
3303 self._warn(node.item.name_and_loc +
3304 " has leading or trailing whitespace in its prompt")
3306 # This avoid issues for e.g. reStructuredText documentation, where
3307 # '*prompt *' is invalid
3308 prompt = prompt.strip()
3310 node.prompt = (prompt, self._parse_cond())
3312 def _parse_help(self, node):
3313 if node.help is not None:
3314 self._warn(node.item.name_and_loc + " defined with more than "
3315 "one help text -- only the last one will be used")
3317 # Micro-optimization. This code is pretty hot.
3318 readline = self._readline
3320 # Find first non-blank (not all-space) line and get its
3327 self._empty_help(node, line)
3329 if not line.isspace():
3332 len_ = len # Micro-optimization
3334 # Use a separate 'expline' variable here and below to avoid stomping on
3335 # any tabs people might've put deliberately into the first line after
3337 expline = line.expandtabs()
3338 indent = len_(expline) - len_(expline.lstrip())
3340 self._empty_help(node, line)
3343 # The help text goes on till the first non-blank line with less indent
3344 # than the first line
3346 # Add the first line
3347 lines = [expline[indent:]]
3348 add_line = lines.append # Micro-optimization
3353 # No need to preserve the exact whitespace in these
3359 expline = line.expandtabs()
3360 if len_(expline) - len_(expline.lstrip()) < indent:
3362 add_line(expline[indent:])
3364 self.linenr += len_(lines)
3365 node.help = "".join(lines).rstrip()
3367 self._line_after_help(line)
3369 def _empty_help(self, node, line):
3370 self._warn(node.item.name_and_loc +
3371 " has 'help' but empty help text")
3374 self._line_after_help(line)
3376 def _parse_expr(self, transform_m):
3377 # Parses an expression from the tokens in Kconfig._tokens using a
3378 # simple top-down approach. See the module docstring for the expression
3382 # True if m should be rewritten to m && MODULES. See the
3383 # Kconfig.eval_string() documentation.
3387 # expr: and_expr ['||' expr]
3388 # and_expr: factor ['&&' and_expr]
3389 # factor: <symbol> ['='/'!='/'<'/... <symbol>]
3393 # It helps to think of the 'expr: and_expr' case as a single-operand OR
3394 # (no ||), and of the 'and_expr: factor' case as a single-operand AND
3395 # (no &&). Parsing code is always a bit tricky.
3397 # Mind dump: parse_factor() and two nested loops for OR and AND would
3398 # work as well. The straightforward implementation there gives a
3399 # (op, (op, (op, A, B), C), D) parse for A op B op C op D. Representing
3400 # expressions as (op, [list of operands]) instead goes nicely with that
3401 # version, but is wasteful for short expressions and complicates
3402 # expression evaluation and other code that works on expressions (more
3403 # complicated code likely offsets any performance gain from less
3404 # recursion too). If we also try to optimize the list representation by
3405 # merging lists when possible (e.g. when ANDing two AND expressions),
3406 # we end up allocating a ton of lists instead of reusing expressions,
3409 and_expr = self._parse_and_expr(transform_m)
3411 # Return 'and_expr' directly if we have a "single-operand" OR.
3412 # Otherwise, parse the expression on the right and make an OR node.
3413 # This turns A || B || C || D into (OR, A, (OR, B, (OR, C, D))).
3414 return and_expr if not self._check_token(_T_OR) else \
3415 (OR, and_expr, self._parse_expr(transform_m))
3417 def _parse_and_expr(self, transform_m):
3418 factor = self._parse_factor(transform_m)
3420 # Return 'factor' directly if we have a "single-operand" AND.
3421 # Otherwise, parse the right operand and make an AND node. This turns
3422 # A && B && C && D into (AND, A, (AND, B, (AND, C, D))).
3423 return factor if not self._check_token(_T_AND) else \
3424 (AND, factor, self._parse_and_expr(transform_m))
3426 def _parse_factor(self, transform_m):
3427 token = self._tokens[self._tokens_i]
3430 if token.__class__ is Symbol:
3431 # Plain symbol or relation
3433 if self._tokens[self._tokens_i] not in _RELATIONS:
3436 # For conditional expressions ('depends on <expr>',
3437 # '... if <expr>', etc.), m is rewritten to m && MODULES.
3438 if transform_m and token is self.m:
3439 return (AND, self.m, self.modules)
3445 # _T_EQUAL, _T_UNEQUAL, etc., deliberately have the same values as
3446 # EQUAL, UNEQUAL, etc., so we can just use the token directly
3448 return (self._tokens[self._tokens_i - 1], token,
3452 # token == _T_NOT == NOT
3453 return (token, self._parse_factor(transform_m))
3455 if token is _T_OPEN_PAREN:
3456 expr_parse = self._parse_expr(transform_m)
3457 if self._check_token(_T_CLOSE_PAREN):
3460 self._parse_error("malformed expression")
3463 # Caching and invalidation
3466 def _build_dep(self):
3467 # Populates the Symbol/Choice._dependents sets, which contain all other
3468 # items (symbols and choices) that immediately depend on the item in
3469 # the sense that changing the value of the item might affect the value
3470 # of the dependent items. This is used for caching/invalidation.
3472 # The calculated sets might be larger than necessary as we don't do any
3473 # complex analysis of the expressions.
3475 depend_on = _depend_on # Micro-optimization
3477 # Only calculate _dependents for defined symbols. Constant and
3478 # undefined symbols could theoretically be selected/implied, but it
3479 # wouldn't change their value, so it's not a true dependency.
3480 for sym in self.unique_defined_syms:
3481 # Symbols depend on the following:
3483 # The prompt conditions
3484 for node in sym.nodes:
3486 depend_on(sym, node.prompt[1])
3488 # The default values and their conditions
3489 for value, cond in sym.defaults:
3490 depend_on(sym, value)
3491 depend_on(sym, cond)
3493 # The reverse and weak reverse dependencies
3494 depend_on(sym, sym.rev_dep)
3495 depend_on(sym, sym.weak_rev_dep)
3497 # The ranges along with their conditions
3498 for low, high, cond in sym.ranges:
3500 depend_on(sym, high)
3501 depend_on(sym, cond)
3503 # The direct dependencies. This is usually redundant, as the direct
3504 # dependencies get propagated to properties, but it's needed to get
3505 # invalidation solid for 'imply', which only checks the direct
3506 # dependencies (even if there are no properties to propagate it
3508 depend_on(sym, sym.direct_dep)
3510 # In addition to the above, choice symbols depend on the choice
3511 # they're in, but that's handled automatically since the Choice is
3512 # propagated to the conditions of the properties before
3513 # _build_dep() runs.
3515 for choice in self.unique_choices:
3516 # Choices depend on the following:
3518 # The prompt conditions
3519 for node in choice.nodes:
3521 depend_on(choice, node.prompt[1])
3523 # The default symbol conditions
3524 for _, cond in choice.defaults:
3525 depend_on(choice, cond)
3527 def _add_choice_deps(self):
3528 # Choices also depend on the choice symbols themselves, because the
3529 # y-mode selection of the choice might change if a choice symbol's
3530 # visibility changes.
3532 # We add these dependencies separately after dependency loop detection.
3533 # The invalidation algorithm can handle the resulting
3534 # <choice symbol> <-> <choice> dependency loops, but they make loop
3535 # detection awkward.
3537 for choice in self.unique_choices:
3538 for sym in choice.syms:
3539 sym._dependents.add(choice)
3541 def _invalidate_all(self):
3542 # Undefined symbols never change value and don't need to be
3543 # invalidated, so we can just iterate over defined symbols.
3544 # Invalidating constant symbols would break things horribly.
3545 for sym in self.unique_defined_syms:
3548 for choice in self.unique_choices:
3549 choice._invalidate()
3552 # Post-parsing menu tree processing, including dependency propagation and
3553 # implicit submenu creation
3556 def _finalize_node(self, node, visible_if):
3557 # Finalizes a menu node and its children:
3559 # - Copies properties from menu nodes up to their contained
3562 # - Propagates dependencies from parent to child nodes
3564 # - Creates implicit menus (see kconfig-language.txt)
3566 # - Removes 'if' nodes
3568 # - Sets 'choice' types and registers choice symbols
3570 # menu_finalize() in the C implementation is similar.
3573 # The menu node to finalize. This node and its children will have
3574 # been finalized when the function returns, and any implicit menus
3575 # will have been created.
3578 # Dependencies from 'visible if' on parent menus. These are added to
3579 # the prompts of symbols and choices.
3581 if node.item.__class__ is Symbol:
3582 # Copy defaults, ranges, selects, and implies to the Symbol
3583 self._add_props_to_sym(node)
3585 # Find any items that should go in an implicit menu rooted at the
3588 while cur.next and _auto_menu_dep(node, cur.next):
3589 # This makes implicit submenu creation work recursively, with
3590 # implicit menus inside implicit menus
3591 self._finalize_node(cur.next, visible_if)
3596 # Found symbols that should go in an implicit submenu. Tilt
3598 node.list = node.next
3599 node.next = cur.next
3603 # The menu node is a choice, menu, or if. Finalize each child node.
3605 if node.item is MENU:
3606 visible_if = self._make_and(visible_if, node.visibility)
3608 # Propagate the menu node's dependencies to each child menu node.
3610 # This needs to go before the recursive _finalize_node() call so
3611 # that implicit submenu creation can look ahead at dependencies.
3612 self._propagate_deps(node, visible_if)
3614 # Finalize the children
3617 self._finalize_node(cur, visible_if)
3621 # node's children have been individually finalized. Do final steps
3622 # to finalize this "level" in the menu tree.
3626 # Empty choices (node.list None) are possible, so this needs to go
3628 if node.item.__class__ is Choice:
3629 # Add the node's non-node-specific properties to the choice, like
3630 # _add_props_to_sym() does
3632 choice.direct_dep = self._make_or(choice.direct_dep, node.dep)
3633 choice.defaults += node.defaults
3635 _finalize_choice(node)
3637 def _propagate_deps(self, node, visible_if):
3638 # Propagates 'node's dependencies to its child menu nodes
3640 # If the parent node holds a Choice, we use the Choice itself as the
3641 # parent dependency. This makes sense as the value (mode) of the choice
3642 # limits the visibility of the contained choice symbols. The C
3643 # implementation works the same way.
3645 # Due to the similar interface, Choice works as a drop-in replacement
3647 basedep = node.item if node.item.__class__ is Choice else node.dep
3651 dep = cur.dep = self._make_and(cur.dep, basedep)
3653 if cur.item.__class__ in _SYMBOL_CHOICE:
3654 # Propagate 'visible if' and dependencies to the prompt
3656 cur.prompt = (cur.prompt[0],
3659 self._make_and(visible_if, dep)))
3661 # Propagate dependencies to defaults
3663 cur.defaults = [(default, self._make_and(cond, dep))
3664 for default, cond in cur.defaults]
3666 # Propagate dependencies to ranges
3668 cur.ranges = [(low, high, self._make_and(cond, dep))
3669 for low, high, cond in cur.ranges]
3671 # Propagate dependencies to selects
3673 cur.selects = [(target, self._make_and(cond, dep))
3674 for target, cond in cur.selects]
3676 # Propagate dependencies to implies
3678 cur.implies = [(target, self._make_and(cond, dep))
3679 for target, cond in cur.implies]
3681 elif cur.prompt: # Not a symbol/choice
3682 # Propagate dependencies to the prompt. 'visible if' is only
3683 # propagated to symbols/choices.
3684 cur.prompt = (cur.prompt[0],
3685 self._make_and(cur.prompt[1], dep))
3689 def _add_props_to_sym(self, node):
3690 # Copies properties from the menu node 'node' up to its contained
3691 # symbol, and adds (weak) reverse dependencies to selected/implied
3694 # This can't be rolled into _propagate_deps(), because that function
3695 # traverses the menu tree roughly breadth-first, meaning properties on
3696 # symbols defined in multiple locations could end up in the wrong
3701 # See the Symbol class docstring
3702 sym.direct_dep = self._make_or(sym.direct_dep, node.dep)
3704 sym.defaults += node.defaults
3705 sym.ranges += node.ranges
3706 sym.selects += node.selects
3707 sym.implies += node.implies
3709 # Modify the reverse dependencies of the selected symbol
3710 for target, cond in node.selects:
3711 target.rev_dep = self._make_or(
3713 self._make_and(sym, cond))
3715 # Modify the weak reverse dependencies of the implied
3717 for target, cond in node.implies:
3718 target.weak_rev_dep = self._make_or(
3719 target.weak_rev_dep,
3720 self._make_and(sym, cond))
3726 def _check_sym_sanity(self):
3727 # Checks various symbol properties that are handiest to check after
3728 # parsing. Only generates errors and warnings.
3730 def num_ok(sym, type_):
3731 # Returns True if the (possibly constant) symbol 'sym' is valid as a value
3732 # for a symbol of type type_ (INT or HEX)
3734 # 'not sym.nodes' implies a constant or undefined symbol, e.g. a plain
3737 return _is_base_n(sym.name, _TYPE_TO_BASE[type_])
3739 return sym.orig_type is type_
3741 for sym in self.unique_defined_syms:
3742 if sym.orig_type in _BOOL_TRISTATE:
3743 # A helper function could be factored out here, but keep it
3744 # speedy/straightforward
3746 for target_sym, _ in sym.selects:
3747 if target_sym.orig_type not in _BOOL_TRISTATE_UNKNOWN:
3748 self._warn("{} selects the {} symbol {}, which is not "
3750 .format(sym.name_and_loc,
3751 TYPE_TO_STR[target_sym.orig_type],
3752 target_sym.name_and_loc))
3754 for target_sym, _ in sym.implies:
3755 if target_sym.orig_type not in _BOOL_TRISTATE_UNKNOWN:
3756 self._warn("{} implies the {} symbol {}, which is not "
3758 .format(sym.name_and_loc,
3759 TYPE_TO_STR[target_sym.orig_type],
3760 target_sym.name_and_loc))
3762 elif sym.orig_type: # STRING/INT/HEX
3763 for default, _ in sym.defaults:
3764 if default.__class__ is not Symbol:
3766 "the {} symbol {} has a malformed default {} -- "
3767 "expected a single symbol"
3768 .format(TYPE_TO_STR[sym.orig_type],
3769 sym.name_and_loc, expr_str(default)))
3771 if sym.orig_type is STRING:
3772 if not default.is_constant and not default.nodes and \
3773 not default.name.isupper():
3774 # 'default foo' on a string symbol could be either a symbol
3775 # reference or someone leaving out the quotes. Guess that
3776 # the quotes were left out if 'foo' isn't all-uppercase
3777 # (and no symbol named 'foo' exists).
3778 self._warn("style: quotes recommended around "
3779 "default value for string symbol "
3782 elif not num_ok(default, sym.orig_type): # INT/HEX
3783 self._warn("the {0} symbol {1} has a non-{0} default {2}"
3784 .format(TYPE_TO_STR[sym.orig_type],
3786 default.name_and_loc))
3788 if sym.selects or sym.implies:
3789 self._warn("the {} symbol {} has selects or implies"
3790 .format(TYPE_TO_STR[sym.orig_type],
3794 self._warn("{} defined without a type"
3795 .format(sym.name_and_loc))
3799 if sym.orig_type not in _INT_HEX:
3801 "the {} symbol {} has ranges, but is not int or hex"
3802 .format(TYPE_TO_STR[sym.orig_type],
3805 for low, high, _ in sym.ranges:
3806 if not num_ok(low, sym.orig_type) or \
3807 not num_ok(high, sym.orig_type):
3809 self._warn("the {0} symbol {1} has a non-{0} "
3811 .format(TYPE_TO_STR[sym.orig_type],
3816 def _check_choice_sanity(self):
3817 # Checks various choice properties that are handiest to check after
3818 # parsing. Only generates errors and warnings.
3820 def warn_select_imply(sym, expr, expr_type):
3821 msg = "the choice symbol {} is {} by the following symbols, but " \
3822 "select/imply has no effect on choice symbols" \
3823 .format(sym.name_and_loc, expr_type)
3826 for si in split_expr(expr, OR):
3827 msg += "\n - " + split_expr(si, AND)[0].name_and_loc
3831 for choice in self.unique_choices:
3832 if choice.orig_type not in _BOOL_TRISTATE:
3833 self._warn("{} defined with type {}"
3834 .format(choice.name_and_loc,
3835 TYPE_TO_STR[choice.orig_type]))
3837 for node in choice.nodes:
3841 self._warn(choice.name_and_loc + " defined without a prompt")
3843 for default, _ in choice.defaults:
3844 if default.__class__ is not Symbol:
3846 "{} has a malformed default {}"
3847 .format(choice.name_and_loc, expr_str(default)))
3849 if default.choice is not choice:
3850 self._warn("the default selection {} of {} is not "
3851 "contained in the choice"
3852 .format(default.name_and_loc,
3853 choice.name_and_loc))
3855 for sym in choice.syms:
3857 self._warn("default on the choice symbol {} will have "
3858 "no effect, as defaults do not affect choice "
3859 "symbols".format(sym.name_and_loc))
3861 if sym.rev_dep is not sym.kconfig.n:
3862 warn_select_imply(sym, sym.rev_dep, "selected")
3864 if sym.weak_rev_dep is not sym.kconfig.n:
3865 warn_select_imply(sym, sym.weak_rev_dep, "implied")
3867 for node in sym.nodes:
3868 if node.parent.item is choice:
3870 self._warn("the choice symbol {} has no prompt"
3871 .format(sym.name_and_loc))
3874 self._warn("the choice symbol {} is defined with a "
3875 "prompt outside the choice"
3876 .format(sym.name_and_loc))
3878 def _parse_error(self, msg):
3879 raise KconfigError("{}error: couldn't parse '{}': {}".format(
3880 "" if self.filename is None else
3881 "{}:{}: ".format(self.filename, self.linenr),
3882 self._line.strip(), msg))
3884 def _trailing_tokens_error(self):
3885 self._parse_error("extra tokens at end of line")
3887 def _open(self, filename, mode):
3890 # - Enable universal newlines mode on Python 2 to ease
3891 # interoperability between Linux and Windows. It's already the
3892 # default on Python 3.
3894 # The "U" flag would currently work for both Python 2 and 3, but it's
3895 # deprecated on Python 3, so play it future-safe.
3897 # io.open() defaults to universal newlines on Python 2 (and is an
3898 # alias for open() on Python 3), but it returns 'unicode' strings and
3899 # slows things down:
3901 # Parsing x86 Kconfigs on Python 2
3903 # with open(..., "rU"):
3915 # There's no appreciable performance difference between "r" and
3916 # "rU" for parsing performance on Python 2.
3918 # - For Python 3, force the encoding. Forcing the encoding on Python 2
3919 # turns strings into Unicode strings, which gets messy. Python 2
3920 # doesn't decode regular strings anyway.
3921 return open(filename, "rU" if mode == "r" else mode) if _IS_PY2 else \
3922 open(filename, mode, encoding=self._encoding)
3924 def _check_undef_syms(self):
3925 # Prints warnings for all references to undefined symbols within the
3929 # Returns True if the string 's' looks like a number.
3931 # Internally, all operands in Kconfig are symbols, only undefined symbols
3932 # (which numbers usually are) get their name as their value.
3934 # Only hex numbers that start with 0x/0X are classified as numbers.
3935 # Otherwise, symbols whose names happen to contain only the letters A-F
3936 # would trigger false positives.
3941 if not s.startswith(("0x", "0X")):
3951 for sym in (self.syms.viewvalues if _IS_PY2 else self.syms.values)():
3952 # - sym.nodes empty means the symbol is undefined (has no
3953 # definition locations)
3955 # - Due to Kconfig internals, numbers show up as undefined Kconfig
3956 # symbols, but shouldn't be flagged
3958 # - The MODULES symbol always exists
3959 if not sym.nodes and not is_num(sym.name) and \
3960 sym.name != "MODULES":
3962 msg = "undefined symbol {}:".format(sym.name)
3963 for node in self.node_iter():
3964 if sym in node.referenced:
3965 msg += "\n\n- Referenced at {}:{}:\n\n{}" \
3966 .format(node.filename, node.linenr, node)
3969 def _warn(self, msg, filename=None, linenr=None):
3970 # For printing general warnings
3975 msg = "warning: " + msg
3976 if filename is not None:
3977 msg = "{}:{}: {}".format(filename, linenr, msg)
3979 self.warnings.append(msg)
3980 if self.warn_to_stderr:
3981 sys.stderr.write(msg + "\n")
3984 class Symbol(object):
3986 Represents a configuration symbol:
3991 The following attributes are available. They should be viewed as read-only,
3992 and some are implemented through @property magic (but are still efficient
3993 to access due to internal caching).
3995 Note: Prompts, help texts, and locations are stored in the Symbol's
3996 MenuNode(s) rather than in the Symbol itself. Check the MenuNode class and
3997 the Symbol.nodes attribute. This organization matches the C tools.
4000 The name of the symbol, e.g. "FOO" for 'config FOO'.
4003 The type of the symbol. One of BOOL, TRISTATE, STRING, INT, HEX, UNKNOWN.
4004 UNKNOWN is for undefined symbols, (non-special) constant symbols, and
4005 symbols defined without a type.
4007 When running without modules (MODULES having the value n), TRISTATE
4008 symbols magically change type to BOOL. This also happens for symbols
4009 within choices in "y" mode. This matches the C tools, and makes sense for
4010 menuconfig-like functionality.
4013 The type as given in the Kconfig file, without any magic applied. Used
4014 when printing the symbol.
4017 The tristate value of the symbol as an integer. One of 0, 1, 2,
4018 representing n, m, y. Always 0 (n) for non-bool/tristate symbols.
4020 This is the symbol value that's used outside of relation expressions
4021 (A, !A, A && B, A || B).
4024 The value of the symbol as a string. Gives the value for string/int/hex
4025 symbols. For bool/tristate symbols, gives "n", "m", or "y".
4027 This is the symbol value that's used in relational expressions
4028 (A = B, A != B, etc.)
4030 Gotcha: For int/hex symbols, the exact format of the value is often
4031 preserved (e.g. when writing a .config file), hence why you can't get it
4032 directly as an int. Do int(int_sym.str_value) or
4033 int(hex_sym.str_value, 16) to get the integer value.
4036 The user value of the symbol. None if no user value has been assigned
4037 (via Kconfig.load_config() or Symbol.set_value()).
4039 Holds 0, 1, or 2 for bool/tristate symbols, and a string for the other
4042 WARNING: Do not assign directly to this. It will break things. Use
4046 A tuple containing the tristate user values that can currently be
4047 assigned to the symbol (that would be respected), ordered from lowest (0,
4048 representing n) to highest (2, representing y). This corresponds to the
4049 selections available in the menuconfig interface. The set of assignable
4050 values is calculated from the symbol's visibility and selects/implies.
4052 Returns the empty set for non-bool/tristate symbols and for symbols with
4053 visibility n. The other possible values are (0, 2), (0, 1, 2), (1, 2),
4054 (1,), and (2,). A (1,) or (2,) result means the symbol is visible but
4055 "locked" to m or y through a select, perhaps in combination with the
4056 visibility. menuconfig represents this as -M- and -*-, respectively.
4058 For string/hex/int symbols, check if Symbol.visibility is non-0 (non-n)
4059 instead to determine if the value can be changed.
4061 Some handy 'assignable' idioms:
4063 # Is 'sym' an assignable (visible) bool/tristate symbol?
4065 # What's the highest value it can be assigned? [-1] in Python
4066 # gives the last element.
4067 sym_high = sym.assignable[-1]
4070 sym_low = sym.assignable[0]
4072 # Can the symbol be set to at least m?
4073 if sym.assignable[-1] >= 1:
4076 # Can the symbol be set to m?
4077 if 1 in sym.assignable:
4081 The visibility of the symbol. One of 0, 1, 2, representing n, m, y. See
4082 the module documentation for an overview of symbol values and visibility.
4085 The .config assignment string that would get written out for the symbol
4086 by Kconfig.write_config(). Returns the empty string if no .config
4087 assignment would get written out.
4089 In general, visible symbols, symbols with (active) defaults, and selected
4090 symbols get written out. This includes all non-n-valued bool/tristate
4091 symbols, and all visible string/int/hex symbols.
4093 Symbols with the (no longer needed) 'option env=...' option generate no
4094 configuration output, and neither does the special
4095 'option defconfig_list' symbol.
4097 Tip: This field is useful when generating custom configuration output,
4098 even for non-.config-like formats. To write just the symbols that would
4099 get written out to .config files, do this:
4101 if sym.config_string:
4102 *Write symbol, e.g. by looking sym.str_value*
4104 This is a superset of the symbols written out by write_autoconf().
4105 That function skips all n-valued symbols.
4107 There usually won't be any great harm in just writing all symbols either,
4108 though you might get some special symbols and possibly some "redundant"
4109 n-valued symbol entries in there.
4114 "MY_SYMBOL (defined at foo/Kconfig:12, bar/Kconfig:14)"
4116 , giving the name of the symbol and its definition location(s).
4118 If the symbol is undefined, the location is given as "(undefined)".
4121 A list of MenuNodes for this symbol. Will contain a single MenuNode for
4122 most symbols. Undefined and constant symbols have an empty nodes list.
4123 Symbols defined in multiple locations get one node for each location.
4126 Holds the parent Choice for choice symbols, and None for non-choice
4127 symbols. Doubles as a flag for whether a symbol is a choice symbol.
4130 List of (default, cond) tuples for the symbol's 'default' properties. For
4131 example, 'default A && B if C || D' is represented as
4132 ((AND, A, B), (OR, C, D)). If no condition was given, 'cond' is
4135 Note that 'depends on' and parent dependencies are propagated to
4136 'default' conditions.
4139 List of (symbol, cond) tuples for the symbol's 'select' properties. For
4140 example, 'select A if B && C' is represented as (A, (AND, B, C)). If no
4141 condition was given, 'cond' is self.kconfig.y.
4143 Note that 'depends on' and parent dependencies are propagated to 'select'
4147 Like 'selects', for imply.
4150 List of (low, high, cond) tuples for the symbol's 'range' properties. For
4151 example, 'range 1 2 if A' is represented as (1, 2, A). If there is no
4152 condition, 'cond' is self.kconfig.y.
4154 Note that 'depends on' and parent dependencies are propagated to 'range'
4157 Gotcha: 1 and 2 above will be represented as (undefined) Symbols rather
4158 than plain integers. Undefined symbols get their name as their string
4159 value, so this works out. The C tools work the same way.
4165 See the corresponding attributes on the MenuNode class.
4168 Reverse dependency expression from other symbols selecting this symbol.
4169 Multiple selections get ORed together. A condition on a select is ANDed
4170 with the selecting symbol.
4172 For example, if A has 'select FOO' and B has 'select FOO if C', then
4173 FOO's rev_dep will be (OR, A, (AND, B, C)).
4176 Like rev_dep, for imply.
4179 The direct ('depends on') dependencies for the symbol, or self.kconfig.y
4180 if there are no direct dependencies.
4182 This attribute includes any dependencies from surrounding menus and ifs.
4183 Those get propagated to the direct dependencies, and the resulting direct
4184 dependencies in turn get propagated to the conditions of all properties.
4186 If the symbol is defined in multiple locations, the dependencies from the
4187 different locations get ORed together.
4190 A set() with all symbols and choices referenced in the properties and
4191 property conditions of the symbol.
4193 Also includes dependencies from surrounding menus and ifs, because those
4194 get propagated to the symbol (see the 'Intro to symbol values' section in
4195 the module docstring).
4197 Choices appear in the dependencies of choice symbols.
4199 For the following definitions, only B and not C appears in A's
4200 'referenced'. To get transitive references, you'll have to recursively
4201 expand 'references' until no new items appear.
4214 See the Symbol.direct_dep attribute if you're only interested in the
4215 direct dependencies of the symbol (its 'depends on'). You can extract the
4216 symbols in it with the global expr_items() function.
4219 If the Symbol has an 'option env="FOO"' option, this contains the name
4220 ("FOO") of the environment variable. None for symbols without no
4223 'option env="FOO"' acts like a 'default' property whose value is the
4226 Symbols with 'option env' are never written out to .config files, even if
4227 they are visible. env_var corresponds to a flag called SYMBOL_AUTO in the
4231 True if the symbol has 'option allnoconfig_y' set on it. This has no
4232 effect internally (except when printing symbols), but can be checked by
4236 True if the symbol is a constant (quoted) symbol.
4239 The Kconfig instance this symbol is from.
4242 "_cached_assignable",
4276 See the class documentation.
4278 if self.orig_type is TRISTATE and \
4279 (self.choice and self.choice.tri_value == 2 or
4280 not self.kconfig.modules.tri_value):
4284 return self.orig_type
4287 def str_value(self):
4289 See the class documentation.
4291 if self._cached_str_val is not None:
4292 return self._cached_str_val
4294 if self.orig_type in _BOOL_TRISTATE:
4295 # Also calculates the visibility, so invalidation safe
4296 self._cached_str_val = TRI_TO_STR[self.tri_value]
4297 return self._cached_str_val
4299 # As a quirk of Kconfig, undefined symbols get their name as their
4300 # string value. This is why things like "FOO = bar" work for seeing if
4301 # FOO has the value "bar".
4302 if not self.orig_type: # UNKNOWN
4303 self._cached_str_val = self.name
4307 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4308 # function call (property magic)
4309 vis = self.visibility
4311 self._write_to_conf = (vis != 0)
4313 if self.orig_type in _INT_HEX:
4314 # The C implementation checks the user value against the range in a
4315 # separate code path (post-processing after loading a .config).
4316 # Checking all values here instead makes more sense for us. It
4317 # requires that we check for a range first.
4319 base = _TYPE_TO_BASE[self.orig_type]
4321 # Check if a range is in effect
4322 for low_expr, high_expr, cond in self.ranges:
4323 if expr_value(cond):
4324 has_active_range = True
4326 # The zeros are from the C implementation running strtoll()
4328 low = int(low_expr.str_value, base) if \
4329 _is_base_n(low_expr.str_value, base) else 0
4330 high = int(high_expr.str_value, base) if \
4331 _is_base_n(high_expr.str_value, base) else 0
4335 has_active_range = False
4337 # Defaults are used if the symbol is invisible, lacks a user value,
4338 # or has an out-of-range user value
4341 if vis and self.user_value:
4342 user_val = int(self.user_value, base)
4343 if has_active_range and not low <= user_val <= high:
4344 num2str = str if base == 10 else hex
4346 "user value {} on the {} symbol {} ignored due to "
4347 "being outside the active range ([{}, {}]) -- falling "
4349 .format(num2str(user_val), TYPE_TO_STR[self.orig_type],
4351 num2str(low), num2str(high)))
4353 # If the user value is well-formed and satisfies range
4354 # contraints, it is stored in exactly the same form as
4355 # specified in the assignment (with or without "0x", etc.)
4356 val = self.user_value
4357 use_defaults = False
4360 # No user value or invalid user value. Look at defaults.
4362 # Used to implement the warning below
4365 for sym, cond in self.defaults:
4366 if expr_value(cond):
4367 has_default = self._write_to_conf = True
4371 if _is_base_n(val, base):
4372 val_num = int(val, base)
4374 val_num = 0 # strtoll() on empty string
4378 val_num = 0 # strtoll() on empty string
4380 # This clamping procedure runs even if there's no default
4381 if has_active_range:
4385 elif val_num > high:
4388 if clamp is not None:
4389 # The value is rewritten to a standard form if it is
4392 if self.orig_type is INT else \
4396 num2str = str if base == 10 else hex
4398 "default value {} on {} clamped to {} due to "
4399 "being outside the active range ([{}, {}])"
4400 .format(val_num, self.name_and_loc,
4401 num2str(clamp), num2str(low),
4404 elif self.orig_type is STRING:
4405 if vis and self.user_value is not None:
4406 # If the symbol is visible and has a user value, use that
4407 val = self.user_value
4409 # Otherwise, look at defaults
4410 for sym, cond in self.defaults:
4411 if expr_value(cond):
4413 self._write_to_conf = True
4416 # env_var corresponds to SYMBOL_AUTO in the C implementation, and is
4417 # also set on the defconfig_list symbol there. Test for the
4418 # defconfig_list symbol explicitly instead here, to avoid a nonsensical
4419 # env_var setting and the defconfig_list symbol being printed
4420 # incorrectly. This code is pretty cold anyway.
4421 if self.env_var is not None or self is self.kconfig.defconfig_list:
4422 self._write_to_conf = False
4424 self._cached_str_val = val
4428 def tri_value(self):
4430 See the class documentation.
4432 if self._cached_tri_val is not None:
4433 return self._cached_tri_val
4435 if self.orig_type not in _BOOL_TRISTATE:
4436 if self.orig_type: # != UNKNOWN
4437 # Would take some work to give the location here
4439 "The {} symbol {} is being evaluated in a logical context "
4440 "somewhere. It will always evaluate to n."
4441 .format(TYPE_TO_STR[self.orig_type], self.name_and_loc))
4443 self._cached_tri_val = 0
4446 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4447 # function call (property magic)
4448 vis = self.visibility
4449 self._write_to_conf = (vis != 0)
4456 if vis and self.user_value is not None:
4457 # If the symbol is visible and has a user value, use that
4458 val = min(self.user_value, vis)
4461 # Otherwise, look at defaults and weak reverse dependencies
4464 for default, cond in self.defaults:
4465 dep_val = expr_value(cond)
4467 val = min(expr_value(default), dep_val)
4469 self._write_to_conf = True
4472 # Weak reverse dependencies are only considered if our
4473 # direct dependencies are met
4474 dep_val = expr_value(self.weak_rev_dep)
4475 if dep_val and expr_value(self.direct_dep):
4476 val = max(dep_val, val)
4477 self._write_to_conf = True
4479 # Reverse (select-related) dependencies take precedence
4480 dep_val = expr_value(self.rev_dep)
4482 if expr_value(self.direct_dep) < dep_val:
4483 self._warn_select_unsatisfied_deps()
4485 val = max(dep_val, val)
4486 self._write_to_conf = True
4488 # m is promoted to y for (1) bool symbols and (2) symbols with a
4489 # weak_rev_dep (from imply) of y
4491 (self.type is BOOL or expr_value(self.weak_rev_dep) == 2):
4495 # Visible choice symbol in y-mode choice. The choice mode limits
4496 # the visibility of choice symbols, so it's sufficient to just
4497 # check the visibility of the choice symbols themselves.
4498 val = 2 if self.choice.selection is self else 0
4500 elif vis and self.user_value:
4501 # Visible choice symbol in m-mode choice, with set non-0 user value
4504 self._cached_tri_val = val
4508 def assignable(self):
4510 See the class documentation.
4512 if self._cached_assignable is None:
4513 self._cached_assignable = self._assignable()
4514 return self._cached_assignable
4517 def visibility(self):
4519 See the class documentation.
4521 if self._cached_vis is None:
4522 self._cached_vis = _visibility(self)
4523 return self._cached_vis
4526 def config_string(self):
4528 See the class documentation.
4530 # _write_to_conf is determined when the value is calculated. This is a
4531 # hidden function call due to property magic.
4532 val = self.str_value
4533 if not self._write_to_conf:
4536 if self.orig_type in _BOOL_TRISTATE:
4537 return "{}{}={}\n" \
4538 .format(self.kconfig.config_prefix, self.name, val) \
4539 if val != "n" else \
4540 "# {}{} is not set\n" \
4541 .format(self.kconfig.config_prefix, self.name)
4543 if self.orig_type in _INT_HEX:
4544 return "{}{}={}\n" \
4545 .format(self.kconfig.config_prefix, self.name, val)
4547 # sym.orig_type is STRING
4548 return '{}{}="{}"\n' \
4549 .format(self.kconfig.config_prefix, self.name, escape(val))
4552 def name_and_loc(self):
4554 See the class documentation.
4556 return self.name + " " + _locs(self)
4558 def set_value(self, value):
4560 Sets the user value of the symbol.
4562 Equal in effect to assigning the value to the symbol within a .config
4563 file. For bool and tristate symbols, use the 'assignable' attribute to
4564 check which values can currently be assigned. Setting values outside
4565 'assignable' will cause Symbol.user_value to differ from
4566 Symbol.str/tri_value (be truncated down or up).
4568 Setting a choice symbol to 2 (y) sets Choice.user_selection to the
4569 choice symbol in addition to setting Symbol.user_value.
4570 Choice.user_selection is considered when the choice is in y mode (the
4573 Other symbols that depend (possibly indirectly) on this symbol are
4574 automatically recalculated to reflect the assigned value.
4577 The user value to give to the symbol. For bool and tristate symbols,
4578 n/m/y can be specified either as 0/1/2 (the usual format for tristate
4579 values in Kconfiglib) or as one of the strings "n", "m", or "y". For
4580 other symbol types, pass a string.
4582 Note that the value for an int/hex symbol is passed as a string, e.g.
4583 "123" or "0x0123". The format of this string is preserved in the
4586 Values that are invalid for the type (such as "foo" or 1 (m) for a
4587 BOOL or "0x123" for an INT) are ignored and won't be stored in
4588 Symbol.user_value. Kconfiglib will print a warning by default for
4589 invalid assignments, and set_value() will return False.
4591 Returns True if the value is valid for the type of the symbol, and
4592 False otherwise. This only looks at the form of the value. For BOOL and
4593 TRISTATE symbols, check the Symbol.assignable attribute to see what
4594 values are currently in range and would actually be reflected in the
4595 value of the symbol. For other symbol types, check whether the
4596 visibility is non-n.
4598 if self.orig_type in _BOOL_TRISTATE and value in STR_TO_TRI:
4599 value = STR_TO_TRI[value]
4601 # If the new user value matches the old, nothing changes, and we can
4602 # avoid invalidating cached values.
4604 # This optimization is skipped for choice symbols: Setting a choice
4605 # symbol's user value to y might change the state of the choice, so it
4606 # wouldn't be safe (symbol user values always match the values set in a
4607 # .config file or via set_value(), and are never implicitly updated).
4608 if value == self.user_value and not self.choice:
4609 self._was_set = True
4612 # Check if the value is valid for our type
4613 if not (self.orig_type is BOOL and value in (2, 0) or
4614 self.orig_type is TRISTATE and value in TRI_TO_STR or
4615 value.__class__ is str and
4616 (self.orig_type is STRING or
4617 self.orig_type is INT and _is_base_n(value, 10) or
4618 self.orig_type is HEX and _is_base_n(value, 16)
4619 and int(value, 16) >= 0)):
4621 # Display tristate values as n, m, y in the warning
4623 "the value {} is invalid for {}, which has type {} -- "
4624 "assignment ignored"
4625 .format(TRI_TO_STR[value] if value in TRI_TO_STR else
4626 "'{}'".format(value),
4627 self.name_and_loc, TYPE_TO_STR[self.orig_type]))
4631 self.user_value = value
4632 self._was_set = True
4634 if self.choice and value == 2:
4635 # Setting a choice symbol to y makes it the user selection of the
4636 # choice. Like for symbol user values, the user selection is not
4637 # guaranteed to match the actual selection of the choice, as
4638 # dependencies come into play.
4639 self.choice.user_selection = self
4640 self.choice._was_set = True
4641 self.choice._rec_invalidate()
4643 self._rec_invalidate_if_has_prompt()
4647 def unset_value(self):
4649 Removes any user value from the symbol, as if the symbol had never
4650 gotten a user value via Kconfig.load_config() or Symbol.set_value().
4652 if self.user_value is not None:
4653 self.user_value = None
4654 self._rec_invalidate_if_has_prompt()
4657 def referenced(self):
4659 See the class documentation.
4661 return {item for node in self.nodes for item in node.referenced}
4664 def orig_defaults(self):
4666 See the class documentation.
4668 return [d for node in self.nodes for d in node.orig_defaults]
4671 def orig_selects(self):
4673 See the class documentation.
4675 return [s for node in self.nodes for s in node.orig_selects]
4678 def orig_implies(self):
4680 See the class documentation.
4682 return [i for node in self.nodes for i in node.orig_implies]
4685 def orig_ranges(self):
4687 See the class documentation.
4689 return [r for node in self.nodes for r in node.orig_ranges]
4693 Returns a string with information about the symbol (including its name,
4694 value, visibility, and location(s)) when it is evaluated on e.g. the
4695 interactive Python prompt.
4697 fields = ["symbol " + self.name, TYPE_TO_STR[self.type]]
4700 for node in self.nodes:
4702 add('"{}"'.format(node.prompt[0]))
4704 # Only add quotes for non-bool/tristate symbols
4705 add("value " + (self.str_value if self.orig_type in _BOOL_TRISTATE
4706 else '"{}"'.format(self.str_value)))
4708 if not self.is_constant:
4709 # These aren't helpful to show for constant symbols
4711 if self.user_value is not None:
4712 # Only add quotes for non-bool/tristate symbols
4713 add("user value " + (TRI_TO_STR[self.user_value]
4714 if self.orig_type in _BOOL_TRISTATE
4715 else '"{}"'.format(self.user_value)))
4717 add("visibility " + TRI_TO_STR[self.visibility])
4720 add("choice symbol")
4722 if self.is_allnoconfig_y:
4723 add("allnoconfig_y")
4725 if self is self.kconfig.defconfig_list:
4726 add("is the defconfig_list symbol")
4728 if self.env_var is not None:
4729 add("from environment variable " + self.env_var)
4731 if self is self.kconfig.modules:
4732 add("is the modules symbol")
4734 add("direct deps " + TRI_TO_STR[expr_value(self.direct_dep)])
4737 for node in self.nodes:
4738 add("{}:{}".format(node.filename, node.linenr))
4740 add("constant" if self.is_constant else "undefined")
4742 return "<{}>".format(", ".join(fields))
4746 Returns a string representation of the symbol when it is printed.
4747 Matches the Kconfig format, with any parent dependencies propagated to
4748 the 'depends on' condition.
4750 The string is constructed by joining the strings returned by
4751 MenuNode.__str__() for each of the symbol's menu nodes, so symbols
4752 defined in multiple locations will return a string with all
4755 The returned string does not end in a newline. An empty string is
4756 returned for undefined and constant symbols.
4758 return self.custom_str(standard_sc_expr_str)
4760 def custom_str(self, sc_expr_str_fn):
4762 Works like Symbol.__str__(), but allows a custom format to be used for
4763 all symbol/choice references. See expr_str().
4765 return "\n\n".join(node.custom_str(sc_expr_str_fn)
4766 for node in self.nodes)
4774 Symbol constructor -- not intended to be called directly by Kconfiglib
4777 # These attributes are always set on the instance from outside and
4778 # don't need defaults:
4787 # - _visited is used during tree iteration and dep. loop detection
4788 self.orig_type = self._visited = 0
4800 self._cached_str_val = self._cached_tri_val = self._cached_vis = \
4801 self._cached_assignable = None
4803 # _write_to_conf is calculated along with the value. If True, the
4804 # Symbol gets a .config entry.
4806 self.is_allnoconfig_y = \
4808 self._write_to_conf = False
4810 # See Kconfig._build_dep()
4811 self._dependents = set()
4813 def _assignable(self):
4814 # Worker function for the 'assignable' attribute
4816 if self.orig_type not in _BOOL_TRISTATE:
4819 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4820 # function call (property magic)
4821 vis = self.visibility
4825 rev_dep_val = expr_value(self.rev_dep)
4832 if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
4836 if rev_dep_val == 2:
4841 if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
4847 # Must be a tristate here, because bool m visibility gets promoted to y
4850 return (0, 1) if expr_value(self.weak_rev_dep) != 2 else (0, 2)
4852 if rev_dep_val == 2:
4855 # vis == rev_dep_val == 1
4859 def _invalidate(self):
4860 # Marks the symbol as needing to be recalculated
4862 self._cached_str_val = self._cached_tri_val = self._cached_vis = \
4863 self._cached_assignable = None
4865 def _rec_invalidate(self):
4866 # Invalidates the symbol and all items that (possibly) depend on it
4868 if self is self.kconfig.modules:
4869 # Invalidating MODULES has wide-ranging effects
4870 self.kconfig._invalidate_all()
4874 for item in self._dependents:
4875 # _cached_vis doubles as a flag that tells us whether 'item'
4876 # has cached values, because it's calculated as a side effect
4877 # of calculating all other (non-constant) cached values.
4879 # If item._cached_vis is None, it means there can't be cached
4880 # values on other items that depend on 'item', because if there
4881 # were, some value on 'item' would have been calculated and
4882 # item._cached_vis set as a side effect. It's therefore safe to
4883 # stop the invalidation at symbols with _cached_vis None.
4885 # This approach massively speeds up scripts that set a lot of
4886 # values, vs simply invalidating all possibly dependent symbols
4887 # (even when you already have a list of all the dependent
4888 # symbols, because some symbols get huge dependency trees).
4890 # This gracefully handles dependency loops too, which is nice
4891 # for choices, where the choice depends on the choice symbols
4893 if item._cached_vis is not None:
4894 item._rec_invalidate()
4896 def _rec_invalidate_if_has_prompt(self):
4897 # Invalidates the symbol and its dependent symbols, but only if the
4898 # symbol has a prompt. User values never have an effect on promptless
4899 # symbols, so we skip invalidation for them as an optimization.
4901 # This also prevents constant (quoted) symbols from being invalidated
4902 # if set_value() is called on them, which would make them lose their
4903 # value and break things.
4905 # Prints a warning if the symbol has no prompt. In some contexts (e.g.
4906 # when loading a .config files) assignments to promptless symbols are
4907 # normal and expected, so the warning can be disabled.
4909 for node in self.nodes:
4911 self._rec_invalidate()
4914 if self.kconfig._warn_assign_no_prompt:
4915 self.kconfig._warn(self.name_and_loc + " has no prompt, meaning "
4916 "user values have no effect on it")
4918 def _str_default(self):
4919 # write_min_config() helper function. Returns the value the symbol
4920 # would get from defaults if it didn't have a user value. Uses exactly
4921 # the same algorithm as the C implementation (though a bit cleaned up),
4922 # for compatibility.
4924 if self.orig_type in _BOOL_TRISTATE:
4927 # Defaults, selects, and implies do not affect choice symbols
4929 for default, cond in self.defaults:
4930 cond_val = expr_value(cond)
4932 val = min(expr_value(default), cond_val)
4935 val = max(expr_value(self.rev_dep),
4936 expr_value(self.weak_rev_dep),
4939 # Transpose mod to yes if type is bool (possibly due to modules
4941 if val == 1 and self.type is BOOL:
4944 return TRI_TO_STR[val]
4946 if self.orig_type: # STRING/INT/HEX
4947 for default, cond in self.defaults:
4948 if expr_value(cond):
4949 return default.str_value
4953 def _warn_select_unsatisfied_deps(self):
4954 # Helper for printing an informative warning when a symbol with
4955 # unsatisfied direct dependencies (dependencies from 'depends on', ifs,
4956 # and menus) is selected by some other symbol. Also warn if a symbol
4957 # whose direct dependencies evaluate to m is selected to y.
4959 msg = "{} has direct dependencies {} with value {}, but is " \
4960 "currently being {}-selected by the following symbols:" \
4961 .format(self.name_and_loc, expr_str(self.direct_dep),
4962 TRI_TO_STR[expr_value(self.direct_dep)],
4963 TRI_TO_STR[expr_value(self.rev_dep)])
4965 # The reverse dependencies from each select are ORed together
4966 for select in split_expr(self.rev_dep, OR):
4967 if expr_value(select) <= expr_value(self.direct_dep):
4968 # Only include selects that exceed the direct dependencies
4971 # - 'select A if B' turns into A && B
4972 # - 'select A' just turns into A
4974 # In both cases, we can split on AND and pick the first operand
4975 selecting_sym = split_expr(select, AND)[0]
4977 msg += "\n - {}, with value {}, direct dependencies {} " \
4979 .format(selecting_sym.name_and_loc,
4980 selecting_sym.str_value,
4981 expr_str(selecting_sym.direct_dep),
4982 TRI_TO_STR[expr_value(selecting_sym.direct_dep)])
4984 if select.__class__ is tuple:
4985 msg += ", and select condition {} (value: {})" \
4986 .format(expr_str(select[2]),
4987 TRI_TO_STR[expr_value(select[2])])
4989 self.kconfig._warn(msg)
4992 class Choice(object):
4994 Represents a choice statement:
5000 The following attributes are available on Choice instances. They should be
5001 treated as read-only, and some are implemented through @property magic (but
5002 are still efficient to access due to internal caching).
5004 Note: Prompts, help texts, and locations are stored in the Choice's
5005 MenuNode(s) rather than in the Choice itself. Check the MenuNode class and
5006 the Choice.nodes attribute. This organization matches the C tools.
5009 The name of the choice, e.g. "FOO" for 'choice FOO', or None if the
5013 The type of the choice. One of BOOL, TRISTATE, UNKNOWN. UNKNOWN is for
5014 choices defined without a type where none of the contained symbols have a
5015 type either (otherwise the choice inherits the type of the first symbol
5016 defined with a type).
5018 When running without modules (CONFIG_MODULES=n), TRISTATE choices
5019 magically change type to BOOL. This matches the C tools, and makes sense
5020 for menuconfig-like functionality.
5023 The type as given in the Kconfig file, without any magic applied. Used
5024 when printing the choice.
5027 The tristate value (mode) of the choice. A choice can be in one of three
5030 0 (n) - The choice is disabled and no symbols can be selected. For
5031 visible choices, this mode is only possible for choices with
5032 the 'optional' flag set (see kconfig-language.txt).
5034 1 (m) - Any number of choice symbols can be set to m, the rest will
5037 2 (y) - One symbol will be y, the rest n.
5039 Only tristate choices can be in m mode. The visibility of the choice is
5040 an upper bound on the mode, and the mode in turn is an upper bound on the
5041 visibility of the choice symbols.
5043 To change the mode, use Choice.set_value().
5045 Implementation note:
5046 The C tools internally represent choices as a type of symbol, with
5047 special-casing in many code paths. This is why there is a lot of
5048 similarity to Symbol. The value (mode) of a choice is really just a
5049 normal symbol value, and an implicit reverse dependency forces its
5050 lower bound to m for visible non-optional choices (the reverse
5051 dependency is 'm && <visibility>').
5053 Symbols within choices get the choice propagated as a dependency to
5054 their properties. This turns the mode of the choice into an upper bound
5055 on e.g. the visibility of choice symbols, and explains the gotcha
5056 related to printing choice symbols mentioned in the module docstring.
5058 Kconfiglib uses a separate Choice class only because it makes the code
5059 and interface less confusing (especially in a user-facing interface).
5060 Corresponding attributes have the same name in the Symbol and Choice
5061 classes, for consistency and compatibility.
5064 Like choice.tri_value, but gives the value as one of the strings
5068 The value (mode) selected by the user through Choice.set_value(). Either
5069 0, 1, or 2, or None if the user hasn't selected a mode. See
5072 WARNING: Do not assign directly to this. It will break things. Use
5073 Choice.set_value() instead.
5076 See the symbol class documentation. Gives the assignable values (modes).
5079 The Symbol instance of the currently selected symbol. None if the Choice
5080 is not in y mode or has no selected symbol (due to unsatisfied
5081 dependencies on choice symbols).
5083 WARNING: Do not assign directly to this. It will break things. Call
5084 sym.set_value(2) on the choice symbol you want to select instead.
5087 The symbol selected by the user (by setting it to y). Ignored if the
5088 choice is not in y mode, but still remembered so that the choice "snaps
5089 back" to the user selection if the mode is changed back to y. This might
5090 differ from 'selection' due to unsatisfied dependencies.
5092 WARNING: Do not assign directly to this. It will break things. Call
5093 sym.set_value(2) on the choice symbol to be selected instead.
5096 See the Symbol class documentation. Acts on the value (mode).
5101 "<choice MY_CHOICE> (defined at foo/Kconfig:12)"
5103 , giving the name of the choice and its definition location(s). If the
5104 choice has no name (isn't defined with 'choice MY_CHOICE'), then it will
5105 be shown as "<choice>" before the list of locations (always a single one
5109 List of symbols contained in the choice.
5111 Obscure gotcha: If a symbol depends on the previous symbol within a
5112 choice so that an implicit menu is created, it won't be a choice symbol,
5113 and won't be included in 'syms'.
5116 A list of MenuNodes for this choice. In practice, the list will probably
5117 always contain a single MenuNode, but it is possible to give a choice a
5118 name and define it in multiple locations.
5121 List of (symbol, cond) tuples for the choice's 'defaults' properties. For
5122 example, 'default A if B && C' is represented as (A, (AND, B, C)). If
5123 there is no condition, 'cond' is self.kconfig.y.
5125 Note that 'depends on' and parent dependencies are propagated to
5126 'default' conditions.
5129 See the corresponding attribute on the MenuNode class.
5132 See Symbol.direct_dep.
5135 A set() with all symbols referenced in the properties and property
5136 conditions of the choice.
5138 Also includes dependencies from surrounding menus and ifs, because those
5139 get propagated to the choice (see the 'Intro to symbol values' section in
5140 the module docstring).
5143 True if the choice has the 'optional' flag set on it and can be in
5147 The Kconfig instance this choice is from.
5150 "_cached_assignable",
5151 "_cached_selection",
5176 Returns the type of the choice. See Symbol.type.
5178 if self.orig_type is TRISTATE and not self.kconfig.modules.tri_value:
5180 return self.orig_type
5183 def str_value(self):
5185 See the class documentation.
5187 return TRI_TO_STR[self.tri_value]
5190 def tri_value(self):
5192 See the class documentation.
5194 # This emulates a reverse dependency of 'm && visibility' for
5195 # non-optional choices, which is how the C implementation does it
5197 val = 0 if self.is_optional else 1
5199 if self.user_value is not None:
5200 val = max(val, self.user_value)
5202 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
5203 # function call (property magic)
5204 val = min(val, self.visibility)
5206 # Promote m to y for boolean choices
5207 return 2 if val == 1 and self.type is BOOL else val
5210 def assignable(self):
5212 See the class documentation.
5214 if self._cached_assignable is None:
5215 self._cached_assignable = self._assignable()
5216 return self._cached_assignable
5219 def visibility(self):
5221 See the class documentation.
5223 if self._cached_vis is None:
5224 self._cached_vis = _visibility(self)
5225 return self._cached_vis
5228 def name_and_loc(self):
5230 See the class documentation.
5232 # Reuse the expression format, which is '<choice (name, if any)>'.
5233 return standard_sc_expr_str(self) + " " + _locs(self)
5236 def selection(self):
5238 See the class documentation.
5240 if self._cached_selection is _NO_CACHED_SELECTION:
5241 self._cached_selection = self._selection()
5242 return self._cached_selection
5244 def set_value(self, value):
5246 Sets the user value (mode) of the choice. Like for Symbol.set_value(),
5247 the visibility might truncate the value. Choices without the 'optional'
5248 attribute (is_optional) can never be in n mode, but 0/"n" is still
5249 accepted since it's not a malformed value (though it will have no
5252 Returns True if the value is valid for the type of the choice, and
5253 False otherwise. This only looks at the form of the value. Check the
5254 Choice.assignable attribute to see what values are currently in range
5255 and would actually be reflected in the mode of the choice.
5257 if value in STR_TO_TRI:
5258 value = STR_TO_TRI[value]
5260 if value == self.user_value:
5261 # We know the value must be valid if it was successfully set
5263 self._was_set = True
5266 if not (self.orig_type is BOOL and value in (2, 0) or
5267 self.orig_type is TRISTATE and value in TRI_TO_STR):
5269 # Display tristate values as n, m, y in the warning
5271 "the value {} is invalid for {}, which has type {} -- "
5272 "assignment ignored"
5273 .format(TRI_TO_STR[value] if value in TRI_TO_STR else
5274 "'{}'".format(value),
5275 self.name_and_loc, TYPE_TO_STR[self.orig_type]))
5279 self.user_value = value
5280 self._was_set = True
5281 self._rec_invalidate()
5285 def unset_value(self):
5287 Resets the user value (mode) and user selection of the Choice, as if
5288 the user had never touched the mode or any of the choice symbols.
5290 if self.user_value is not None or self.user_selection:
5291 self.user_value = self.user_selection = None
5292 self._rec_invalidate()
5295 def referenced(self):
5297 See the class documentation.
5299 return {item for node in self.nodes for item in node.referenced}
5302 def orig_defaults(self):
5304 See the class documentation.
5306 return [d for node in self.nodes for d in node.orig_defaults]
5310 Returns a string with information about the choice when it is evaluated
5311 on e.g. the interactive Python prompt.
5313 fields = ["choice " + self.name if self.name else "choice",
5314 TYPE_TO_STR[self.type]]
5317 for node in self.nodes:
5319 add('"{}"'.format(node.prompt[0]))
5321 add("mode " + self.str_value)
5323 if self.user_value is not None:
5324 add('user mode {}'.format(TRI_TO_STR[self.user_value]))
5327 add("{} selected".format(self.selection.name))
5329 if self.user_selection:
5330 user_sel_str = "{} selected by user" \
5331 .format(self.user_selection.name)
5333 if self.selection is not self.user_selection:
5334 user_sel_str += " (overridden)"
5338 add("visibility " + TRI_TO_STR[self.visibility])
5340 if self.is_optional:
5343 for node in self.nodes:
5344 add("{}:{}".format(node.filename, node.linenr))
5346 return "<{}>".format(", ".join(fields))
5350 Returns a string representation of the choice when it is printed.
5351 Matches the Kconfig format (though without the contained choice
5352 symbols), with any parent dependencies propagated to the 'depends on'
5355 The returned string does not end in a newline.
5357 See Symbol.__str__() as well.
5359 return self.custom_str(standard_sc_expr_str)
5361 def custom_str(self, sc_expr_str_fn):
5363 Works like Choice.__str__(), but allows a custom format to be used for
5364 all symbol/choice references. See expr_str().
5366 return "\n\n".join(node.custom_str(sc_expr_str_fn)
5367 for node in self.nodes)
5375 Choice constructor -- not intended to be called directly by Kconfiglib
5378 # These attributes are always set on the instance from outside and
5379 # don't need defaults:
5384 # - _visited is used during dep. loop detection
5385 self.orig_type = self._visited = 0
5393 self.user_value = self.user_selection = \
5394 self._cached_vis = self._cached_assignable = None
5396 self._cached_selection = _NO_CACHED_SELECTION
5398 # is_constant is checked by _depend_on(). Just set it to avoid having
5399 # to special-case choices.
5400 self.is_constant = self.is_optional = False
5402 # See Kconfig._build_dep()
5403 self._dependents = set()
5405 def _assignable(self):
5406 # Worker function for the 'assignable' attribute
5408 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
5409 # function call (property magic)
5410 vis = self.visibility
5416 if not self.is_optional:
5417 return (2,) if self.type is BOOL else (1, 2)
5418 return (0, 2) if self.type is BOOL else (0, 1, 2)
5422 return (0, 1) if self.is_optional else (1,)
5424 def _selection(self):
5425 # Worker function for the 'selection' attribute
5427 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
5428 # function call (property magic)
5429 if self.tri_value != 2:
5430 # Not in y mode, so no selection
5433 # Use the user selection if it's visible
5434 if self.user_selection and self.user_selection.visibility:
5435 return self.user_selection
5437 # Otherwise, check if we have a default
5438 return self._selection_from_defaults()
5440 def _selection_from_defaults(self):
5441 # Check if we have a default
5442 for sym, cond in self.defaults:
5443 # The default symbol must be visible too
5444 if expr_value(cond) and sym.visibility:
5447 # Otherwise, pick the first visible symbol, if any
5448 for sym in self.syms:
5452 # Couldn't find a selection
5455 def _invalidate(self):
5456 self._cached_vis = self._cached_assignable = None
5457 self._cached_selection = _NO_CACHED_SELECTION
5459 def _rec_invalidate(self):
5460 # See Symbol._rec_invalidate()
5464 for item in self._dependents:
5465 if item._cached_vis is not None:
5466 item._rec_invalidate()
5469 class MenuNode(object):
5471 Represents a menu node in the configuration. This corresponds to an entry
5472 in e.g. the 'make menuconfig' interface, though non-visible choices, menus,
5473 and comments also get menu nodes. If a symbol or choice is defined in
5474 multiple locations, it gets one menu node for each location.
5476 The top-level menu node, corresponding to the implicit top-level menu, is
5477 available in Kconfig.top_node.
5479 The menu nodes for a Symbol or Choice can be found in the
5480 Symbol/Choice.nodes attribute. Menus and comments are represented as plain
5481 menu nodes, with their text stored in the prompt attribute (prompt[0]).
5482 This mirrors the C implementation.
5484 The following attributes are available on MenuNode instances. They should
5485 be viewed as read-only.
5488 Either a Symbol, a Choice, or one of the constants MENU and COMMENT.
5489 Menus and comments are represented as plain menu nodes. Ifs are collapsed
5490 (matching the C implementation) and do not appear in the final menu tree.
5493 The following menu node. None if there is no following node.
5496 The first child menu node. None if there are no children.
5498 Choices and menus naturally have children, but Symbols can also have
5499 children because of menus created automatically from dependencies (see
5500 kconfig-language.txt).
5503 The parent menu node. None if there is no parent.
5506 A (string, cond) tuple with the prompt for the menu node and its
5507 conditional expression (which is self.kconfig.y if there is no
5508 condition). None if there is no prompt.
5510 For symbols and choices, the prompt is stored in the MenuNode rather than
5511 the Symbol or Choice instance. For menus and comments, the prompt holds
5515 The 'default' properties for this particular menu node. See
5518 When evaluating defaults, you should use Symbol/Choice.defaults instead,
5519 as it include properties from all menu nodes (a symbol/choice can have
5520 multiple definition locations/menu nodes). MenuNode.defaults is meant for
5521 documentation generation.
5524 Like MenuNode.defaults, for selects.
5527 Like MenuNode.defaults, for implies.
5530 Like MenuNode.defaults, for ranges.
5537 These work the like the corresponding attributes without orig_*, but omit
5538 any dependencies propagated from 'depends on' and surrounding 'if's (the
5539 direct dependencies, stored in MenuNode.dep).
5541 One use for this is generating less cluttered documentation, by only
5542 showing the direct dependencies in one place.
5545 The help text for the menu node for Symbols and Choices. None if there is
5546 no help text. Always stored in the node rather than the Symbol or Choice.
5547 It is possible to have a separate help text at each location if a symbol
5548 is defined in multiple locations.
5550 Trailing whitespace (including a final newline) is stripped from the help
5551 text. This was not the case before Kconfiglib 10.21.0, where the format
5555 The direct ('depends on') dependencies for the menu node, or
5556 self.kconfig.y if there are no direct dependencies.
5558 This attribute includes any dependencies from surrounding menus and ifs.
5559 Those get propagated to the direct dependencies, and the resulting direct
5560 dependencies in turn get propagated to the conditions of all properties.
5562 If a symbol or choice is defined in multiple locations, only the
5563 properties defined at a particular location get the corresponding
5564 MenuNode.dep dependencies propagated to them.
5567 The 'visible if' dependencies for the menu node (which must represent a
5568 menu), or self.kconfig.y if there are no 'visible if' dependencies.
5569 'visible if' dependencies are recursively propagated to the prompts of
5570 symbols and choices within the menu.
5573 A set() with all symbols and choices referenced in the properties and
5574 property conditions of the menu node.
5576 Also includes dependencies inherited from surrounding menus and ifs.
5577 Choices appear in the dependencies of choice symbols.
5580 Set to True if the children of the menu node should be displayed in a
5581 separate menu. This is the case for the following items:
5583 - Menus (node.item == MENU)
5587 - Symbols defined with the 'menuconfig' keyword. The children come from
5588 implicitly created submenus, and should be displayed in a separate
5589 menu rather than being indented.
5591 'is_menuconfig' is just a hint on how to display the menu node. It's
5592 ignored internally by Kconfiglib, except when printing symbols.
5595 The location where the menu node appears. The filename is relative to
5596 $srctree (or to the current directory if $srctree isn't set), except
5597 absolute paths are used for paths outside $srctree.
5600 A tuple of (filename, linenr) tuples, giving the locations of the
5601 'source' statements via which the Kconfig file containing this menu node
5602 was included. The first element is the location of the 'source' statement
5603 in the top-level Kconfig file passed to Kconfig.__init__(), etc.
5605 Note that the Kconfig file of the menu node itself isn't included. Check
5606 'filename' and 'linenr' for that.
5609 The Kconfig instance the menu node is from.
5634 # Properties defined on this particular menu node. A local 'depends on'
5635 # only applies to these, in case a symbol is defined in multiple
5643 def orig_prompt(self):
5645 See the class documentation.
5649 return (self.prompt[0], self._strip_dep(self.prompt[1]))
5652 def orig_defaults(self):
5654 See the class documentation.
5656 return [(default, self._strip_dep(cond))
5657 for default, cond in self.defaults]
5660 def orig_selects(self):
5662 See the class documentation.
5664 return [(select, self._strip_dep(cond))
5665 for select, cond in self.selects]
5668 def orig_implies(self):
5670 See the class documentation.
5672 return [(imply, self._strip_dep(cond))
5673 for imply, cond in self.implies]
5676 def orig_ranges(self):
5678 See the class documentation.
5680 return [(low, high, self._strip_dep(cond))
5681 for low, high, cond in self.ranges]
5684 def referenced(self):
5686 See the class documentation.
5688 # self.dep is included to catch dependencies from a lone 'depends on'
5689 # when there are no properties to propagate it to
5690 res = expr_items(self.dep)
5693 res |= expr_items(self.prompt[1])
5695 if self.item is MENU:
5696 res |= expr_items(self.visibility)
5698 for value, cond in self.defaults:
5699 res |= expr_items(value)
5700 res |= expr_items(cond)
5702 for value, cond in self.selects:
5704 res |= expr_items(cond)
5706 for value, cond in self.implies:
5708 res |= expr_items(cond)
5710 for low, high, cond in self.ranges:
5713 res |= expr_items(cond)
5719 Returns a string with information about the menu node when it is
5720 evaluated on e.g. the interactive Python prompt.
5725 if self.item.__class__ is Symbol:
5726 add("menu node for symbol " + self.item.name)
5728 elif self.item.__class__ is Choice:
5729 s = "menu node for choice"
5730 if self.item.name is not None:
5731 s += " " + self.item.name
5734 elif self.item is MENU:
5735 add("menu node for menu")
5737 else: # self.item is COMMENT
5738 add("menu node for comment")
5741 add('prompt "{}" (visibility {})'.format(
5742 self.prompt[0], TRI_TO_STR[expr_value(self.prompt[1])]))
5744 if self.item.__class__ is Symbol and self.is_menuconfig:
5745 add("is menuconfig")
5747 add("deps " + TRI_TO_STR[expr_value(self.dep)])
5749 if self.item is MENU:
5750 add("'visible if' deps " + TRI_TO_STR[expr_value(self.visibility)])
5752 if self.item.__class__ in _SYMBOL_CHOICE and self.help is not None:
5761 add("{}:{}".format(self.filename, self.linenr))
5763 return "<{}>".format(", ".join(fields))
5767 Returns a string representation of the menu node. Matches the Kconfig
5768 format, with any parent dependencies propagated to the 'depends on'
5771 The output could (almost) be fed back into a Kconfig parser to redefine
5772 the object associated with the menu node. See the module documentation
5773 for a gotcha related to choice symbols.
5775 For symbols and choices with multiple menu nodes (multiple definition
5776 locations), properties that aren't associated with a particular menu
5777 node are shown on all menu nodes ('option env=...', 'optional' for
5780 The returned string does not end in a newline.
5782 return self.custom_str(standard_sc_expr_str)
5784 def custom_str(self, sc_expr_str_fn):
5786 Works like MenuNode.__str__(), but allows a custom format to be used
5787 for all symbol/choice references. See expr_str().
5789 return self._menu_comment_node_str(sc_expr_str_fn) \
5790 if self.item in _MENU_COMMENT else \
5791 self._sym_choice_node_str(sc_expr_str_fn)
5793 def _menu_comment_node_str(self, sc_expr_str_fn):
5794 s = '{} "{}"'.format("menu" if self.item is MENU else "comment",
5797 if self.dep is not self.kconfig.y:
5798 s += "\n\tdepends on {}".format(expr_str(self.dep, sc_expr_str_fn))
5800 if self.item is MENU and self.visibility is not self.kconfig.y:
5801 s += "\n\tvisible if {}".format(expr_str(self.visibility,
5806 def _sym_choice_node_str(self, sc_expr_str_fn):
5808 lines.append("\t" + s)
5810 def indent_add_cond(s, cond):
5811 if cond is not self.kconfig.y:
5812 s += " if " + expr_str(cond, sc_expr_str_fn)
5817 if sc.__class__ is Symbol:
5818 lines = [("menuconfig " if self.is_menuconfig else "config ")
5821 lines = ["choice " + sc.name if sc.name else "choice"]
5823 if sc.orig_type and not self.prompt: # sc.orig_type != UNKNOWN
5824 # If there's a prompt, we'll use the '<type> "prompt"' shorthand
5826 indent_add(TYPE_TO_STR[sc.orig_type])
5830 prefix = TYPE_TO_STR[sc.orig_type]
5832 # Symbol defined without a type (which generates a warning)
5835 indent_add_cond(prefix + ' "{}"'.format(escape(self.prompt[0])),
5836 self.orig_prompt[1])
5838 if sc.__class__ is Symbol:
5839 if sc.is_allnoconfig_y:
5840 indent_add("option allnoconfig_y")
5842 if sc is sc.kconfig.defconfig_list:
5843 indent_add("option defconfig_list")
5845 if sc.env_var is not None:
5846 indent_add('option env="{}"'.format(sc.env_var))
5848 if sc is sc.kconfig.modules:
5849 indent_add("option modules")
5851 for low, high, cond in self.orig_ranges:
5853 "range {} {}".format(sc_expr_str_fn(low),
5854 sc_expr_str_fn(high)),
5857 for default, cond in self.orig_defaults:
5858 indent_add_cond("default " + expr_str(default, sc_expr_str_fn),
5861 if sc.__class__ is Choice and sc.is_optional:
5862 indent_add("optional")
5864 if sc.__class__ is Symbol:
5865 for select, cond in self.orig_selects:
5866 indent_add_cond("select " + sc_expr_str_fn(select), cond)
5868 for imply, cond in self.orig_implies:
5869 indent_add_cond("imply " + sc_expr_str_fn(imply), cond)
5871 if self.dep is not sc.kconfig.y:
5872 indent_add("depends on " + expr_str(self.dep, sc_expr_str_fn))
5874 if self.help is not None:
5876 for line in self.help.splitlines():
5877 indent_add(" " + line)
5879 return "\n".join(lines)
5881 def _strip_dep(self, expr):
5882 # Helper function for removing MenuNode.dep from 'expr'. Uses two
5883 # pieces of internal knowledge: (1) Expressions are reused rather than
5884 # copied, and (2) the direct dependencies always appear at the end.
5886 # ... if dep -> ... if y
5887 if self.dep is expr:
5888 return self.kconfig.y
5890 # (AND, X, dep) -> X
5891 if expr.__class__ is tuple and expr[0] is AND and expr[2] is self.dep:
5897 class Variable(object):
5899 Represents a preprocessor variable/function.
5901 The following attributes are available:
5904 The name of the variable.
5907 The unexpanded value of the variable.
5910 The expanded value of the variable. For simple variables (those defined
5911 with :=), this will equal 'value'. Accessing this property will raise a
5912 KconfigError if the expansion seems to be stuck in a loop.
5914 Accessing this field is the same as calling expanded_value_w_args() with
5915 no arguments. I hadn't considered function arguments when adding it. It
5916 is retained for backwards compatibility though.
5919 True if the variable is recursive (defined with =).
5930 def expanded_value(self):
5932 See the class documentation.
5934 return self.expanded_value_w_args()
5936 def expanded_value_w_args(self, *args):
5938 Returns the expanded value of the variable/function. Any arguments
5939 passed will be substituted for $(1), $(2), etc.
5941 Raises a KconfigError if the expansion seems to be stuck in a loop.
5943 return self.kconfig._fn_val((self.name,) + args)
5946 return "<variable {}, {}, value '{}'>" \
5948 "recursive" if self.is_recursive else "immediate",
5952 class KconfigError(Exception):
5954 Exception raised for Kconfig-related errors.
5956 KconfigError and KconfigSyntaxError are the same class. The
5957 KconfigSyntaxError alias is only maintained for backwards compatibility.
5960 KconfigSyntaxError = KconfigError # Backwards compatibility
5963 class InternalError(Exception):
5964 "Never raised. Kept around for backwards compatibility."
5969 # If 'errno' and 'strerror' are set on IOError, then __str__() always returns
5970 # "[Errno <errno>] <strerror>", ignoring any custom message passed to the
5971 # constructor. By defining our own subclass, we can use a custom message while
5972 # also providing 'errno', 'strerror', and 'filename' to scripts.
5973 class _KconfigIOError(IOError):
5974 def __init__(self, ioerror, msg):
5976 super(_KconfigIOError, self).__init__(
5977 ioerror.errno, ioerror.strerror, ioerror.filename)
5988 def expr_value(expr):
5990 Evaluates the expression 'expr' to a tristate value. Returns 0 (n), 1 (m),
5993 'expr' must be an already-parsed expression from a Symbol, Choice, or
5994 MenuNode property. To evaluate an expression represented as a string, use
5995 Kconfig.eval_string().
5997 Passing subexpressions of expressions to this function works as expected.
5999 if expr.__class__ is not tuple:
6000 return expr.tri_value
6003 v1 = expr_value(expr[1])
6004 # Short-circuit the n case as an optimization (~5% faster
6005 # allnoconfig.py and allyesconfig.py, as of writing)
6006 return 0 if not v1 else min(v1, expr_value(expr[2]))
6009 v1 = expr_value(expr[1])
6010 # Short-circuit the y case as an optimization
6011 return 2 if v1 == 2 else max(v1, expr_value(expr[2]))
6014 return 2 - expr_value(expr[1])
6018 # Implements <, <=, >, >= comparisons as well. These were added to
6019 # kconfig in 31847b67 (kconfig: allow use of relations other than
6024 # If both operands are strings...
6025 if v1.orig_type is STRING and v2.orig_type is STRING:
6026 # ...then compare them lexicographically
6027 comp = _strcmp(v1.str_value, v2.str_value)
6029 # Otherwise, try to compare them as numbers
6031 comp = _sym_to_num(v1) - _sym_to_num(v2)
6033 # Fall back on a lexicographic comparison if the operands don't
6035 comp = _strcmp(v1.str_value, v2.str_value)
6037 return 2*(comp == 0 if rel is EQUAL else
6038 comp != 0 if rel is UNEQUAL else
6039 comp < 0 if rel is LESS else
6040 comp <= 0 if rel is LESS_EQUAL else
6041 comp > 0 if rel is GREATER else
6045 def standard_sc_expr_str(sc):
6047 Standard symbol/choice printing function. Uses plain Kconfig syntax, and
6048 displays choices as <choice> (or <choice NAME>, for named choices).
6052 if sc.__class__ is Symbol:
6053 if sc.is_constant and sc.name not in STR_TO_TRI:
6054 return '"{}"'.format(escape(sc.name))
6057 return "<choice {}>".format(sc.name) if sc.name else "<choice>"
6060 def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
6062 Returns the string representation of the expression 'expr', as in a Kconfig
6065 Passing subexpressions of expressions to this function works as expected.
6067 sc_expr_str_fn (default: standard_sc_expr_str):
6068 This function is called for every symbol/choice (hence "sc") appearing in
6069 the expression, with the symbol/choice as the argument. It is expected to
6070 return a string to be used for the symbol/choice.
6072 This can be used e.g. to turn symbols/choices into links when generating
6073 documentation, or for printing the value of each symbol/choice after it.
6075 Note that quoted values are represented as constants symbols
6076 (Symbol.is_constant == True).
6078 if expr.__class__ is not tuple:
6079 return sc_expr_str_fn(expr)
6082 return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn),
6083 _parenthesize(expr[2], OR, sc_expr_str_fn))
6086 # This turns A && B || C && D into "(A && B) || (C && D)", which is
6087 # redundant, but more readable
6088 return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn),
6089 _parenthesize(expr[2], AND, sc_expr_str_fn))
6092 if expr[1].__class__ is tuple:
6093 return "!({})".format(expr_str(expr[1], sc_expr_str_fn))
6094 return "!" + sc_expr_str_fn(expr[1]) # Symbol
6098 # Relation operands are always symbols (quoted strings are constant
6100 return "{} {} {}".format(sc_expr_str_fn(expr[1]), REL_TO_STR[expr[0]],
6101 sc_expr_str_fn(expr[2]))
6104 def expr_items(expr):
6106 Returns a set() of all items (symbols and choices) that appear in the
6109 Passing subexpressions of expressions to this function works as expected.
6114 if subexpr.__class__ is tuple:
6115 # AND, OR, NOT, or relation
6119 # NOTs only have a single operand
6120 if subexpr[0] is not NOT:
6131 def split_expr(expr, op):
6133 Returns a list containing the top-level AND or OR operands in the
6134 expression 'expr', in the same (left-to-right) order as they appear in
6137 This can be handy e.g. for splitting (weak) reverse dependencies
6138 from 'select' and 'imply' into individual selects/implies.
6141 Either AND to get AND operands, or OR to get OR operands.
6143 (Having this as an operand might be more future-safe than having two
6144 hardcoded functions.)
6147 Pseudo-code examples:
6149 split_expr( A , OR ) -> [A]
6150 split_expr( A && B , OR ) -> [A && B]
6151 split_expr( A || B , OR ) -> [A, B]
6152 split_expr( A || B , AND ) -> [A || B]
6153 split_expr( A || B || (C && D) , OR ) -> [A, B, C && D]
6155 # Second || is not at the top level
6156 split_expr( A || (B && (C || D)) , OR ) -> [A, B && (C || D)]
6158 # Parentheses don't matter as long as we stay at the top level (don't
6159 # encounter any non-'op' nodes)
6160 split_expr( (A || B) || C , OR ) -> [A, B, C]
6161 split_expr( A || (B || C) , OR ) -> [A, B, C]
6166 if subexpr.__class__ is tuple and subexpr[0] is op:
6178 Escapes the string 's' in the same fashion as is done for display in
6179 Kconfig format and when writing strings to a .config file. " and \ are
6180 replaced by \" and \\, respectively.
6182 # \ must be escaped before " to avoid double escaping
6183 return s.replace("\\", r"\\").replace('"', r'\"')
6188 Unescapes the string 's'. \ followed by any character is replaced with just
6189 that character. Used internally when reading .config files.
6191 return _unescape_sub(r"\1", s)
6194 _unescape_sub = re.compile(r"\\(.)").sub
6197 def standard_kconfig(description=None):
6199 Argument parsing helper for tools that take a single optional Kconfig file
6200 argument (default: Kconfig). Returns the Kconfig instance for the parsed
6201 configuration. Uses argparse internally.
6203 Exits with sys.exit() (which raises SystemExit) on errors.
6205 description (default: None):
6206 The 'description' passed to argparse.ArgumentParser().
6207 argparse.RawDescriptionHelpFormatter is used, so formatting is preserved.
6211 parser = argparse.ArgumentParser(
6212 formatter_class=argparse.RawDescriptionHelpFormatter,
6213 description=description)
6215 parser.add_argument(
6220 help="Top-level Kconfig file (default: Kconfig)")
6222 return Kconfig(parser.parse_args().kconfig, suppress_traceback=True)
6225 def standard_config_filename():
6227 Helper for tools. Returns the value of KCONFIG_CONFIG (which specifies the
6228 .config file to load/save) if it is set, and ".config" otherwise.
6230 Calling load_config() with filename=None might give the behavior you want,
6231 without having to use this function.
6233 return os.getenv("KCONFIG_CONFIG", ".config")
6236 def load_allconfig(kconf, filename):
6238 Use Kconfig.load_allconfig() instead, which was added in Kconfiglib 13.4.0.
6239 Supported for backwards compatibility. Might be removed at some point after
6240 a long period of deprecation warnings.
6242 allconfig = os.getenv("KCONFIG_ALLCONFIG")
6243 if allconfig is None:
6247 # "Upcasts" a _KconfigIOError to an IOError, removing the custom
6248 # __str__() message. The standard message is better here.
6250 # This might also convert an OSError to an IOError in obscure cases,
6251 # but it's probably not a big deal. The distinction is shaky (see
6253 return IOError(e.errno, e.strerror, e.filename)
6255 old_warn_assign_override = kconf.warn_assign_override
6256 old_warn_assign_redun = kconf.warn_assign_redun
6257 kconf.warn_assign_override = kconf.warn_assign_redun = False
6259 if allconfig in ("", "1"):
6261 print(kconf.load_config(filename, False))
6262 except EnvironmentError as e1:
6264 print(kconf.load_config("all.config", False))
6265 except EnvironmentError as e2:
6266 sys.exit("error: KCONFIG_ALLCONFIG is set, but neither {} "
6267 "nor all.config could be opened: {}, {}"
6268 .format(filename, std_msg(e1), std_msg(e2)))
6271 print(kconf.load_config(allconfig, False))
6272 except EnvironmentError as e:
6273 sys.exit("error: KCONFIG_ALLCONFIG is set to '{}', which "
6274 "could not be opened: {}"
6275 .format(allconfig, std_msg(e)))
6277 kconf.warn_assign_override = old_warn_assign_override
6278 kconf.warn_assign_redun = old_warn_assign_redun
6282 # Internal functions
6286 def _visibility(sc):
6287 # Symbols and Choices have a "visibility" that acts as an upper bound on
6288 # the values a user can set for them, corresponding to the visibility in
6289 # e.g. 'make menuconfig'. This function calculates the visibility for the
6290 # Symbol or Choice 'sc' -- the logic is nearly identical.
6294 for node in sc.nodes:
6296 vis = max(vis, expr_value(node.prompt[1]))
6298 if sc.__class__ is Symbol and sc.choice:
6299 if sc.choice.orig_type is TRISTATE and \
6300 sc.orig_type is not TRISTATE and sc.choice.tri_value != 2:
6301 # Non-tristate choice symbols are only visible in y mode
6304 if sc.orig_type is TRISTATE and vis == 1 and sc.choice.tri_value == 2:
6305 # Choice symbols with m visibility are not visible in y mode
6308 # Promote m to y if we're dealing with a non-tristate (possibly due to
6309 # modules being disabled)
6310 if vis == 1 and sc.type is not TRISTATE:
6316 def _depend_on(sc, expr):
6317 # Adds 'sc' (symbol or choice) as a "dependee" to all symbols in 'expr'.
6318 # Constant symbols in 'expr' are skipped as they can never change value
6321 if expr.__class__ is tuple:
6322 # AND, OR, NOT, or relation
6324 _depend_on(sc, expr[1])
6326 # NOTs only have a single operand
6327 if expr[0] is not NOT:
6328 _depend_on(sc, expr[2])
6330 elif not expr.is_constant:
6331 # Non-constant symbol, or choice
6332 expr._dependents.add(sc)
6335 def _parenthesize(expr, type_, sc_expr_str_fn):
6336 # expr_str() helper. Adds parentheses around expressions of type 'type_'.
6338 if expr.__class__ is tuple and expr[0] is type_:
6339 return "({})".format(expr_str(expr, sc_expr_str_fn))
6340 return expr_str(expr, sc_expr_str_fn)
6343 def _ordered_unique(lst):
6344 # Returns 'lst' with any duplicates removed, preserving order. This hacky
6345 # version seems to be a common idiom. It relies on short-circuit evaluation
6346 # and set.add() returning None, which is falsy.
6350 return [x for x in lst if x not in seen and not seen_add(x)]
6353 def _is_base_n(s, n):
6361 def _strcmp(s1, s2):
6362 # strcmp()-alike that returns -1, 0, or 1
6364 return (s1 > s2) - (s1 < s2)
6367 def _sym_to_num(sym):
6368 # expr_value() helper for converting a symbol to a number. Raises
6369 # ValueError for symbols that can't be converted.
6371 # For BOOL and TRISTATE, n/m/y count as 0/1/2. This mirrors 9059a3493ef
6372 # ("kconfig: fix relational operators for bool and tristate symbols") in
6373 # the C implementation.
6374 return sym.tri_value if sym.orig_type in _BOOL_TRISTATE else \
6375 int(sym.str_value, _TYPE_TO_BASE[sym.orig_type])
6378 def _touch_dep_file(path, sym_name):
6379 # If sym_name is MY_SYM_NAME, touches my/sym/name.h. See the sync_deps()
6382 sym_path = path + os.sep + sym_name.lower().replace("_", os.sep) + ".h"
6383 sym_path_dir = dirname(sym_path)
6384 if not exists(sym_path_dir):
6385 os.makedirs(sym_path_dir, 0o755)
6387 # A kind of truncating touch, mirroring the C tools
6389 sym_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644))
6392 def _save_old(path):
6393 # See write_config()
6396 # Import as needed, to save some startup time
6398 shutil.copyfile(src, dst)
6403 elif hasattr(os, "replace"):
6404 # Python 3 (3.3+) only. Best choice when available, because it
6405 # removes <filename>.old on both *nix and Windows.
6406 copy_fn = os.replace
6407 elif os.name == "posix":
6408 # Removes <filename>.old on POSIX systems
6411 # Fall back on copying
6415 copy_fn(path, path + ".old")
6417 # Ignore errors from 'path' missing as well as other errors.
6418 # <filename>.old file is usually more of a nice-to-have, and not worth
6419 # erroring out over e.g. if <filename>.old happens to be a directory or
6420 # <filename> is something like /dev/null.
6425 # Symbol/Choice.name_and_loc helper. Returns the "(defined at ...)" part of
6426 # the string. 'sc' is a Symbol or Choice.
6429 return "(defined at {})".format(
6430 ", ".join("{0.filename}:{0.linenr}".format(node)
6431 for node in sc.nodes))
6433 return "(undefined)"
6439 def _expr_depends_on(expr, sym):
6440 # Reimplementation of expr_depends_symbol() from mconf.c. Used to determine
6441 # if a submenu should be implicitly created. This also influences which
6442 # items inside choice statements are considered choice items.
6444 if expr.__class__ is not tuple:
6447 if expr[0] in _EQUAL_UNEQUAL:
6448 # Check for one of the following:
6449 # sym = m/y, m/y = sym, sym != n, n != sym
6451 left, right = expr[1:]
6454 left, right = right, left
6455 elif left is not sym:
6458 return (expr[0] is EQUAL and right is sym.kconfig.m or
6459 right is sym.kconfig.y) or \
6460 (expr[0] is UNEQUAL and right is sym.kconfig.n)
6462 return expr[0] is AND and \
6463 (_expr_depends_on(expr[1], sym) or
6464 _expr_depends_on(expr[2], sym))
6467 def _auto_menu_dep(node1, node2):
6468 # Returns True if node2 has an "automatic menu dependency" on node1. If
6469 # node2 has a prompt, we check its condition. Otherwise, we look directly
6472 return _expr_depends_on(node2.prompt[1] if node2.prompt else node2.dep,
6477 # "Flattens" menu nodes without prompts (e.g. 'if' nodes and non-visible
6478 # symbols with children from automatic menu creation) so that their
6479 # children appear after them instead. This gives a clean menu structure
6480 # with no unexpected "jumps" in the indentation.
6482 # Do not flatten promptless choices (which can appear "legitimately" if a
6483 # named choice is defined in multiple locations to add on symbols). It
6484 # looks confusing, and the menuconfig already shows all choice symbols if
6485 # you enter the choice at some location with a prompt.
6488 if node.list and not node.prompt and \
6489 node.item.__class__ is not Choice:
6491 last_node = node.list
6493 last_node.parent = node.parent
6494 if not last_node.next:
6496 last_node = last_node.next
6498 last_node.next = node.next
6499 node.next = node.list
6505 def _remove_ifs(node):
6506 # Removes 'if' nodes (which can be recognized by MenuNode.item being None),
6507 # which are assumed to already have been flattened. The C implementation
6508 # doesn't bother to do this, but we expose the menu tree directly, and it
6509 # makes it nicer to work with.
6512 while cur and not cur.item:
6519 while next and not next.item:
6527 # due to tricky Python semantics. The order matters.
6528 cur.next = cur = next
6531 def _finalize_choice(node):
6532 # Finalizes a choice, marking each symbol whose menu node has the choice as
6533 # the parent as a choice symbol, and automatically determining types if not
6540 if cur.item.__class__ is Symbol:
6541 cur.item.choice = choice
6542 choice.syms.append(cur.item)
6545 # If no type is specified for the choice, its type is that of
6546 # the first choice item with a specified type
6547 if not choice.orig_type:
6548 for item in choice.syms:
6550 choice.orig_type = item.orig_type
6553 # Each choice item of UNKNOWN type gets the type of the choice
6554 for sym in choice.syms:
6555 if not sym.orig_type:
6556 sym.orig_type = choice.orig_type
6559 def _check_dep_loop_sym(sym, ignore_choice):
6560 # Detects dependency loops using depth-first search on the dependency graph
6561 # (which is calculated earlier in Kconfig._build_dep()).
6565 # 1. Symbols/choices start out with _visited = 0, meaning unvisited.
6567 # 2. When a symbol/choice is first visited, _visited is set to 1, meaning
6568 # "visited, potentially part of a dependency loop". The recursive
6569 # search then continues from the symbol/choice.
6571 # 3. If we run into a symbol/choice X with _visited already set to 1,
6572 # there's a dependency loop. The loop is found on the call stack by
6573 # recording symbols while returning ("on the way back") until X is seen
6576 # 4. Once a symbol/choice and all its dependencies (or dependents in this
6577 # case) have been checked recursively without detecting any loops, its
6578 # _visited is set to 2, meaning "visited, not part of a dependency
6581 # This saves work if we run into the symbol/choice again in later calls
6582 # to _check_dep_loop_sym(). We just return immediately.
6584 # Choices complicate things, as every choice symbol depends on every other
6585 # choice symbol in a sense. When a choice is "entered" via a choice symbol
6586 # X, we visit all choice symbols from the choice except X, and prevent
6587 # immediately revisiting the choice with a flag (ignore_choice).
6589 # Maybe there's a better way to handle this (different flags or the
6592 if not sym._visited:
6593 # sym._visited == 0, unvisited
6597 for dep in sym._dependents:
6598 # Choices show up in Symbol._dependents when the choice has the
6599 # symbol in a 'prompt' or 'default' condition (e.g.
6600 # 'default ... if SYM').
6602 # Since we aren't entering the choice via a choice symbol, all
6603 # choice symbols need to be checked, hence the None.
6604 loop = _check_dep_loop_choice(dep, None) \
6605 if dep.__class__ is Choice \
6606 else _check_dep_loop_sym(dep, False)
6609 # Dependency loop found
6610 return _found_dep_loop(loop, sym)
6612 if sym.choice and not ignore_choice:
6613 loop = _check_dep_loop_choice(sym.choice, sym)
6615 # Dependency loop found
6616 return _found_dep_loop(loop, sym)
6618 # The symbol is not part of a dependency loop
6621 # No dependency loop found
6624 if sym._visited == 2:
6625 # The symbol was checked earlier and is already known to not be part of
6629 # sym._visited == 1, found a dependency loop. Return the symbol as the
6630 # first element in it.
6634 def _check_dep_loop_choice(choice, skip):
6635 if not choice._visited:
6636 # choice._visited == 0, unvisited
6640 # Check for loops involving choice symbols. If we came here via a
6641 # choice symbol, skip that one, as we'd get a false positive
6642 # '<sym FOO> -> <choice> -> <sym FOO>' loop otherwise.
6643 for sym in choice.syms:
6645 # Prevent the choice from being immediately re-entered via the
6646 # "is a choice symbol" path by passing True
6647 loop = _check_dep_loop_sym(sym, True)
6649 # Dependency loop found
6650 return _found_dep_loop(loop, choice)
6652 # The choice is not part of a dependency loop
6655 # No dependency loop found
6658 if choice._visited == 2:
6659 # The choice was checked earlier and is already known to not be part of
6663 # choice._visited == 1, found a dependency loop. Return the choice as the
6664 # first element in it.
6668 def _found_dep_loop(loop, cur):
6669 # Called "on the way back" when we know we have a loop
6671 # Is the symbol/choice 'cur' where the loop started?
6672 if cur is not loop[0]:
6673 # Nope, it's just a part of the loop
6674 return loop + (cur,)
6676 # Yep, we have the entire loop. Throw an exception that shows it.
6678 msg = "\nDependency loop\n" \
6679 "===============\n\n"
6682 if item is not loop[0]:
6683 msg += "...depends on "
6684 if item.__class__ is Symbol and item.choice:
6685 msg += "the choice symbol "
6687 msg += "{}, with definition...\n\n{}\n\n" \
6688 .format(item.name_and_loc, item)
6690 # Small wart: Since we reuse the already calculated
6691 # Symbol/Choice._dependents sets for recursive dependency detection, we
6692 # lose information on whether a dependency came from a 'select'/'imply'
6693 # condition or e.g. a 'depends on'.
6695 # This might cause selecting symbols to "disappear". For example,
6696 # a symbol B having 'select A if C' gives a direct dependency from A to
6697 # C, since it corresponds to a reverse dependency of B && C.
6699 # Always print reverse dependencies for symbols that have them to make
6700 # sure information isn't lost. I wonder if there's some neat way to
6703 if item.__class__ is Symbol:
6704 if item.rev_dep is not item.kconfig.n:
6705 msg += "(select-related dependencies: {})\n\n" \
6706 .format(expr_str(item.rev_dep))
6708 if item.weak_rev_dep is not item.kconfig.n:
6709 msg += "(imply-related dependencies: {})\n\n" \
6710 .format(expr_str(item.rev_dep))
6712 msg += "...depends again on " + loop[0].name_and_loc
6714 raise KconfigError(msg)
6717 def _decoding_error(e, filename, macro_linenr=None):
6718 # Gives the filename and context for UnicodeDecodeError's, which are a pain
6719 # to debug otherwise. 'e' is the UnicodeDecodeError object.
6721 # If the decoding error is for the output of a $(shell,...) command,
6722 # macro_linenr holds the line number where it was run (the exact line
6723 # number isn't available for decoding errors in files).
6727 "Malformed {} in {}\n"
6729 "Problematic data: {}\n"
6730 "Reason: {}".format(
6732 "'{}'".format(filename) if macro_linenr is None else
6733 "output from macro at {}:{}".format(filename, macro_linenr),
6734 e.object[max(e.start - 40, 0):e.end + 40],
6735 e.object[e.start:e.end],
6739 def _warn_verbose_deprecated(fn_name):
6741 "Deprecation warning: {0}()'s 'verbose' argument has no effect. Since "
6742 "Kconfiglib 12.0.0, the message is returned from {0}() instead, "
6743 "and is always generated. Do e.g. print(kconf.{0}()) if you want to "
6744 "want to show a message like \"Loaded configuration '.config'\" on "
6745 "stdout. The old API required ugly hacks to reuse messages in "
6746 "configuration interfaces.\n".format(fn_name))
6749 # Predefined preprocessor functions
6752 def _filename_fn(kconf, _):
6753 return kconf.filename
6756 def _lineno_fn(kconf, _):
6757 return str(kconf.linenr)
6760 def _info_fn(kconf, _, msg):
6761 print("{}:{}: {}".format(kconf.filename, kconf.linenr, msg))
6766 def _warning_if_fn(kconf, _, cond, msg):
6768 kconf._warn(msg, kconf.filename, kconf.linenr)
6773 def _error_if_fn(kconf, _, cond, msg):
6775 raise KconfigError("{}:{}: {}".format(
6776 kconf.filename, kconf.linenr, msg))
6781 def _shell_fn(kconf, _, command):
6782 import subprocess # Only import as needed, to save some startup time
6784 stdout, stderr = subprocess.Popen(
6785 command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
6790 stdout = stdout.decode(kconf._encoding)
6791 stderr = stderr.decode(kconf._encoding)
6792 except UnicodeDecodeError as e:
6793 _decoding_error(e, kconf.filename, kconf.linenr)
6796 kconf._warn("'{}' wrote to stderr: {}".format(
6797 command, "\n".join(stderr.splitlines())),
6798 kconf.filename, kconf.linenr)
6800 # Universal newlines with splitlines() (to prevent e.g. stray \r's in
6801 # command output on Windows), trailing newline removal, and
6802 # newline-to-space conversion.
6804 # On Python 3 versions before 3.6, it's not possible to specify the
6805 # encoding when passing universal_newlines=True to Popen() (the 'encoding'
6806 # parameter was added in 3.6), so we do this manual version instead.
6807 return "\n".join(stdout.splitlines()).rstrip("\n").replace("\n", " ")
6825 # Constant representing that there's no cached choice selection. This is
6826 # distinct from a cached None (no selection). Any object that's not None or a
6827 # Symbol will do. We test this with 'is'.
6828 _NO_CACHED_SELECTION = 0
6830 # Are we running on Python 2?
6831 _IS_PY2 = sys.version_info[0] < 3
6834 _UNAME_RELEASE = os.uname()[2]
6835 except AttributeError:
6836 # Only import as needed, to save some startup time
6838 _UNAME_RELEASE = platform.uname()[2]
6840 # The token and type constants below are safe to test with 'is', which is a bit
6841 # faster (~30% faster on my machine, and a few % faster for total parsing
6842 # time), even without assuming Python's small integer optimization (which
6843 # caches small integer objects). The constants end up pointing to unique
6844 # integer objects, and since we consistently refer to them via the names below,
6845 # we always get the same object.
6847 # Client code should use == though.
6849 # Tokens, with values 1, 2, ... . Avoiding 0 simplifies some checks by making
6850 # all tokens except empty strings truthy.
6904 # Keyword to token map, with the get() method assigned directly as a small
6907 "---help---": _T_HELP,
6908 "allnoconfig_y": _T_ALLNOCONFIG_Y,
6911 "choice": _T_CHOICE,
6912 "comment": _T_COMMENT,
6913 "config": _T_CONFIG,
6914 "def_bool": _T_DEF_BOOL,
6915 "def_hex": _T_DEF_HEX,
6916 "def_int": _T_DEF_INT,
6917 "def_string": _T_DEF_STRING,
6918 "def_tristate": _T_DEF_TRISTATE,
6919 "default": _T_DEFAULT,
6920 "defconfig_list": _T_DEFCONFIG_LIST,
6921 "depends": _T_DEPENDS,
6922 "endchoice": _T_ENDCHOICE,
6924 "endmenu": _T_ENDMENU,
6926 "grsource": _T_ORSOURCE, # Backwards compatibility
6927 "gsource": _T_OSOURCE, # Backwards compatibility
6933 "mainmenu": _T_MAINMENU,
6935 "menuconfig": _T_MENUCONFIG,
6936 "modules": _T_MODULES,
6938 "option": _T_OPTION,
6939 "optional": _T_OPTIONAL,
6940 "orsource": _T_ORSOURCE,
6941 "osource": _T_OSOURCE,
6942 "prompt": _T_PROMPT,
6944 "rsource": _T_RSOURCE,
6945 "select": _T_SELECT,
6946 "source": _T_SOURCE,
6947 "string": _T_STRING,
6948 "tristate": _T_TRISTATE,
6949 "visible": _T_VISIBLE,
6952 # The constants below match the value of the corresponding tokens to remove the
6953 # need for conversion
6957 COMMENT = _T_COMMENT
6964 UNEQUAL = _T_UNEQUAL
6966 LESS_EQUAL = _T_LESS_EQUAL
6967 GREATER = _T_GREATER
6968 GREATER_EQUAL = _T_GREATER_EQUAL
6976 GREATER_EQUAL: ">=",
6979 # Symbol/choice types. UNKNOWN is 0 (falsy) to simplify some checks.
6980 # Client code shouldn't rely on it though, as it was non-zero in
6984 TRISTATE = _T_TRISTATE
6992 TRISTATE: "tristate",
6998 # Used in comparisons. 0 means the base is inferred from the format of the
7007 # def_bool -> BOOL, etc.
7008 _DEF_TOKEN_TO_TYPE = {
7012 _T_DEF_STRING: STRING,
7013 _T_DEF_TRISTATE: TRISTATE,
7016 # Tokens after which strings are expected. This is used to tell strings from
7017 # constant symbol references during tokenization, both of which are enclosed in
7020 # Identifier-like lexemes ("missing quotes") are also treated as strings after
7021 # these tokens. _T_CHOICE is included to avoid symbols being registered for
7023 _STRING_LEX = frozenset({
7040 # Various sets for quick membership tests. Gives a single global lookup and
7041 # avoids creating temporary dicts/tuples.
7043 _TYPE_TOKENS = frozenset({
7051 _SOURCE_TOKENS = frozenset({
7058 _REL_SOURCE_TOKENS = frozenset({
7063 # Obligatory (non-optional) sources
7064 _OBL_SOURCE_TOKENS = frozenset({
7069 _BOOL_TRISTATE = frozenset({
7074 _BOOL_TRISTATE_UNKNOWN = frozenset({
7080 _INT_HEX = frozenset({
7085 _SYMBOL_CHOICE = frozenset({
7090 _MENU_COMMENT = frozenset({
7095 _EQUAL_UNEQUAL = frozenset({
7100 _RELATIONS = frozenset({
7109 # Helper functions for getting compiled regular expressions, with the needed
7110 # matching function returned directly as a small optimization.
7112 # Use ASCII regex matching on Python 3. It's already the default on Python 2.
7115 def _re_match(regex):
7116 return re.compile(regex, 0 if _IS_PY2 else re.ASCII).match
7119 def _re_search(regex):
7120 return re.compile(regex, 0 if _IS_PY2 else re.ASCII).search
7123 # Various regular expressions used during parsing
7125 # The initial token on a line. Also eats leading and trailing whitespace, so
7126 # that we can jump straight to the next token (or to the end of the line if
7127 # there is only one token).
7129 # This regex will also fail to match for empty lines and comment lines.
7131 # '$' is included to detect preprocessor variable assignments with macro
7132 # expansions in the left-hand side.
7133 _command_match = _re_match(r"\s*([A-Za-z0-9_$-]+)\s*")
7135 # An identifier/keyword after the first token. Also eats trailing whitespace.
7136 # '$' is included to detect identifiers containing macro expansions.
7137 _id_keyword_match = _re_match(r"([A-Za-z0-9_$/.-]+)\s*")
7139 # A fragment in the left-hand side of a preprocessor variable assignment. These
7140 # are the portions between macro expansions ($(foo)). Macros are supported in
7141 # the LHS (variable name).
7142 _assignment_lhs_fragment_match = _re_match("[A-Za-z0-9_-]*")
7144 # The assignment operator and value (right-hand side) in a preprocessor
7145 # variable assignment
7146 _assignment_rhs_match = _re_match(r"\s*(=|:=|\+=)\s*(.*)")
7148 # Special characters/strings while expanding a macro ('(', ')', ',', and '$(')
7149 _macro_special_search = _re_search(r"\(|\)|,|\$\(")
7151 # Special characters/strings while expanding a string (quotes, '\', and '$(')
7152 _string_special_search = _re_search(r'"|\'|\\|\$\(')
7154 # Special characters/strings while expanding a symbol name. Also includes
7155 # end-of-line, in case the macro is the last thing on the line.
7156 _name_special_search = _re_search(r'[^A-Za-z0-9_$/.-]|\$\(|$')
7158 # A valid right-hand side for an assignment to a string symbol in a .config
7159 # file, including escaped characters. Extracts the contents.
7160 _conf_string_match = _re_match(r'"((?:[^\\"]|\\.)*)"')