source: menu/kconfiglib.py@ dfab075

ablfs-more legacy trunk
Last change on this file since dfab075 was cf2f109, checked in by Pierre Labastie <pierre@…>, 5 years ago

Update to Kconfiglib version 12.4.0. This removes the need to use
".configuration.old"

  • Property mode set to 100644
File size: 246.9 KB
RevLine 
[f596dde]1# Copyright (c) 2011-2019, Ulf Magnusson
2# SPDX-License-Identifier: ISC
3
4"""
5Overview
6========
7
8Kconfiglib is a Python 2/3 library for scripting and extracting information
9from Kconfig (https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt)
10configuration systems.
11
12See the homepage at https://github.com/ulfalizer/Kconfiglib for a longer
13overview.
14
[cf2f109]15Since Kconfiglib 12.0.0, the library version is available in
16kconfiglib.VERSION, which is a (<major>, <minor>, <patch>) tuple, e.g.
17(12, 0, 0).
18
19
[f596dde]20Using Kconfiglib on the Linux kernel with the Makefile targets
21==============================================================
22
23For the Linux kernel, a handy interface is provided by the
24scripts/kconfig/Makefile patch, which can be applied with either 'git am' or
25the 'patch' utility:
26
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
29
30Warning: Not passing -p1 to patch will cause the wrong file to be patched.
31
32Please tell me if the patch does not apply. It should be trivial to apply
33manually, as it's just a block of text that needs to be inserted near the other
34*conf: targets in scripts/kconfig/Makefile.
35
36Look further down for a motivation for the Makefile patch and for instructions
37on how you can use Kconfiglib without it.
38
39If you do not wish to install Kconfiglib via pip, the Makefile patch is set up
40so that you can also just clone Kconfiglib into the kernel root:
41
42 $ git clone git://github.com/ulfalizer/Kconfiglib.git
43 $ git am Kconfiglib/makefile.patch (or 'patch -p1 < Kconfiglib/makefile.patch')
44
45Warning: The directory name Kconfiglib/ is significant in this case, because
46it's added to PYTHONPATH by the new targets in makefile.patch.
47
48The targets added by the Makefile patch are described in the following
49sections.
50
51
52make kmenuconfig
53----------------
54
[cf2f109]55This target runs the curses menuconfig interface with Python 3. As of
56Kconfiglib 12.2.0, both Python 2 and Python 3 are supported (previously, only
57Python 3 was supported, so this was a backport).
58
59
60make guiconfig
61--------------
62
63This target runs the Tkinter menuconfig interface. Both Python 2 and Python 3
64are supported. To change the Python interpreter used, pass
65PYTHONCMD=<executable> to 'make'. The default is 'python'.
[f596dde]66
67
68make [ARCH=<arch>] iscriptconfig
69--------------------------------
70
71This target gives an interactive Python prompt where a Kconfig instance has
72been preloaded and is available in 'kconf'. To change the Python interpreter
[cf2f109]73used, pass PYTHONCMD=<executable> to 'make'. The default is 'python'.
[f596dde]74
75To get a feel for the API, try evaluating and printing the symbols in
76kconf.defined_syms, and explore the MenuNode menu tree starting at
77kconf.top_node by following 'next' and 'list' pointers.
78
79The item contained in a menu node is found in MenuNode.item (note that this can
80be one of the constants kconfiglib.MENU and kconfiglib.COMMENT), and all
81symbols and choices have a 'nodes' attribute containing their menu nodes
82(usually only one). Printing a menu node will print its item, in Kconfig
83format.
84
85If you want to look up a symbol by name, use the kconf.syms dictionary.
86
87
88make scriptconfig SCRIPT=<script> [SCRIPT_ARG=<arg>]
89----------------------------------------------------
90
91This target runs the Python script given by the SCRIPT parameter on the
92configuration. 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
94argument, if given.
95
96See the examples/ subdirectory for example scripts.
97
98
99make dumpvarsconfig
100-------------------
101
102This target prints a list of all environment variables referenced from the
103Kconfig files, together with their values. See the
104Kconfiglib/examples/dumpvars.py script.
105
106Only environment variables that are referenced via the Kconfig preprocessor
107$(FOO) syntax are included. The preprocessor was added in Linux 4.18.
108
109
110Using Kconfiglib without the Makefile targets
111=============================================
112
113The make targets are only needed to pick up environment variables exported from
114the Kbuild makefiles and referenced inside Kconfig files, via e.g.
115'source "arch/$(SRCARCH)/Kconfig" and commands run via '$(shell,...)'.
116
117These variables are referenced as of writing (Linux 4.18), together with sample
118values:
119
120 srctree (.)
121 ARCH (x86)
122 SRCARCH (x86)
123 KERNELVERSION (4.18.0)
124 CC (gcc)
125 HOSTCC (gcc)
126 HOSTCXX (g++)
127 CC_VERSION_TEXT (gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0)
128
129Older kernels only reference ARCH, SRCARCH, and KERNELVERSION.
130
131If your kernel is recent enough (4.18+), you can get a list of referenced
132environment variables via 'make dumpvarsconfig' (see above). Note that this
133command is added by the Makefile patch.
134
135To run Kconfiglib without the Makefile patch, set the environment variables
136manually:
137
138 $ srctree=. ARCH=x86 SRCARCH=x86 KERNELVERSION=`make kernelversion` ... python(3)
139 >>> import kconfiglib
140 >>> kconf = kconfiglib.Kconfig() # filename defaults to "Kconfig"
141
142Search the top-level Makefile for "Additional ARCH settings" to see other
143possibilities for ARCH and SRCARCH.
144
145
146Intro to symbol values
147======================
148
149Kconfiglib has the same assignment semantics as the C implementation.
150
151Any symbol can be assigned a value by the user (via Kconfig.load_config() or
152Symbol.set_value()), but this user value is only respected if the symbol is
153visible, which corresponds to it (currently) being visible in the menuconfig
154interface.
155
156For symbols with prompts, the visibility of the symbol is determined by the
157condition on the prompt. Symbols without prompts are never visible, so setting
158a user value on them is pointless. A warning will be printed by default if
159Symbol.set_value() is called on a promptless symbol. Assignments to promptless
160symbols are normal within a .config file, so no similar warning will be printed
161by load_config().
162
163Dependencies from parents and 'if'/'depends on' are propagated to properties,
164including prompts, so these two configurations are logically equivalent:
165
166(1)
167
168 menu "menu"
169 depends on A
170
171 if B
172
173 config FOO
174 tristate "foo" if D
175 default y
176 depends on C
177
178 endif
179
180 endmenu
181
182(2)
183
184 menu "menu"
185 depends on A
186
187 config FOO
188 tristate "foo" if A && B && C && D
189 default y if A && B && C
190
191 endmenu
192
193In this example, A && B && C && D (the prompt condition) needs to be non-n for
194FOO to be visible (assignable). If its value is m, the symbol can only be
195assigned the value m: The visibility sets an upper bound on the value that can
196be assigned by the user, and any higher user value will be truncated down.
197
198'default' properties are independent of the visibility, though a 'default' will
199often 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
201value.
202
203Symbols with no user value (or that have a user value but are not visible) and
204no (active) 'default' default to n for bool/tristate symbols, and to the empty
205string for other symbol types.
206
207'select' works similarly to symbol visibility, but sets a lower bound on the
208value of the symbol. The lower bound is determined by the value of the
209select*ing* symbol. 'select' does not respect visibility, so non-visible
210symbols can be forced to a particular (minimum) value by a select as well.
211
212For non-bool/tristate symbols, it only matters whether the visibility is n or
213non-n: m visibility acts the same as y visibility.
214
215Conditions on 'default' and 'select' work in mostly intuitive ways. If the
216condition 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
218down to m.
219
220When writing a configuration with Kconfig.write_config(), only symbols that are
221visible, have an (active) default, or are selected will get written out (note
222that this includes all symbols that would accept user values). Kconfiglib
223matches the .config format produced by the C implementations down to the
224character. This eases testing.
225
226For a visible bool/tristate symbol FOO with value n, this line is written to
227.config:
228
229 # CONFIG_FOO is not set
230
231The point is to remember the user n selection (which might differ from the
232default value the symbol would get), while at the same sticking to the rule
233that undefined corresponds to n (.config uses Makefile format, making the line
234above a comment). When the .config file is read back in, this line will be
235treated the same as the following assignment:
236
237 CONFIG_FOO=n
238
239In Kconfiglib, the set of (currently) assignable values for a bool/tristate
240symbol appear in Symbol.assignable. For other symbol types, just check if
241sym.visibility is non-0 (non-n) to see whether the user value will have an
242effect.
243
244
245Intro to the menu tree
246======================
247
248The menu structure, as seen in e.g. menuconfig, is represented by a tree of
249MenuNode objects. The top node of the configuration corresponds to an implicit
250top-level menu, the title of which is shown at the top in the standard
251menuconfig interface. (The title is also available in Kconfig.mainmenu_text in
252Kconfiglib.)
253
254The top node is found in Kconfig.top_node. From there, you can visit child menu
255nodes by following the 'list' pointer, and any following menu nodes by
256following the 'next' pointer. Usually, a non-None 'list' pointer indicates a
257menu or Choice, but menu nodes for symbols can sometimes have a non-None 'list'
258pointer too due to submenus created implicitly from dependencies.
259
260MenuNode.item is either a Symbol or a Choice object, or one of the constants
261MENU and COMMENT. The prompt of the menu node can be found in MenuNode.prompt,
262which also holds the title for menus and comments. For Symbol and Choice,
263MenuNode.help holds the help text (if any, otherwise None).
264
265Most symbols will only have a single menu node. A symbol defined in multiple
266locations will have one menu node for each location. The list of menu nodes for
267a Symbol or Choice can be found in the Symbol/Choice.nodes attribute.
268
269Note that prompts and help texts for symbols and choices are stored in their
270menu node(s) rather than in the Symbol or Choice objects themselves. This makes
271it possible to define a symbol in multiple locations with a different prompt or
272help text in each location. To get the help text or prompt for a symbol with a
273single menu node, do sym.nodes[0].help and sym.nodes[0].prompt, respectively.
274The prompt is a (text, condition) tuple, where condition determines the
275visibility (see 'Intro to expressions' below).
276
277This organization mirrors the C implementation. MenuNode is called
278'struct menu' there, but I thought "menu" was a confusing name.
279
280It is possible to give a Choice a name and define it in multiple locations,
281hence why Choice.nodes is also a list.
282
283As a convenience, the properties added at a particular definition location are
284available on the MenuNode itself, in e.g. MenuNode.defaults. This is helpful
285when generating documentation, so that symbols/choices defined in multiple
286locations can be shown with the correct properties at each location.
287
288
289Intro to expressions
290====================
291
292Expressions can be evaluated with the expr_value() function and printed with
293the expr_str() function (these are used internally as well). Evaluating an
294expression always yields a tristate value, where n, m, and y are represented as
2950, 1, and 2, respectively.
296
297The following table should help you figure out how expressions are represented.
298A, B, C, ... are symbols (Symbol instances), NOT is the kconfiglib.NOT
299constant, etc.
300
301Expression Representation
302---------- --------------
303A A
304"A" A (constant symbol)
305!A (NOT, A)
306A && B (AND, A, B)
307A && B && C (AND, A, (AND, B, C))
308A || B (OR, A, B)
309A || (B && C && D) (OR, A, (AND, B, (AND, C, D)))
310A = B (EQUAL, A, B)
311A != "foo" (UNEQUAL, A, foo (constant symbol))
312A && B = C && D (AND, A, (AND, (EQUAL, B, C), D))
313n Kconfig.n (constant symbol)
314m Kconfig.m (constant symbol)
315y Kconfig.y (constant symbol)
316"y" Kconfig.y (constant symbol)
317
318Strings like "foo" in 'default "foo"' or 'depends on SYM = "foo"' are
319represented as constant symbols, so the only values that appear in expressions
320are symbols***. This mirrors the C implementation.
321
322***For choice symbols, the parent Choice will appear in expressions as well,
323but it's usually invisible as the value interfaces of Symbol and Choice are
324identical. This mirrors the C implementation and makes different choice modes
325"just work".
326
327Manual evaluation examples:
328
329 - The value of A && B is min(A.tri_value, B.tri_value)
330
331 - The value of A || B is max(A.tri_value, B.tri_value)
332
333 - The value of !A is 2 - A.tri_value
334
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.
337
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.
341
342n/m/y are automatically converted to the corresponding constant symbols
343"n"/"m"/"y" (Kconfig.n/m/y) during parsing.
344
345Kconfig.const_syms is a dictionary like Kconfig.syms but for constant symbols.
346
347If 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__()
349functions just avoid printing 'if y' conditions to give cleaner output.
350
351
352Kconfig extensions
353==================
354
355Kconfiglib includes a couple of Kconfig extensions:
356
357'source' with relative path
358---------------------------
359
360The 'rsource' statement sources Kconfig files with a path relative to directory
361of the Kconfig file containing the 'rsource' statement, instead of relative to
362the project root.
363
364Consider following directory tree:
365
366 Project
367 +--Kconfig
368 |
369 +--src
370 +--Kconfig
371 |
372 +--SubSystem1
373 +--Kconfig
374 |
375 +--ModuleA
376 +--Kconfig
377
378In this example, assume that src/SubSystem1/Kconfig wants to source
379src/SubSystem1/ModuleA/Kconfig.
380
381With 'source', this statement would be used:
382
383 source "src/SubSystem1/ModuleA/Kconfig"
384
385With 'rsource', this turns into
386
387 rsource "ModuleA/Kconfig"
388
389If an absolute path is given to 'rsource', it acts the same as 'source'.
390
391'rsource' can be used to create "position-independent" Kconfig trees that can
392be moved around freely.
393
394
395Globbing 'source'
396-----------------
397
398'source' and 'rsource' accept glob patterns, sourcing all matching Kconfig
[cf2f109]399files. They require at least one matching file, raising a KconfigError
[f596dde]400otherwise.
401
402For example, the following statement might source sub1/foofoofoo and
403sub2/foobarfoo:
404
405 source "sub[12]/foo*foo"
406
407The glob patterns accepted are the same as for the standard glob.glob()
408function.
409
410Two additional statements are provided for cases where it's acceptable for a
411pattern to match no files: 'osource' and 'orsource' (the o is for "optional").
412
413For example, the following statements will be no-ops if neither "foo" nor any
414files matching "bar*" exist:
415
416 osource "foo"
417 osource "bar*"
418
419'orsource' does a relative optional source.
420
421'source' and 'osource' are analogous to 'include' and '-include' in Make.
422
423
424Generalized def_* keywords
425--------------------------
426
427def_int, def_hex, and def_string are available in addition to def_bool and
428def_tristate, allowing int, hex, and string symbols to be given a type and a
429default at the same time.
430
431
432Extra optional warnings
433-----------------------
434
435Some optional warnings can be controlled via environment variables:
436
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.
441
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
445 tree though.
446
447 KCONFIG_STRICT is an older alias for this environment variable, supported
448 for backwards compatibility.
449
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.
453
[cf2f109]454 This warning can also be enabled/disabled via the Kconfig.warn_assign_undef
455 variable.
[f596dde]456
457
458Preprocessor user functions defined in Python
459---------------------------------------------
460
461Preprocessor functions can be defined in Python, which makes it simple to
462integrate information from existing Python tools into Kconfig (e.g. to have
463Kconfig symbols depend on hardware information stored in some other format).
464
465Putting a Python module named kconfigfunctions(.py) anywhere in sys.path will
466cause it to be imported by Kconfiglib (in Kconfig.__init__()). Note that
467sys.path can be customized via PYTHONPATH, and includes the directory of the
468module being run by default, as well as installation directories.
469
470If the KCONFIG_FUNCTIONS environment variable is set, it gives a different
471module name to use instead of 'kconfigfunctions'.
472
473The imported module is expected to define a global dictionary named 'functions'
474that maps function names to Python functions, as follows:
475
476 def my_fn(kconf, name, arg_1, arg_2, ...):
477 # kconf:
478 # Kconfig instance
479 #
480 # name:
481 # Name of the user-defined function ("my-fn"). Think argv[0].
482 #
483 # arg_1, arg_2, ...:
484 # Arguments passed to the function from Kconfig (strings)
485 #
486 # Returns a string to be substituted as the result of calling the
487 # function
488 ...
489
490 def my_other_fn(kconf, name, arg_1, arg_2, ...):
491 ...
492
493 functions = {
494 "my-fn": (my_fn, <min.args>, <max.args>/None),
495 "my-other-fn": (my_other_fn, <min.args>, <max.args>/None),
496 ...
497 }
498
499 ...
500
501<min.args> and <max.args> are the minimum and maximum number of arguments
502expected 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
504an invalid number of arguments will generate a KconfigError exception.
505
506Once defined, user functions can be called from Kconfig in the same way as
507other preprocessor functions:
508
509 config FOO
510 ...
511 depends on $(my-fn,arg1,arg2)
512
513If my_fn() returns "n", this will result in
514
515 config FOO
516 ...
517 depends on n
518
519Warning
520*******
521
522User-defined preprocessor functions are called as they're encountered at parse
523time, before all Kconfig files have been processed, and before the menu tree
524has been finalized. There are no guarantees that accessing Kconfig symbols or
525the menu tree via the 'kconf' parameter will work, and it could potentially
526lead to a crash. The 'kconf' parameter is provided for future extension (and
527because the predefined functions take it anyway).
528
529Preferably, user-defined functions should be stateless.
530
531
532Feedback
533========
534
535Send bug reports, suggestions, and questions to ulfalizer a.t Google's email
536service, or open a ticket on the GitHub page.
537"""
538import errno
539import importlib
540import os
541import re
542import sys
543
544# Get rid of some attribute lookups. These are obvious in context.
545from glob import iglob
[cf2f109]546from os.path import dirname, exists, expandvars, islink, join, realpath
547
548
549VERSION = (12, 4, 0)
[f596dde]550
551
552# File layout:
553#
554# Public classes
555# Public functions
556# Internal functions
557# Global constants
558
559# Line length: 79 columns
560
561
562#
563# Public classes
564#
565
566
567class Kconfig(object):
568 """
569 Represents a Kconfig configuration, e.g. for x86 or ARM. This is the set of
570 symbols, choices, and menu nodes appearing in the configuration. Creating
571 any number of Kconfig objects (including for different architectures) is
572 safe. Kconfiglib doesn't keep any global state.
573
574 The following attributes are available. They should be treated as
575 read-only, and some are implemented through @property magic.
576
577 syms:
578 A dictionary with all symbols in the configuration, indexed by name. Also
579 includes all symbols that are referenced in expressions but never
580 defined, except for constant (quoted) symbols.
581
582 Undefined symbols can be recognized by Symbol.nodes being empty -- see
583 the 'Intro to the menu tree' section in the module docstring.
584
585 const_syms:
586 A dictionary like 'syms' for constant (quoted) symbols
587
588 named_choices:
589 A dictionary like 'syms' for named choices (choice FOO)
590
591 defined_syms:
592 A list with all defined symbols, in the same order as they appear in the
593 Kconfig files. Symbols defined in multiple locations appear multiple
594 times.
595
596 Note: You probably want to use 'unique_defined_syms' instead. This
597 attribute is mostly maintained for backwards compatibility.
598
599 unique_defined_syms:
600 A list like 'defined_syms', but with duplicates removed. Just the first
601 instance is kept for symbols defined in multiple locations. Kconfig order
602 is preserved otherwise.
603
604 Using this attribute instead of 'defined_syms' can save work, and
605 automatically gives reasonable behavior when writing configuration output
606 (symbols defined in multiple locations only generate output once, while
607 still preserving Kconfig order for readability).
608
609 choices:
610 A list with all choices, in the same order as they appear in the Kconfig
611 files.
612
613 Note: You probably want to use 'unique_choices' instead. This attribute
614 is mostly maintained for backwards compatibility.
615
616 unique_choices:
617 Analogous to 'unique_defined_syms', for choices. Named choices can have
618 multiple definition locations.
619
620 menus:
621 A list with all menus, in the same order as they appear in the Kconfig
622 files
623
624 comments:
625 A list with all comments, in the same order as they appear in the Kconfig
626 files
627
628 kconfig_filenames:
629 A list with the filenames of all Kconfig files included in the
630 configuration, relative to $srctree (or relative to the current directory
631 if $srctree isn't set), except absolute paths (e.g.
632 'source "/foo/Kconfig"') are kept as-is.
633
634 The files are listed in the order they are source'd, starting with the
635 top-level Kconfig file. If a file is source'd multiple times, it will
636 appear multiple times. Use set() to get unique filenames.
637
[cf2f109]638 Note that Kconfig.sync_deps() already indirectly catches any file
639 modifications that change configuration output.
[f596dde]640
641 env_vars:
642 A set() with the names of all environment variables referenced in the
643 Kconfig files.
644
645 Only environment variables referenced with the preprocessor $(FOO) syntax
646 will be registered. The older $FOO syntax is only supported for backwards
647 compatibility.
648
649 Also note that $(FOO) won't be registered unless the environment variable
650 $FOO is actually set. If it isn't, $(FOO) is an expansion of an unset
651 preprocessor variable (which gives the empty string).
652
653 Another gotcha is that environment variables referenced in the values of
654 recursively expanded preprocessor variables (those defined with =) will
655 only be registered if the variable is actually used (expanded) somewhere.
656
657 The note from the 'kconfig_filenames' documentation applies here too.
658
659 n/m/y:
660 The predefined constant symbols n/m/y. Also available in const_syms.
661
662 modules:
663 The Symbol instance for the modules symbol. Currently hardcoded to
664 MODULES, which is backwards compatible. Kconfiglib will warn if
665 'option modules' is set on some other symbol. Tell me if you need proper
666 'option modules' support.
667
668 'modules' is never None. If the MODULES symbol is not explicitly defined,
669 its tri_value will be 0 (n), as expected.
670
671 A simple way to enable modules is to do 'kconf.modules.set_value(2)'
672 (provided the MODULES symbol is defined and visible). Modules are
673 disabled by default in the kernel Kconfig files as of writing, though
674 nearly all defconfig files enable them (with 'CONFIG_MODULES=y').
675
676 defconfig_list:
677 The Symbol instance for the 'option defconfig_list' symbol, or None if no
678 defconfig_list symbol exists. The defconfig filename derived from this
679 symbol can be found in Kconfig.defconfig_filename.
680
681 defconfig_filename:
682 The filename given by the defconfig_list symbol. This is taken from the
683 first 'default' with a satisfied condition where the specified file
684 exists (can be opened for reading). If a defconfig file foo/defconfig is
685 not found and $srctree was set when the Kconfig was created,
686 $srctree/foo/defconfig is looked up as well.
687
688 'defconfig_filename' is None if either no defconfig_list symbol exists,
689 or if the defconfig_list symbol has no 'default' with a satisfied
690 condition that specifies a file that exists.
691
692 Gotcha: scripts/kconfig/Makefile might pass --defconfig=<defconfig> to
693 scripts/kconfig/conf when running e.g. 'make defconfig'. This option
694 overrides the defconfig_list symbol, meaning defconfig_filename might not
695 always match what 'make defconfig' would use.
696
697 top_node:
698 The menu node (see the MenuNode class) of the implicit top-level menu.
699 Acts as the root of the menu tree.
700
701 mainmenu_text:
702 The prompt (title) of the top menu (top_node). Defaults to "Main menu".
703 Can be changed with the 'mainmenu' statement (see kconfig-language.txt).
704
705 variables:
706 A dictionary with all preprocessor variables, indexed by name. See the
707 Variable class.
708
[cf2f109]709 warn:
710 Set this variable to True/False to enable/disable warnings. See
711 Kconfig.__init__().
712
713 When 'warn' is False, the values of the other warning-related variables
714 are ignored.
715
716 This variable as well as the other warn* variables can be read to check
717 the current warning settings.
718
719 warn_to_stderr:
720 Set this variable to True/False to enable/disable warnings on stderr. See
721 Kconfig.__init__().
722
723 warn_assign_undef:
724 Set this variable to True to generate warnings for assignments to
725 undefined symbols in configuration files.
726
727 This variable is False by default unless the KCONFIG_WARN_UNDEF_ASSIGN
728 environment variable was set to 'y' when the Kconfig instance was
729 created.
730
731 warn_assign_override:
732 Set this variable to True to generate warnings for multiple assignments
733 to the same symbol in configuration files, where the assignments set
734 different values (e.g. CONFIG_FOO=m followed by CONFIG_FOO=y, where the
735 last value would get used).
736
737 This variable is True by default. Disabling it might be useful when
738 merging configurations.
739
740 warn_assign_redun:
741 Like warn_assign_override, but for multiple assignments setting a symbol
742 to the same value.
743
744 This variable is True by default. Disabling it might be useful when
745 merging configurations.
746
[f596dde]747 warnings:
[cf2f109]748 A list of strings containing all warnings that have been generated, for
749 cases where more flexibility is needed.
[f596dde]750
751 See the 'warn_to_stderr' parameter to Kconfig.__init__() and the
[cf2f109]752 Kconfig.warn_to_stderr variable as well. Note that warnings still get
753 added to Kconfig.warnings when 'warn_to_stderr' is True.
[f596dde]754
[cf2f109]755 Just as for warnings printed to stderr, only warnings that are enabled
756 will get added to Kconfig.warnings. See the various Kconfig.warn*
757 variables.
[f596dde]758
759 missing_syms:
760 A list with (name, value) tuples for all assignments to undefined symbols
761 within the most recently loaded .config file(s). 'name' is the symbol
762 name without the 'CONFIG_' prefix. 'value' is a string that gives the
763 right-hand side of the assignment verbatim.
764
765 See Kconfig.load_config() as well.
766
767 srctree:
768 The value of the $srctree environment variable when the configuration was
769 loaded, or the empty string if $srctree wasn't set. This gives nice
770 behavior with os.path.join(), which treats "" as the current directory,
771 without adding "./".
772
773 Kconfig files are looked up relative to $srctree (unless absolute paths
774 are used), and .config files are looked up relative to $srctree if they
775 are not found in the current directory. This is used to support
776 out-of-tree builds. The C tools use this environment variable in the same
777 way.
778
779 Changing $srctree after creating the Kconfig instance has no effect. Only
780 the value when the configuration is loaded matters. This avoids surprises
781 if multiple configurations are loaded with different values for $srctree.
782
783 config_prefix:
784 The value of the $CONFIG_ environment variable when the configuration was
785 loaded. This is the prefix used (and expected) on symbol names in .config
786 files and C headers. Defaults to "CONFIG_". Used in the same way in the C
787 tools.
788
789 Like for srctree, only the value of $CONFIG_ when the configuration is
790 loaded matters.
791 """
792 __slots__ = (
793 "_encoding",
794 "_functions",
795 "_set_match",
[cf2f109]796 "_srctree_prefix",
[f596dde]797 "_unset_match",
[cf2f109]798 "_warn_no_prompt",
[f596dde]799 "choices",
800 "comments",
801 "config_prefix",
802 "const_syms",
803 "defconfig_list",
804 "defined_syms",
805 "env_vars",
806 "kconfig_filenames",
807 "m",
808 "mainmenu_text",
809 "menus",
810 "missing_syms",
811 "modules",
812 "n",
813 "named_choices",
814 "srctree",
815 "syms",
816 "top_node",
817 "unique_choices",
818 "unique_defined_syms",
819 "variables",
[cf2f109]820 "warn",
821 "warn_assign_override",
822 "warn_assign_redun",
823 "warn_assign_undef",
824 "warn_to_stderr",
[f596dde]825 "warnings",
826 "y",
827
828 # Parsing-related
829 "_parsing_kconfigs",
830 "_readline",
831 "_filename",
832 "_linenr",
833 "_include_path",
834 "_filestack",
835 "_line",
836 "_tokens",
837 "_tokens_i",
838 "_reuse_tokens",
839 )
840
841 #
842 # Public interface
843 #
844
845 def __init__(self, filename="Kconfig", warn=True, warn_to_stderr=True,
846 encoding="utf-8"):
847 """
848 Creates a new Kconfig object by parsing Kconfig files.
849 Note that Kconfig files are not the same as .config files (which store
850 configuration symbol values).
851
852 See the module docstring for some environment variables that influence
853 default warning settings (KCONFIG_WARN_UNDEF and
854 KCONFIG_WARN_UNDEF_ASSIGN).
855
[cf2f109]856 Raises KconfigError on syntax/semantic errors, and (possibly a subclass
857 of) IOError on IO errors ('errno', 'strerror', and 'filename' are
[f596dde]858 available). Note that IOError can be caught as OSError on Python 3.
859
860 filename (default: "Kconfig"):
861 The Kconfig file to load. For the Linux kernel, you'll want "Kconfig"
862 from the top-level directory, as environment variables will make sure
863 the right Kconfig is included from there (arch/$SRCARCH/Kconfig as of
864 writing).
865
866 If $srctree is set, 'filename' will be looked up relative to it.
867 $srctree is also used to look up source'd files within Kconfig files.
868 See the class documentation.
869
870 If you are using Kconfiglib via 'make scriptconfig', the filename of
871 the base base Kconfig file will be in sys.argv[1]. It's currently
872 always "Kconfig" in practice.
873
874 warn (default: True):
875 True if warnings related to this configuration should be generated.
[cf2f109]876 This can be changed later by setting Kconfig.warn to True/False. It
[f596dde]877 is provided as a constructor argument since warnings might be
878 generated during parsing.
879
[cf2f109]880 See the other Kconfig.warn_* variables as well, which enable or
881 suppress certain warnings when warnings are enabled.
[f596dde]882
883 All generated warnings are added to the Kconfig.warnings list. See
884 the class documentation.
885
886 warn_to_stderr (default: True):
887 True if warnings should be printed to stderr in addition to being
888 added to Kconfig.warnings.
889
[cf2f109]890 This can be changed later by setting Kconfig.warn_to_stderr to
891 True/False.
[f596dde]892
893 encoding (default: "utf-8"):
894 The encoding to use when reading and writing files. If None, the
895 encoding specified in the current locale will be used.
896
897 The "utf-8" default avoids exceptions on systems that are configured
898 to use the C locale, which implies an ASCII encoding.
899
900 This parameter has no effect on Python 2, due to implementation
901 issues (regular strings turning into Unicode strings, which are
902 distinct in Python 2). Python 2 doesn't decode regular strings
903 anyway.
904
905 Related PEP: https://www.python.org/dev/peps/pep-0538/
906 """
907 self.srctree = os.environ.get("srctree", "")
[cf2f109]908 # A prefix we can reliably strip from glob() results to get a filename
909 # relative to $srctree. relpath() can cause issues for symlinks,
910 # because it assumes symlink/../foo is the same as foo/.
911 self._srctree_prefix = realpath(self.srctree) + os.sep
912
[f596dde]913 self.config_prefix = os.environ.get("CONFIG_", "CONFIG_")
914
915 # Regular expressions for parsing .config files
916 self._set_match = _re_match(self.config_prefix + r"([^=]+)=(.*)")
917 self._unset_match = \
918 _re_match(r"# {}([^ ]+) is not set".format(self.config_prefix))
919
920
921 self.warnings = []
922
[cf2f109]923 self.warn = warn
924 self.warn_to_stderr = warn_to_stderr
925 self.warn_assign_undef = \
[f596dde]926 os.environ.get("KCONFIG_WARN_UNDEF_ASSIGN") == "y"
[cf2f109]927 self.warn_assign_override = self.warn_assign_redun = True
[f596dde]928
929
930 self._encoding = encoding
931
932
933 self.syms = {}
934 self.const_syms = {}
935 self.defined_syms = []
936
937 self.missing_syms = []
938
939 self.named_choices = {}
940 self.choices = []
941
942 self.menus = []
943 self.comments = []
944
945 for nmy in "n", "m", "y":
946 sym = Symbol()
947 sym.kconfig = self
948 sym.name = nmy
949 sym.is_constant = True
950 sym.orig_type = TRISTATE
951 sym._cached_tri_val = STR_TO_TRI[nmy]
952
953 self.const_syms[nmy] = sym
954
955 self.n = self.const_syms["n"]
956 self.m = self.const_syms["m"]
957 self.y = self.const_syms["y"]
958
959 # Make n/m/y well-formed symbols
960 for nmy in "n", "m", "y":
961 sym = self.const_syms[nmy]
962 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
963
964
965 # Maps preprocessor variables names to Variable instances
966 self.variables = {}
967
968 # Predefined preprocessor functions, with min/max number of arguments
969 self._functions = {
970 "info": (_info_fn, 1, 1),
971 "error-if": (_error_if_fn, 2, 2),
972 "filename": (_filename_fn, 0, 0),
973 "lineno": (_lineno_fn, 0, 0),
974 "shell": (_shell_fn, 1, 1),
975 "warning-if": (_warning_if_fn, 2, 2),
976 }
977
978 # Add any user-defined preprocessor functions
979 try:
980 self._functions.update(
981 importlib.import_module(
982 os.environ.get("KCONFIG_FUNCTIONS", "kconfigfunctions")
983 ).functions)
984 except ImportError:
985 pass
986
987
988 # This is used to determine whether previously unseen symbols should be
989 # registered. They shouldn't be if we parse expressions after parsing,
990 # as part of Kconfig.eval_string().
991 self._parsing_kconfigs = True
992
993 self.modules = self._lookup_sym("MODULES")
994 self.defconfig_list = None
995
996 self.top_node = MenuNode()
997 self.top_node.kconfig = self
998 self.top_node.item = MENU
999 self.top_node.is_menuconfig = True
1000 self.top_node.visibility = self.y
1001 self.top_node.prompt = ("Main menu", self.y)
1002 self.top_node.parent = None
1003 self.top_node.dep = self.y
1004 self.top_node.filename = filename
1005 self.top_node.linenr = 1
1006 self.top_node.include_path = ()
1007
1008 # Parse the Kconfig files
1009
1010 # Not used internally. Provided as a convenience.
1011 self.kconfig_filenames = [filename]
1012 self.env_vars = set()
1013
1014 # Used to avoid retokenizing lines when we discover that they're not
1015 # part of the construct currently being parsed. This is kinda like an
1016 # unget operation.
1017 self._reuse_tokens = False
1018
1019 # Keeps track of the location in the parent Kconfig files. Kconfig
1020 # files usually source other Kconfig files. See _enter_file().
1021 self._filestack = []
1022 self._include_path = ()
1023
1024 # The current parsing location
1025 self._filename = filename
1026 self._linenr = 0
1027
1028 # Open the top-level Kconfig file. Store the readline() method directly
1029 # as a small optimization.
1030 self._readline = self._open(join(self.srctree, filename), "r").readline
1031
1032 try:
1033 # Parse everything
1034 self._parse_block(None, self.top_node, self.top_node)
1035 except UnicodeDecodeError as e:
1036 _decoding_error(e, self._filename)
1037
1038 # Close the top-level Kconfig file. __self__ fetches the 'file' object
1039 # for the method.
1040 self._readline.__self__.close()
1041
1042 self.top_node.list = self.top_node.next
1043 self.top_node.next = None
1044
1045 self._parsing_kconfigs = False
1046
1047 self.unique_defined_syms = _ordered_unique(self.defined_syms)
1048 self.unique_choices = _ordered_unique(self.choices)
1049
1050 # Do various post-processing on the menu tree
1051 self._finalize_tree(self.top_node, self.y)
1052
1053
1054 # Do sanity checks. Some of these depend on everything being finalized.
1055 self._check_sym_sanity()
1056 self._check_choice_sanity()
1057
1058 # KCONFIG_STRICT is an older alias for KCONFIG_WARN_UNDEF, supported
1059 # for backwards compatibility
1060 if os.environ.get("KCONFIG_WARN_UNDEF") == "y" or \
1061 os.environ.get("KCONFIG_STRICT") == "y":
1062
1063 self._check_undef_syms()
1064
1065
1066 # Build Symbol._dependents for all symbols and choices
1067 self._build_dep()
1068
1069 # Check for dependency loops
1070 check_dep_loop_sym = _check_dep_loop_sym # Micro-optimization
1071 for sym in self.unique_defined_syms:
1072 check_dep_loop_sym(sym, False)
1073
1074 # Add extra dependencies from choices to choice symbols that get
1075 # awkward during dependency loop detection
1076 self._add_choice_deps()
1077
1078
[cf2f109]1079 self._warn_no_prompt = True
[f596dde]1080
1081 self.mainmenu_text = self.top_node.prompt[0]
1082
1083 @property
1084 def defconfig_filename(self):
1085 """
1086 See the class documentation.
1087 """
1088 if self.defconfig_list:
1089 for filename, cond in self.defconfig_list.defaults:
1090 if expr_value(cond):
1091 try:
1092 with self._open_config(filename.str_value) as f:
1093 return f.name
1094 except IOError:
1095 continue
1096
1097 return None
1098
[cf2f109]1099 def load_config(self, filename=None, replace=True, verbose=None):
[f596dde]1100 """
1101 Loads symbol values from a file in the .config format. Equivalent to
1102 calling Symbol.set_value() to set each of the values.
1103
1104 "# CONFIG_FOO is not set" within a .config file sets the user value of
1105 FOO to n. The C tools work the same way.
1106
1107 For each symbol, the Symbol.user_value attribute holds the value the
1108 symbol was assigned in the .config file (if any). The user value might
1109 differ from Symbol.str/tri_value if there are unsatisfied dependencies.
1110
1111 Calling this function also updates the Kconfig.missing_syms attribute
1112 with a list of all assignments to undefined symbols within the
1113 configuration file. Kconfig.missing_syms is cleared if 'replace' is
1114 True, and appended to otherwise. See the documentation for
1115 Kconfig.missing_syms as well.
1116
1117 Raises (possibly a subclass of) IOError on IO errors ('errno',
1118 'strerror', and 'filename' are available). Note that IOError can be
1119 caught as OSError on Python 3.
1120
1121 filename (default: None):
1122 Path to load configuration from (a string). Respects $srctree if set
1123 (see the class documentation).
1124
1125 If 'filename' is None (the default), the configuration file to load
1126 (if any) is calculated automatically, giving the behavior you'd
1127 usually want:
1128
1129 1. If the KCONFIG_CONFIG environment variable is set, it gives the
1130 path to the configuration file to load. Otherwise, ".config" is
1131 used. See standard_config_filename().
1132
1133 2. If the path from (1.) doesn't exist, the configuration file
1134 given by kconf.defconfig_filename is loaded instead, which is
1135 derived from the 'option defconfig_list' symbol.
1136
1137 3. If (1.) and (2.) fail to find a configuration file to load, no
1138 configuration file is loaded, and symbols retain their current
1139 values (e.g., their default values). This is not an error.
1140
1141 See the return value as well.
1142
1143 replace (default: True):
1144 If True, all existing user values will be cleared before loading the
1145 .config. Pass False to merge configurations.
1146
[cf2f109]1147 verbose (default: None):
1148 Limited backwards compatibility to prevent crashes. A warning is
1149 printed if anything but None is passed.
1150
1151 Prior to Kconfiglib 12.0.0, this option enabled printing of messages
1152 to stdout when 'filename' was None. A message is (always) returned
1153 now instead, which is more flexible.
[f596dde]1154
[cf2f109]1155 Will probably be removed in some future version.
1156
1157 Returns a string with a message saying which file got loaded (or
1158 possibly that no file got loaded, when 'filename' is None). This is
1159 meant to reduce boilerplate in tools, which can do e.g.
1160 print(kconf.load_config()). The returned message distinguishes between
1161 loading (replace == True) and merging (replace == False).
[f596dde]1162 """
[cf2f109]1163 if verbose is not None:
1164 _warn_verbose_deprecated("load_config")
1165
1166 msg = None
[f596dde]1167 if filename is None:
1168 filename = standard_config_filename()
[cf2f109]1169 if not exists(filename) and \
1170 not exists(join(self.srctree, filename)):
1171 defconfig = self.defconfig_filename
1172 if defconfig is None:
1173 return "Using default symbol values (no '{}')" \
1174 .format(filename)
[f596dde]1175
[cf2f109]1176 msg = " default configuration '{}' (no '{}')" \
1177 .format(defconfig, filename)
1178 filename = defconfig
[f596dde]1179
[cf2f109]1180 if not msg:
1181 msg = " configuration '{}'".format(filename)
[f596dde]1182
1183 # Disable the warning about assigning to symbols without prompts. This
1184 # is normal and expected within a .config file.
[cf2f109]1185 self._warn_no_prompt = False
[f596dde]1186
[cf2f109]1187 # This stub only exists to make sure _warn_no_prompt gets reenabled
[f596dde]1188 try:
1189 self._load_config(filename, replace)
1190 except UnicodeDecodeError as e:
1191 _decoding_error(e, filename)
1192 finally:
[cf2f109]1193 self._warn_no_prompt = True
[f596dde]1194
[cf2f109]1195 return ("Loaded" if replace else "Merged") + msg
[f596dde]1196
1197 def _load_config(self, filename, replace):
1198 with self._open_config(filename) as f:
1199 if replace:
1200 self.missing_syms = []
1201
1202 # If we're replacing the configuration, keep track of which
1203 # symbols and choices got set so that we can unset the rest
1204 # later. This avoids invalidating everything and is faster.
1205 # Another benefit is that invalidation must be rock solid for
1206 # it to work, making it a good test.
1207
1208 for sym in self.unique_defined_syms:
1209 sym._was_set = False
1210
1211 for choice in self.unique_choices:
1212 choice._was_set = False
1213
1214 # Small optimizations
1215 set_match = self._set_match
1216 unset_match = self._unset_match
1217 syms = self.syms
1218
1219 for linenr, line in enumerate(f, 1):
1220 # The C tools ignore trailing whitespace
1221 line = line.rstrip()
1222
1223 match = set_match(line)
1224 if match:
1225 name, val = match.groups()
1226 if name not in syms:
1227 self._undef_assign(name, val, filename, linenr)
1228 continue
1229
1230 sym = syms[name]
1231 if not sym.nodes:
1232 self._undef_assign(name, val, filename, linenr)
1233 continue
1234
1235 if sym.orig_type in _BOOL_TRISTATE:
1236 # The C implementation only checks the first character
1237 # to the right of '=', for whatever reason
1238 if not ((sym.orig_type is BOOL and
1239 val.startswith(("y", "n"))) or
1240 (sym.orig_type is TRISTATE and
1241 val.startswith(("y", "m", "n")))):
1242 self._warn("'{}' is not a valid value for the {} "
1243 "symbol {}. Assignment ignored."
1244 .format(val, TYPE_TO_STR[sym.orig_type],
1245 _name_and_loc(sym)),
1246 filename, linenr)
1247 continue
1248
1249 val = val[0]
1250
1251 if sym.choice and val != "n":
1252 # During .config loading, we infer the mode of the
1253 # choice from the kind of values that are assigned
1254 # to the choice symbols
1255
1256 prev_mode = sym.choice.user_value
1257 if prev_mode is not None and \
1258 TRI_TO_STR[prev_mode] != val:
1259
1260 self._warn("both m and y assigned to symbols "
1261 "within the same choice",
1262 filename, linenr)
1263
1264 # Set the choice's mode
1265 sym.choice.set_value(val)
1266
1267 elif sym.orig_type is STRING:
1268 match = _conf_string_match(val)
1269 if not match:
1270 self._warn("malformed string literal in "
1271 "assignment to {}. Assignment ignored."
1272 .format(_name_and_loc(sym)),
1273 filename, linenr)
1274 continue
1275
1276 val = unescape(match.group(1))
1277
1278 else:
1279 match = unset_match(line)
1280 if not match:
1281 # Print a warning for lines that match neither
1282 # set_match() nor unset_match() and that are not blank
1283 # lines or comments. 'line' has already been
1284 # rstrip()'d, so blank lines show up as "" here.
1285 if line and not line.lstrip().startswith("#"):
1286 self._warn("ignoring malformed line '{}'"
1287 .format(line),
1288 filename, linenr)
1289
1290 continue
1291
1292 name = match.group(1)
1293 if name not in syms:
1294 self._undef_assign(name, "n", filename, linenr)
1295 continue
1296
1297 sym = syms[name]
1298 if not sym.nodes:
1299 self._undef_assign(name, "n", filename, linenr)
1300 continue
1301
1302 if sym.orig_type not in _BOOL_TRISTATE:
1303 continue
1304
1305 val = "n"
1306
1307 # Done parsing the assignment. Set the value.
1308
1309 if sym._was_set:
1310 # Use strings for bool/tristate user values in the warning
1311 if sym.orig_type in _BOOL_TRISTATE:
1312 display_user_val = TRI_TO_STR[sym.user_value]
1313 else:
1314 display_user_val = sym.user_value
1315
[cf2f109]1316 msg = '{} set more than once. Old value "{}", new value "{}".'.format(
[f596dde]1317 _name_and_loc(sym), display_user_val, val
1318 )
1319
1320 if display_user_val == val:
[cf2f109]1321 if self.warn_assign_redun:
1322 self._warn(msg, filename, linenr)
1323 elif self.warn_assign_override:
1324 self._warn(msg, filename, linenr)
[f596dde]1325
1326 sym.set_value(val)
1327
1328 if replace:
1329 # If we're replacing the configuration, unset the symbols that
1330 # didn't get set
1331
1332 for sym in self.unique_defined_syms:
1333 if not sym._was_set:
1334 sym.unset_value()
1335
1336 for choice in self.unique_choices:
1337 if not choice._was_set:
1338 choice.unset_value()
1339
1340 def _undef_assign(self, name, val, filename, linenr):
1341 # Called for assignments to undefined symbols during .config loading
1342
1343 self.missing_syms.append((name, val))
[cf2f109]1344 if self.warn_assign_undef:
[f596dde]1345 self._warn(
1346 "attempt to assign the value '{}' to the undefined symbol {}"
1347 .format(val, name), filename, linenr)
1348
1349 def write_autoconf(self, filename,
1350 header="/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
1351 r"""
1352 Writes out symbol values as a C header file, matching the format used
1353 by include/generated/autoconf.h in the kernel.
1354
1355 The ordering of the #defines matches the one generated by
1356 write_config(). The order in the C implementation depends on the hash
1357 table implementation as of writing, and so won't match.
1358
[cf2f109]1359 If 'filename' exists and its contents is identical to what would get
1360 written out, it is left untouched. This avoids updating file metadata
1361 like the modification time and possibly triggering redundant work in
1362 build tools.
1363
[f596dde]1364 filename:
1365 Self-explanatory.
1366
1367 header (default: "/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n"):
1368 Text that will be inserted verbatim at the beginning of the file. You
1369 would usually want it enclosed in '/* */' to make it a C comment,
1370 and include a final terminating newline.
1371 """
[cf2f109]1372 self._write_if_changed(filename, self._autoconf_contents(header))
[f596dde]1373
[cf2f109]1374 def _autoconf_contents(self, header):
1375 # write_autoconf() helper. Returns the contents to write as a string,
1376 # with 'header' at the beginning.
[f596dde]1377
[cf2f109]1378 # "".join()ed later
1379 chunks = [header]
1380 add = chunks.append
1381
1382 for sym in self.unique_defined_syms:
1383 # _write_to_conf is determined when the value is calculated. This
1384 # is a hidden function call due to property magic.
1385 val = sym.str_value
1386 if not sym._write_to_conf:
1387 continue
1388
1389 if sym.orig_type in _BOOL_TRISTATE:
1390 if val == "y":
1391 add("#define {}{} 1\n"
1392 .format(self.config_prefix, sym.name))
1393 elif val == "m":
1394 add("#define {}{}_MODULE 1\n"
1395 .format(self.config_prefix, sym.name))
1396
1397 elif sym.orig_type is STRING:
1398 add('#define {}{} "{}"\n'
1399 .format(self.config_prefix, sym.name, escape(val)))
1400
1401 else: # sym.orig_type in _INT_HEX:
1402 if sym.orig_type is HEX and \
1403 not val.startswith(("0x", "0X")):
1404 val = "0x" + val
[f596dde]1405
[cf2f109]1406 add("#define {}{} {}\n"
1407 .format(self.config_prefix, sym.name, val))
[f596dde]1408
[cf2f109]1409 return "".join(chunks)
[f596dde]1410
1411 def write_config(self, filename=None,
1412 header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n",
[cf2f109]1413 save_old=True, verbose=None):
[f596dde]1414 r"""
1415 Writes out symbol values in the .config format. The format matches the
1416 C implementation, including ordering.
1417
1418 Symbols appear in the same order in generated .config files as they do
1419 in the Kconfig files. For symbols defined in multiple locations, a
1420 single assignment is written out corresponding to the first location
1421 where the symbol is defined.
1422
1423 See the 'Intro to symbol values' section in the module docstring to
1424 understand which symbols get written out.
1425
[cf2f109]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
1429 build tools.
1430
[f596dde]1431 filename (default: None):
1432 Filename to save configuration to (a string).
1433
[cf2f109]1434 If None (the default), the filename in the environment variable
[f596dde]1435 KCONFIG_CONFIG is used if set, and ".config" otherwise. See
1436 standard_config_filename().
1437
1438 header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
1439 Text that will be inserted verbatim at the beginning of the file. You
1440 would usually want each line to start with '#' to make it a comment,
1441 and include a final terminating newline.
1442
1443 save_old (default: True):
1444 If True and <filename> already exists, a copy of it will be saved to
[cf2f109]1445 <filename>.old in the same directory before the new configuration is
1446 written.
1447
1448 Errors are silently ignored if <filename>.old cannot be written (e.g.
1449 due to being a directory, or <filename> being something like
1450 /dev/null).
1451
1452 verbose (default: None):
1453 Limited backwards compatibility to prevent crashes. A warning is
1454 printed if anything but None is passed.
1455
1456 Prior to Kconfiglib 12.0.0, this option enabled printing of messages
1457 to stdout when 'filename' was None. A message is (always) returned
1458 now instead, which is more flexible.
[f596dde]1459
[cf2f109]1460 Will probably be removed in some future version.
[f596dde]1461
[cf2f109]1462 Returns a string with a message saying which file got saved. This is
1463 meant to reduce boilerplate in tools, which can do e.g.
1464 print(kconf.write_config()).
[f596dde]1465 """
[cf2f109]1466 if verbose is not None:
1467 _warn_verbose_deprecated("write_config")
1468
[f596dde]1469 if filename is None:
1470 filename = standard_config_filename()
[cf2f109]1471
1472 contents = self._config_contents(header)
1473 if self._contents_eq(filename, contents):
1474 return "No change to '{}'".format(filename)
[f596dde]1475
1476 if save_old:
1477 _save_old(filename)
1478
1479 with self._open(filename, "w") as f:
[cf2f109]1480 f.write(contents)
1481
1482 return "Configuration saved to '{}'".format(filename)
[f596dde]1483
[cf2f109]1484 def _config_contents(self, header):
1485 # write_config() helper. Returns the contents to write as a string,
1486 # with 'header' at the beginning.
1487 #
1488 # More memory friendly would be to 'yield' the strings and
1489 # "".join(_config_contents()), but it was a bit slower on my system.
1490
1491 # node_iter() was used here before commit 3aea9f7 ("Add '# end of
1492 # <menu>' after menus in .config"). Those comments get tricky to
1493 # implement with it.
[f596dde]1494
[cf2f109]1495 for sym in self.unique_defined_syms:
1496 sym._visited = False
[f596dde]1497
[cf2f109]1498 # Did we just print an '# end of ...' comment?
1499 after_end_comment = False
[f596dde]1500
[cf2f109]1501 # "".join()ed later
1502 chunks = [header]
1503 add = chunks.append
[f596dde]1504
[cf2f109]1505 node = self.top_node
1506 while 1:
1507 # Jump to the next node with an iterative tree walk
1508 if node.list:
1509 node = node.list
1510 elif node.next:
1511 node = node.next
1512 else:
1513 while node.parent:
1514 node = node.parent
1515
1516 # Add a comment when leaving visible menus
1517 if node.item is MENU and expr_value(node.dep) and \
1518 expr_value(node.visibility) and \
1519 node is not self.top_node:
1520 add("# end of {}\n".format(node.prompt[0]))
1521 after_end_comment = True
1522
1523 if node.next:
1524 node = node.next
1525 break
1526 else:
1527 # No more nodes
1528 return "".join(chunks)
1529
1530 # Generate configuration output for the node
1531
1532 item = node.item
1533
1534 if item.__class__ is Symbol:
1535 if item._visited:
1536 continue
1537 item._visited = True
1538
1539 conf_string = item.config_string
1540 if not conf_string:
1541 continue
1542
1543 if after_end_comment:
1544 # Add a blank line before the first symbol printed after an
1545 # '# end of ...' comment
1546 after_end_comment = False
1547 add("\n")
1548 add(conf_string)
1549
1550 elif expr_value(node.dep) and \
1551 ((item is MENU and expr_value(node.visibility)) or
1552 item is COMMENT):
1553
1554 add("\n#\n# {}\n#\n".format(node.prompt[0]))
1555 after_end_comment = False
[f596dde]1556
1557 def write_min_config(self, filename,
1558 header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
1559 """
1560 Writes out a "minimal" configuration file, omitting symbols whose value
1561 matches their default value. The format matches the one produced by
1562 'make savedefconfig'.
1563
1564 The resulting configuration file is incomplete, but a complete
1565 configuration can be derived from it by loading it. Minimal
1566 configuration files can serve as a more manageable configuration format
1567 compared to a "full" .config file, especially when configurations files
1568 are merged or edited by hand.
1569
1570 filename:
1571 Self-explanatory.
1572
1573 header (default: "# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
1574 Text that will be inserted verbatim at the beginning of the file. You
1575 would usually want each line to start with '#' to make it a comment,
1576 and include a final terminating newline.
[cf2f109]1577
1578 Returns a string with a message saying which file got saved. This is
1579 meant to reduce boilerplate in tools, which can do e.g.
1580 print(kconf.write_min_config()).
[f596dde]1581 """
[cf2f109]1582 contents = self._min_config_contents(header)
1583 if self._contents_eq(filename, contents):
1584 return "No change to '{}'".format(filename)
1585
[f596dde]1586 with self._open(filename, "w") as f:
[cf2f109]1587 f.write(contents)
[f596dde]1588
[cf2f109]1589 return "Minimal configuration saved to '{}'".format(filename)
[f596dde]1590
[cf2f109]1591 def _min_config_contents(self, header):
1592 # write_min_config() helper. Returns the contents to write as a string,
1593 # with 'header' at the beginning.
[f596dde]1594
[cf2f109]1595 chunks = [header]
1596 add = chunks.append
[f596dde]1597
[cf2f109]1598 for sym in self.unique_defined_syms:
1599 # Skip symbols that cannot be changed. Only check
1600 # non-choice symbols, as selects don't affect choice
1601 # symbols.
1602 if not sym.choice and \
1603 sym.visibility <= expr_value(sym.rev_dep):
1604 continue
1605
1606 # Skip symbols whose value matches their default
1607 if sym.str_value == sym._str_default():
1608 continue
1609
1610 # Skip symbols that would be selected by default in a
1611 # choice, unless the choice is optional or the symbol type
1612 # isn't bool (it might be possible to set the choice mode
1613 # to n or the symbol to m in those cases).
1614 if sym.choice and \
1615 not sym.choice.is_optional and \
1616 sym.choice._get_selection_from_defaults() is sym and \
1617 sym.orig_type is BOOL and \
1618 sym.tri_value == 2:
1619 continue
1620
1621 add(sym.config_string)
1622
1623 return "".join(chunks)
[f596dde]1624
1625 def sync_deps(self, path):
1626 """
1627 Creates or updates a directory structure that can be used to avoid
1628 doing a full rebuild whenever the configuration is changed, mirroring
1629 include/config/ in the kernel.
1630
1631 This function is intended to be called during each build, before
1632 compiling source files that depend on configuration symbols.
1633
1634 path:
1635 Path to directory
1636
1637 sync_deps(path) does the following:
1638
1639 1. If the directory <path> does not exist, it is created.
1640
1641 2. If <path>/auto.conf exists, old symbol values are loaded from it,
1642 which are then compared against the current symbol values. If a
1643 symbol has changed value (would generate different output in
1644 autoconf.h compared to before), the change is signaled by
1645 touch'ing a file corresponding to the symbol.
1646
1647 The first time sync_deps() is run on a directory, <path>/auto.conf
1648 won't exist, and no old symbol values will be available. This
1649 logically has the same effect as updating the entire
1650 configuration.
1651
1652 The path to a symbol's file is calculated from the symbol's name
1653 by replacing all '_' with '/' and appending '.h'. For example, the
1654 symbol FOO_BAR_BAZ gets the file <path>/foo/bar/baz.h, and FOO
1655 gets the file <path>/foo.h.
1656
1657 This scheme matches the C tools. The point is to avoid having a
1658 single directory with a huge number of files, which the underlying
1659 filesystem might not handle well.
1660
1661 3. A new auto.conf with the current symbol values is written, to keep
1662 track of them for the next build.
1663
[cf2f109]1664 If auto.conf exists and its contents is identical to what would
1665 get written out, it is left untouched. This avoids updating file
1666 metadata like the modification time and possibly triggering
1667 redundant work in build tools.
1668
[f596dde]1669
1670 The last piece of the puzzle is knowing what symbols each source file
1671 depends on. Knowing that, dependencies can be added from source files
1672 to the files corresponding to the symbols they depends on. The source
1673 file will then get recompiled (only) when the symbol value changes
1674 (provided sync_deps() is run first during each build).
1675
1676 The tool in the kernel that extracts symbol dependencies from source
1677 files is scripts/basic/fixdep.c. Missing symbol files also correspond
1678 to "not changed", which fixdep deals with by using the $(wildcard) Make
1679 function when adding symbol prerequisites to source files.
1680
1681 In case you need a different scheme for your project, the sync_deps()
1682 implementation can be used as a template.
1683 """
1684 if not exists(path):
1685 os.mkdir(path, 0o755)
1686
1687 # Load old values from auto.conf, if any
[cf2f109]1688 self._load_old_vals(path)
[f596dde]1689
1690 for sym in self.unique_defined_syms:
[cf2f109]1691 # _write_to_conf is determined when the value is calculated. This
1692 # is a hidden function call due to property magic.
[f596dde]1693 val = sym.str_value
1694
[cf2f109]1695 # n tristate values do not get written to auto.conf and autoconf.h,
1696 # making a missing symbol logically equivalent to n
[f596dde]1697
1698 if sym._write_to_conf:
1699 if sym._old_val is None and \
1700 sym.orig_type in _BOOL_TRISTATE and \
1701 val == "n":
1702 # No old value (the symbol was missing or n), new value n.
1703 # No change.
1704 continue
1705
1706 if val == sym._old_val:
1707 # New value matches old. No change.
1708 continue
1709
1710 elif sym._old_val is None:
1711 # The symbol wouldn't appear in autoconf.h (because
1712 # _write_to_conf is false), and it wouldn't have appeared in
1713 # autoconf.h previously either (because it didn't appear in
1714 # auto.conf). No change.
1715 continue
1716
1717 # 'sym' has a new value. Flag it.
[cf2f109]1718 _touch_dep_file(path, sym.name)
[f596dde]1719
1720 # Remember the current values as the "new old" values.
1721 #
1722 # This call could go anywhere after the call to _load_old_vals(), but
1723 # putting it last means _sync_deps() can be safely rerun if it fails
1724 # before this point.
[cf2f109]1725 self._write_old_vals(path)
[f596dde]1726
[cf2f109]1727 def _load_old_vals(self, path):
[f596dde]1728 # Loads old symbol values from auto.conf into a dedicated
1729 # Symbol._old_val field. Mirrors load_config().
1730 #
1731 # The extra field could be avoided with some trickery involving dumping
1732 # symbol values and restoring them later, but this is simpler and
1733 # faster. The C tools also use a dedicated field for this purpose.
1734
1735 for sym in self.unique_defined_syms:
1736 sym._old_val = None
1737
[cf2f109]1738 try:
1739 auto_conf = self._open(join(path, "auto.conf"), "r")
1740 except IOError as e:
1741 if e.errno == errno.ENOENT:
1742 # No old values
1743 return
1744 raise
[f596dde]1745
[cf2f109]1746 with auto_conf as f:
[f596dde]1747 for line in f:
1748 match = self._set_match(line)
1749 if not match:
1750 # We only expect CONFIG_FOO=... (and possibly a header
1751 # comment) in auto.conf
1752 continue
1753
1754 name, val = match.groups()
1755 if name in self.syms:
1756 sym = self.syms[name]
1757
1758 if sym.orig_type is STRING:
1759 match = _conf_string_match(val)
1760 if not match:
1761 continue
1762 val = unescape(match.group(1))
1763
1764 self.syms[name]._old_val = val
1765 else:
1766 # Flag that the symbol no longer exists, in
1767 # case something still depends on it
[cf2f109]1768 _touch_dep_file(path, name)
1769
1770 def _write_old_vals(self, path):
1771 # Helper for writing auto.conf. Basically just a simplified
1772 # write_config() that doesn't write any comments (including
1773 # '# CONFIG_FOO is not set' comments). The format matches the C
1774 # implementation, though the ordering is arbitrary there (depends on
1775 # the hash table implementation).
1776 #
1777 # A separate helper function is neater than complicating write_config()
1778 # by passing a flag to it, plus we only need to look at symbols here.
1779
1780 self._write_if_changed(
1781 os.path.join(path, "auto.conf"),
1782 self._old_vals_contents())
1783
1784 def _old_vals_contents(self):
1785 # _write_old_vals() helper. Returns the contents to write as a string.
1786
1787 # Temporary list instead of generator makes this a bit faster
1788 return "".join([
1789 sym.config_string for sym in self.unique_defined_syms
1790 if not (sym.orig_type in _BOOL_TRISTATE and not sym.tri_value)
1791 ])
[f596dde]1792
1793 def node_iter(self, unique_syms=False):
1794 """
1795 Returns a generator for iterating through all MenuNode's in the Kconfig
1796 tree. The iteration is done in Kconfig definition order (each node is
1797 visited before its children, and the children of a node are visited
1798 before the next node).
1799
1800 The Kconfig.top_node menu node is skipped. It contains an implicit menu
1801 that holds the top-level items.
1802
1803 As an example, the following code will produce a list equal to
1804 Kconfig.defined_syms:
1805
1806 defined_syms = [node.item for node in kconf.node_iter()
1807 if isinstance(node.item, Symbol)]
1808
1809 unique_syms (default: False):
1810 If True, only the first MenuNode will be included for symbols defined
1811 in multiple locations.
1812
1813 Using kconf.node_iter(True) in the example above would give a list
1814 equal to unique_defined_syms.
1815 """
1816 if unique_syms:
1817 for sym in self.unique_defined_syms:
1818 sym._visited = False
1819
1820 node = self.top_node
1821 while 1:
1822 # Jump to the next node with an iterative tree walk
1823 if node.list:
1824 node = node.list
1825 elif node.next:
1826 node = node.next
1827 else:
1828 while node.parent:
1829 node = node.parent
1830 if node.next:
1831 node = node.next
1832 break
1833 else:
1834 # No more nodes
1835 return
1836
1837 if unique_syms and node.item.__class__ is Symbol:
1838 if node.item._visited:
1839 continue
1840 node.item._visited = True
1841
1842 yield node
1843
1844 def eval_string(self, s):
1845 """
1846 Returns the tristate value of the expression 's', represented as 0, 1,
1847 and 2 for n, m, and y, respectively. Raises KconfigError if syntax
1848 errors are detected in 's'. Warns if undefined symbols are referenced.
1849
1850 As an example, if FOO and BAR are tristate symbols at least one of
1851 which has the value y, then config.eval_string("y && (FOO || BAR)")
1852 returns 2 (y).
1853
1854 To get the string value of non-bool/tristate symbols, use
1855 Symbol.str_value. eval_string() always returns a tristate value, and
1856 all non-bool/tristate symbols have the tristate value 0 (n).
1857
1858 The expression parsing is consistent with how parsing works for
1859 conditional ('if ...') expressions in the configuration, and matches
1860 the C implementation. m is rewritten to 'm && MODULES', so
1861 eval_string("m") will return 0 (n) unless modules are enabled.
1862 """
1863 # The parser is optimized to be fast when parsing Kconfig files (where
1864 # an expression can never appear at the beginning of a line). We have
1865 # to monkey-patch things a bit here to reuse it.
1866
1867 self._filename = None
1868
1869 self._tokens = self._tokenize("if " + s)
[cf2f109]1870 # Strip "if " to avoid giving confusing error messages
1871 self._line = s
[f596dde]1872 self._tokens_i = 1 # Skip the 'if' token
1873
1874 return expr_value(self._expect_expr_and_eol())
1875
1876 def unset_values(self):
1877 """
[cf2f109]1878 Removes any user values from all symbols, as if Kconfig.load_config()
1879 or Symbol.set_value() had never been called.
[f596dde]1880 """
[cf2f109]1881 self._warn_no_prompt = False
[f596dde]1882 try:
1883 # set_value() already rejects undefined symbols, and they don't
1884 # need to be invalidated (because their value never changes), so we
1885 # can just iterate over defined symbols
1886 for sym in self.unique_defined_syms:
1887 sym.unset_value()
1888
1889 for choice in self.unique_choices:
1890 choice.unset_value()
1891 finally:
[cf2f109]1892 self._warn_no_prompt = True
[f596dde]1893
1894 def enable_warnings(self):
1895 """
[cf2f109]1896 Do 'Kconfig.warn = True' instead. Maintained for backwards
1897 compatibility.
[f596dde]1898 """
[cf2f109]1899 self.warn = True
[f596dde]1900
1901 def disable_warnings(self):
1902 """
[cf2f109]1903 Do 'Kconfig.warn = False' instead. Maintained for backwards
1904 compatibility.
[f596dde]1905 """
[cf2f109]1906 self.warn = False
[f596dde]1907
1908 def enable_stderr_warnings(self):
1909 """
[cf2f109]1910 Do 'Kconfig.warn_to_stderr = True' instead. Maintained for backwards
1911 compatibility.
[f596dde]1912 """
[cf2f109]1913 self.warn_to_stderr = True
[f596dde]1914
1915 def disable_stderr_warnings(self):
1916 """
[cf2f109]1917 Do 'Kconfig.warn_to_stderr = False' instead. Maintained for backwards
1918 compatibility.
[f596dde]1919 """
[cf2f109]1920 self.warn_to_stderr = False
[f596dde]1921
1922 def enable_undef_warnings(self):
1923 """
[cf2f109]1924 Do 'Kconfig.warn_assign_undef = True' instead. Maintained for backwards
1925 compatibility.
[f596dde]1926 """
[cf2f109]1927 self.warn_assign_undef = True
[f596dde]1928
1929 def disable_undef_warnings(self):
1930 """
[cf2f109]1931 Do 'Kconfig.warn_assign_undef = False' instead. Maintained for
1932 backwards compatibility.
[f596dde]1933 """
[cf2f109]1934 self.warn_assign_undef = False
[f596dde]1935
1936 def enable_override_warnings(self):
1937 """
[cf2f109]1938 Do 'Kconfig.warn_assign_override = True' instead. Maintained for
1939 backwards compatibility.
[f596dde]1940 """
[cf2f109]1941 self.warn_assign_override = True
[f596dde]1942
1943 def disable_override_warnings(self):
1944 """
[cf2f109]1945 Do 'Kconfig.warn_assign_override = False' instead. Maintained for
1946 backwards compatibility.
[f596dde]1947 """
[cf2f109]1948 self.warn_assign_override = False
[f596dde]1949
1950 def enable_redun_warnings(self):
1951 """
[cf2f109]1952 Do 'Kconfig.warn_assign_redun = True' instead. Maintained for backwards
1953 compatibility.
[f596dde]1954 """
[cf2f109]1955 self.warn_assign_redun = True
[f596dde]1956
1957 def disable_redun_warnings(self):
1958 """
[cf2f109]1959 Do 'Kconfig.warn_assign_redun = False' instead. Maintained for
1960 backwards compatibility.
[f596dde]1961 """
[cf2f109]1962 self.warn_assign_redun = False
[f596dde]1963
1964 def __repr__(self):
1965 """
1966 Returns a string with information about the Kconfig object when it is
1967 evaluated on e.g. the interactive Python prompt.
1968 """
[cf2f109]1969 def status(flag):
1970 return "enabled" if flag else "disabled"
1971
[f596dde]1972 return "<{}>".format(", ".join((
1973 "configuration with {} symbols".format(len(self.syms)),
1974 'main menu prompt "{}"'.format(self.mainmenu_text),
1975 "srctree is current directory" if not self.srctree else
1976 'srctree "{}"'.format(self.srctree),
1977 'config symbol prefix "{}"'.format(self.config_prefix),
[cf2f109]1978 "warnings " + status(self.warn),
1979 "printing of warnings to stderr " + status(self.warn_to_stderr),
[f596dde]1980 "undef. symbol assignment warnings " +
[cf2f109]1981 status(self.warn_assign_undef),
1982 "overriding symbol assignment warnings " +
1983 status(self.warn_assign_override),
[f596dde]1984 "redundant symbol assignment warnings " +
[cf2f109]1985 status(self.warn_assign_redun)
[f596dde]1986 )))
1987
1988 #
1989 # Private methods
1990 #
1991
1992
1993 #
1994 # File reading
1995 #
1996
1997 def _open_config(self, filename):
1998 # Opens a .config file. First tries to open 'filename', then
1999 # '$srctree/filename' if $srctree was set when the configuration was
2000 # loaded.
2001
2002 try:
2003 return self._open(filename, "r")
2004 except IOError as e:
2005 # This will try opening the same file twice if $srctree is unset,
2006 # but it's not a big deal
2007 try:
2008 return self._open(join(self.srctree, filename), "r")
2009 except IOError as e2:
2010 # This is needed for Python 3, because e2 is deleted after
2011 # the try block:
2012 #
2013 # https://docs.python.org/3/reference/compound_stmts.html#the-try-statement
2014 e = e2
2015
2016 raise _KconfigIOError(
2017 e, "Could not open '{}' ({}: {}). Check that the $srctree "
2018 "environment variable ({}) is set correctly."
2019 .format(filename, errno.errorcode[e.errno], e.strerror,
2020 "set to '{}'".format(self.srctree) if self.srctree
2021 else "unset or blank"))
2022
[cf2f109]2023 def _enter_file(self, filename):
[f596dde]2024 # Jumps to the beginning of a sourced Kconfig file, saving the previous
2025 # position and file object.
2026 #
[cf2f109]2027 # filename:
2028 # Absolute path to file
2029
2030 # Path relative to $srctree, stored in e.g. self._filename
2031 # (which makes it indirectly show up in MenuNode.filename). Equals
2032 # 'filename' for absolute paths passed to 'source'.
2033 if filename.startswith(self._srctree_prefix):
2034 # Relative path (or a redundant absolute path to within $srctree,
2035 # but it's probably fine to reduce those too)
2036 rel_filename = filename[len(self._srctree_prefix):]
2037 else:
2038 # Absolute path
2039 rel_filename = filename
[f596dde]2040
2041 self.kconfig_filenames.append(rel_filename)
2042
2043 # The parent Kconfig files are represented as a list of
2044 # (<include path>, <Python 'file' object for Kconfig file>) tuples.
2045 #
2046 # <include path> is immutable and holds a *tuple* of
2047 # (<filename>, <linenr>) tuples, giving the locations of the 'source'
2048 # statements in the parent Kconfig files. The current include path is
2049 # also available in Kconfig._include_path.
2050 #
2051 # The point of this redundant setup is to allow Kconfig._include_path
2052 # to be assigned directly to MenuNode.include_path without having to
2053 # copy it, sharing it wherever possible.
2054
2055 # Save include path and 'file' object (via its 'readline' function)
2056 # before entering the file
2057 self._filestack.append((self._include_path, self._readline))
2058
2059 # _include_path is a tuple, so this rebinds the variable instead of
2060 # doing in-place modification
2061 self._include_path += ((self._filename, self._linenr),)
2062
2063 # Check for recursive 'source'
2064 for name, _ in self._include_path:
2065 if name == rel_filename:
2066 raise KconfigError(
2067 "\n{}:{}: recursive 'source' of '{}' detected. Check that "
2068 "environment variables are set correctly.\n"
2069 "Include path:\n{}"
2070 .format(self._filename, self._linenr, rel_filename,
2071 "\n".join("{}:{}".format(name, linenr)
2072 for name, linenr in self._include_path)))
2073
2074 try:
[cf2f109]2075 self._readline = self._open(filename, "r").readline
[f596dde]2076 except IOError as e:
[cf2f109]2077 # We already know that the file exists
[f596dde]2078 raise _KconfigIOError(
[cf2f109]2079 e, "{}:{}: Could not open '{}' (in '{}') ({}: {})"
2080 .format(self._filename, self._linenr, filename,
2081 self._line.strip(),
[f596dde]2082 errno.errorcode[e.errno], e.strerror))
2083
2084 self._filename = rel_filename
2085 self._linenr = 0
2086
2087 def _leave_file(self):
2088 # Returns from a Kconfig file to the file that sourced it. See
2089 # _enter_file().
2090
2091 # __self__ fetches the 'file' object for the method
2092 self._readline.__self__.close()
2093 # Restore location from parent Kconfig file
2094 self._filename, self._linenr = self._include_path[-1]
2095 # Restore include path and 'file' object
2096 self._include_path, self._readline = self._filestack.pop()
2097
2098 def _next_line(self):
2099 # Fetches and tokenizes the next line from the current Kconfig file.
2100 # Returns False at EOF and True otherwise.
2101
2102 # We might already have tokens from parsing a line and discovering that
2103 # it's part of a different construct
2104 if self._reuse_tokens:
2105 self._reuse_tokens = False
2106 # self._tokens_i is known to be 1 here, because _parse_properties()
2107 # leaves it like that when it can't recognize a line (or parses
2108 # a help text)
2109 return True
2110
[cf2f109]2111 # readline() returns '' over and over at EOF, which we rely on for help
2112 # texts at the end of files (see _line_after_help())
[f596dde]2113 line = self._readline()
2114 if not line:
2115 return False
2116 self._linenr += 1
2117
2118 # Handle line joining
2119 while line.endswith("\\\n"):
2120 line = line[:-2] + self._readline()
2121 self._linenr += 1
2122
2123 self._tokens = self._tokenize(line)
2124 # Initialize to 1 instead of 0 to factor out code from _parse_block()
2125 # and _parse_properties(). They immediately fetch self._tokens[0].
2126 self._tokens_i = 1
2127
2128 return True
2129
2130 def _line_after_help(self, line):
2131 # Tokenizes a line after a help text. This case is special in that the
2132 # line has already been fetched (to discover that it isn't part of the
2133 # help text).
2134 #
2135 # An earlier version used a _saved_line variable instead that was
2136 # checked in _next_line(). This special-casing gets rid of it and makes
2137 # _reuse_tokens alone sufficient to handle unget.
2138
2139 # Handle line joining
2140 while line.endswith("\\\n"):
2141 line = line[:-2] + self._readline()
2142 self._linenr += 1
2143
2144 self._tokens = self._tokenize(line)
2145 self._reuse_tokens = True
2146
[cf2f109]2147 def _write_if_changed(self, filename, contents):
2148 # Writes 'contents' into 'filename', but only if it differs from the
2149 # current contents of the file.
2150 #
2151 # Another variant would be write a temporary file on the same
2152 # filesystem, compare the files, and rename() the temporary file if it
2153 # differs, but it breaks stuff like write_config("/dev/null"), which is
2154 # used out there to force evaluation-related warnings to be generated.
2155 # This simple version is pretty failsafe and portable.
2156
2157 if not self._contents_eq(filename, contents):
2158 with self._open(filename, "w") as f:
2159 f.write(contents)
2160
2161 def _contents_eq(self, filename, contents):
2162 # Returns True if the contents of 'filename' is 'contents' (a string),
2163 # and False otherwise (including if 'filename' can't be opened/read)
2164
2165 try:
2166 with self._open(filename, "r") as f:
2167 # Robust re. things like encoding and line endings (mmap()
2168 # trickery isn't)
2169 return f.read(len(contents) + 1) == contents
2170 except IOError:
2171 # If the error here would prevent writing the file as well, we'll
2172 # notice it later
2173 return False
[f596dde]2174
2175 #
2176 # Tokenization
2177 #
2178
2179 def _lookup_sym(self, name):
2180 # Fetches the symbol 'name' from the symbol table, creating and
2181 # registering it if it does not exist. If '_parsing_kconfigs' is False,
2182 # it means we're in eval_string(), and new symbols won't be registered.
2183
2184 if name in self.syms:
2185 return self.syms[name]
2186
2187 sym = Symbol()
2188 sym.kconfig = self
2189 sym.name = name
2190 sym.is_constant = False
2191 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
2192
2193 if self._parsing_kconfigs:
2194 self.syms[name] = sym
2195 else:
2196 self._warn("no symbol {} in configuration".format(name))
2197
2198 return sym
2199
2200 def _lookup_const_sym(self, name):
2201 # Like _lookup_sym(), for constant (quoted) symbols
2202
2203 if name in self.const_syms:
2204 return self.const_syms[name]
2205
2206 sym = Symbol()
2207 sym.kconfig = self
2208 sym.name = name
2209 sym.is_constant = True
2210 sym.rev_dep = sym.weak_rev_dep = sym.direct_dep = self.n
2211
2212 if self._parsing_kconfigs:
2213 self.const_syms[name] = sym
2214
2215 return sym
2216
2217 def _tokenize(self, s):
2218 # Parses 's', returning a None-terminated list of tokens. Registers any
2219 # new symbols encountered with _lookup(_const)_sym().
2220 #
2221 # Tries to be reasonably speedy by processing chunks of text via
2222 # regexes and string operations where possible. This is the biggest
2223 # hotspot during parsing.
2224 #
[cf2f109]2225 # It might be possible to rewrite this to 'yield' tokens instead,
2226 # working across multiple lines. Lookback and compatibility with old
2227 # janky versions of the C tools complicate things though.
2228
2229 self._line = s # Used for error reporting
[f596dde]2230
2231 # Initial token on the line
2232 match = _command_match(s)
2233 if not match:
2234 if s.isspace() or s.lstrip().startswith("#"):
2235 return (None,)
2236 self._parse_error("unknown token at start of line")
2237
2238 # Tricky implementation detail: While parsing a token, 'token' refers
2239 # to the previous token. See _STRING_LEX for why this is needed.
2240 token = _get_keyword(match.group(1))
2241 if not token:
2242 # Backwards compatibility with old versions of the C tools, which
2243 # (accidentally) accepted stuff like "--help--" and "-help---".
2244 # This was fixed in the C tools by commit c2264564 ("kconfig: warn
2245 # of unhandled characters in Kconfig commands"), committed in July
2246 # 2015, but it seems people still run Kconfiglib on older kernels.
2247 if s.strip(" \t\n-") == "help":
2248 return (_T_HELP, None)
2249
2250 # If the first token is not a keyword (and not a weird help token),
2251 # we have a preprocessor variable assignment (or a bare macro on a
2252 # line)
2253 self._parse_assignment(s)
2254 return (None,)
2255
2256 tokens = [token]
2257 # The current index in the string being tokenized
2258 i = match.end()
2259
2260 # Main tokenization loop (for tokens past the first one)
2261 while i < len(s):
2262 # Test for an identifier/keyword first. This is the most common
2263 # case.
2264 match = _id_keyword_match(s, i)
2265 if match:
2266 # We have an identifier or keyword
2267
2268 # Check what it is. lookup_sym() will take care of allocating
2269 # new symbols for us the first time we see them. Note that
2270 # 'token' still refers to the previous token.
2271
2272 name = match.group(1)
2273 keyword = _get_keyword(name)
2274 if keyword:
2275 # It's a keyword
2276 token = keyword
2277 # Jump past it
2278 i = match.end()
2279
2280 elif token not in _STRING_LEX:
2281 # It's a non-const symbol, except we translate n, m, and y
2282 # into the corresponding constant symbols, like the C
2283 # implementation
2284
2285 if "$" in name:
2286 # Macro expansion within symbol name
2287 name, s, i = self._expand_name(s, i)
2288 else:
2289 i = match.end()
2290
2291 token = self.const_syms[name] \
2292 if name in ("y", "m", "n") else \
2293 self._lookup_sym(name)
2294
2295 else:
2296 # It's a case of missing quotes. For example, the
2297 # following is accepted:
2298 #
2299 # menu unquoted_title
2300 #
2301 # config A
2302 # tristate unquoted_prompt
2303 #
2304 # endmenu
2305 #
2306 # Named choices ('choice FOO') also end up here.
2307
2308 if token is not _T_CHOICE:
2309 self._warn("style: quotes recommended around '{}' in '{}'"
2310 .format(name, self._line.strip()),
2311 self._filename, self._linenr)
2312
2313 token = name
2314 i = match.end()
2315
2316 else:
2317 # Neither a keyword nor a non-const symbol
2318
2319 # We always strip whitespace after tokens, so it is safe to
2320 # assume that s[i] is the start of a token here.
2321 c = s[i]
2322
2323 if c in "\"'":
2324 if "$" not in s and "\\" not in s:
2325 # Fast path for lines without $ and \. Find the
2326 # matching quote.
2327 end_i = s.find(c, i + 1) + 1
2328 if not end_i:
2329 self._parse_error("unterminated string")
2330 val = s[i + 1:end_i - 1]
2331 i = end_i
2332 else:
2333 # Slow path
2334 s, end_i = self._expand_str(s, i)
2335
2336 # os.path.expandvars() and the $UNAME_RELEASE replace()
2337 # is a backwards compatibility hack, which should be
2338 # reasonably safe as expandvars() leaves references to
2339 # undefined env. vars. as is.
2340 #
2341 # The preprocessor functionality changed how
2342 # environment variables are referenced, to $(FOO).
2343 val = expandvars(s[i + 1:end_i - 1]
2344 .replace("$UNAME_RELEASE",
2345 _UNAME_RELEASE))
2346
2347 i = end_i
2348
2349 # This is the only place where we don't survive with a
2350 # single token of lookback: 'option env="FOO"' does not
2351 # refer to a constant symbol named "FOO".
2352 token = \
2353 val if token in _STRING_LEX or tokens[0] is _T_OPTION \
2354 else self._lookup_const_sym(val)
2355
2356 elif s.startswith("&&", i):
2357 token = _T_AND
2358 i += 2
2359
2360 elif s.startswith("||", i):
2361 token = _T_OR
2362 i += 2
2363
2364 elif c == "=":
2365 token = _T_EQUAL
2366 i += 1
2367
2368 elif s.startswith("!=", i):
2369 token = _T_UNEQUAL
2370 i += 2
2371
2372 elif c == "!":
2373 token = _T_NOT
2374 i += 1
2375
2376 elif c == "(":
2377 token = _T_OPEN_PAREN
2378 i += 1
2379
2380 elif c == ")":
2381 token = _T_CLOSE_PAREN
2382 i += 1
2383
2384 elif c == "#":
2385 break
2386
2387
2388 # Very rare
2389
2390 elif s.startswith("<=", i):
2391 token = _T_LESS_EQUAL
2392 i += 2
2393
2394 elif c == "<":
2395 token = _T_LESS
2396 i += 1
2397
2398 elif s.startswith(">=", i):
2399 token = _T_GREATER_EQUAL
2400 i += 2
2401
2402 elif c == ">":
2403 token = _T_GREATER
2404 i += 1
2405
2406
2407 else:
2408 self._parse_error("unknown tokens in line")
2409
2410
2411 # Skip trailing whitespace
2412 while i < len(s) and s[i].isspace():
2413 i += 1
2414
2415
2416 # Add the token
2417 tokens.append(token)
2418
2419 # None-terminating the token list makes token fetching simpler/faster
2420 tokens.append(None)
2421
2422 return tokens
2423
2424 # Helpers for syntax checking and token fetching. See the
2425 # 'Intro to expressions' section for what a constant symbol is.
2426 #
2427 # More of these could be added, but the single-use cases are inlined as an
2428 # optimization.
2429
2430 def _expect_sym(self):
2431 token = self._tokens[self._tokens_i]
2432 self._tokens_i += 1
2433
2434 if token.__class__ is not Symbol:
2435 self._parse_error("expected symbol")
2436
2437 return token
2438
2439 def _expect_nonconst_sym(self):
2440 # Used for 'select' and 'imply' only. We know the token indices.
2441
2442 token = self._tokens[1]
2443 self._tokens_i = 2
2444
2445 if token.__class__ is not Symbol or token.is_constant:
2446 self._parse_error("expected nonconstant symbol")
2447
2448 return token
2449
2450 def _expect_str_and_eol(self):
2451 token = self._tokens[self._tokens_i]
2452 self._tokens_i += 1
2453
2454 if token.__class__ is not str:
2455 self._parse_error("expected string")
2456
2457 if self._tokens[self._tokens_i] is not None:
2458 self._trailing_tokens_error()
2459
2460 return token
2461
2462 def _expect_expr_and_eol(self):
2463 expr = self._parse_expr(True)
2464
2465 if self._tokens[self._tokens_i] is not None:
2466 self._trailing_tokens_error()
2467
2468 return expr
2469
2470 def _check_token(self, token):
2471 # If the next token is 'token', removes it and returns True
2472
2473 if self._tokens[self._tokens_i] is token:
2474 self._tokens_i += 1
2475 return True
2476 return False
2477
2478 #
2479 # Preprocessor logic
2480 #
2481
2482 def _parse_assignment(self, s):
2483 # Parses a preprocessor variable assignment, registering the variable
2484 # if it doesn't already exist. Also takes care of bare macros on lines
2485 # (which are allowed, and can be useful for their side effects).
2486
2487 # Expand any macros in the left-hand side of the assignment (the
2488 # variable name)
2489 s = s.lstrip()
2490 i = 0
2491 while 1:
2492 i = _assignment_lhs_fragment_match(s, i).end()
2493 if s.startswith("$(", i):
2494 s, i = self._expand_macro(s, i, ())
2495 else:
2496 break
2497
2498 if s.isspace():
2499 # We also accept a bare macro on a line (e.g.
2500 # $(warning-if,$(foo),ops)), provided it expands to a blank string
2501 return
2502
2503 # Assigned variable
2504 name = s[:i]
2505
2506
2507 # Extract assignment operator (=, :=, or +=) and value
2508 rhs_match = _assignment_rhs_match(s, i)
2509 if not rhs_match:
2510 self._parse_error("syntax error")
2511
2512 op, val = rhs_match.groups()
2513
2514
2515 if name in self.variables:
2516 # Already seen variable
2517 var = self.variables[name]
2518 else:
2519 # New variable
2520 var = Variable()
2521 var.kconfig = self
2522 var.name = name
2523 var._n_expansions = 0
2524 self.variables[name] = var
2525
2526 # += acts like = on undefined variables (defines a recursive
2527 # variable)
2528 if op == "+=":
2529 op = "="
2530
2531 if op == "=":
2532 var.is_recursive = True
2533 var.value = val
2534 elif op == ":=":
2535 var.is_recursive = False
2536 var.value = self._expand_whole(val, ())
2537 else: # op == "+="
2538 # += does immediate expansion if the variable was last set
2539 # with :=
2540 var.value += " " + (val if var.is_recursive else
2541 self._expand_whole(val, ()))
2542
2543 def _expand_whole(self, s, args):
2544 # Expands preprocessor macros in all of 's'. Used whenever we don't
2545 # have to worry about delimiters. See _expand_macro() re. the 'args'
2546 # parameter.
2547 #
2548 # Returns the expanded string.
2549
2550 i = 0
2551 while 1:
2552 i = s.find("$(", i)
2553 if i == -1:
2554 break
2555 s, i = self._expand_macro(s, i, args)
2556 return s
2557
2558 def _expand_name(self, s, i):
2559 # Expands a symbol name starting at index 'i' in 's'.
2560 #
2561 # Returns the expanded name, the expanded 's' (including the part
2562 # before the name), and the index of the first character in the next
2563 # token after the name.
2564
2565 s, end_i = self._expand_name_iter(s, i)
2566 name = s[i:end_i]
2567 # isspace() is False for empty strings
2568 if not name.strip():
2569 # Avoid creating a Kconfig symbol with a blank name. It's almost
2570 # guaranteed to be an error.
2571 self._parse_error("macro expanded to blank string")
2572
2573 # Skip trailing whitespace
2574 while end_i < len(s) and s[end_i].isspace():
2575 end_i += 1
2576
2577 return name, s, end_i
2578
2579 def _expand_name_iter(self, s, i):
2580 # Expands a symbol name starting at index 'i' in 's'.
2581 #
2582 # Returns the expanded 's' (including the part before the name) and the
2583 # index of the first character after the expanded name in 's'.
2584
2585 while 1:
2586 match = _name_special_search(s, i)
2587
2588 if match.group() == "$(":
2589 s, i = self._expand_macro(s, match.start(), ())
2590 else:
2591 return (s, match.start())
2592
2593 def _expand_str(self, s, i):
2594 # Expands a quoted string starting at index 'i' in 's'. Handles both
2595 # backslash escapes and macro expansion.
2596 #
2597 # Returns the expanded 's' (including the part before the string) and
2598 # the index of the first character after the expanded string in 's'.
2599
2600 quote = s[i]
2601 i += 1 # Skip over initial "/'
2602 while 1:
2603 match = _string_special_search(s, i)
2604 if not match:
2605 self._parse_error("unterminated string")
2606
2607
2608 if match.group() == quote:
2609 # Found the end of the string
2610 return (s, match.end())
2611
2612 elif match.group() == "\\":
2613 # Replace '\x' with 'x'. 'i' ends up pointing to the character
2614 # after 'x', which allows macros to be canceled with '\$(foo)'.
2615 i = match.end()
2616 s = s[:match.start()] + s[i:]
2617
2618 elif match.group() == "$(":
2619 # A macro call within the string
2620 s, i = self._expand_macro(s, match.start(), ())
2621
2622 else:
2623 # A ' quote within " quotes or vice versa
2624 i += 1
2625
2626 def _expand_macro(self, s, i, args):
2627 # Expands a macro starting at index 'i' in 's'. If this macro resulted
2628 # from the expansion of another macro, 'args' holds the arguments
2629 # passed to that macro.
2630 #
2631 # Returns the expanded 's' (including the part before the macro) and
2632 # the index of the first character after the expanded macro in 's'.
2633
2634 start = i
2635 i += 2 # Skip over "$("
2636
2637 # Start of current macro argument
2638 arg_start = i
2639
2640 # Arguments of this macro call
2641 new_args = []
2642
2643 while 1:
2644 match = _macro_special_search(s, i)
2645 if not match:
2646 self._parse_error("missing end parenthesis in macro expansion")
2647
2648
2649 if match.group() == ")":
2650 # Found the end of the macro
2651
2652 new_args.append(s[arg_start:match.start()])
2653
2654 prefix = s[:start]
2655
2656 # $(1) is replaced by the first argument to the function, etc.,
2657 # provided at least that many arguments were passed
2658
2659 try:
2660 # Does the macro look like an integer, with a corresponding
2661 # argument? If so, expand it to the value of the argument.
2662 prefix += args[int(new_args[0])]
2663 except (ValueError, IndexError):
2664 # Regular variables are just functions without arguments,
2665 # and also go through the function value path
2666 prefix += self._fn_val(new_args)
2667
2668 return (prefix + s[match.end():],
2669 len(prefix))
2670
2671 elif match.group() == ",":
2672 # Found the end of a macro argument
2673 new_args.append(s[arg_start:match.start()])
2674 arg_start = i = match.end()
2675
2676 else: # match.group() == "$("
2677 # A nested macro call within the macro
2678 s, i = self._expand_macro(s, match.start(), args)
2679
2680 def _fn_val(self, args):
2681 # Returns the result of calling the function args[0] with the arguments
2682 # args[1..len(args)-1]. Plain variables are treated as functions
2683 # without arguments.
2684
2685 fn = args[0]
2686
2687 if fn in self.variables:
2688 var = self.variables[fn]
2689
2690 if len(args) == 1:
2691 # Plain variable
2692 if var._n_expansions:
2693 self._parse_error("Preprocessor variable {} recursively "
2694 "references itself".format(var.name))
2695 elif var._n_expansions > 100:
2696 # Allow functions to call themselves, but guess that functions
2697 # that are overly recursive are stuck
2698 self._parse_error("Preprocessor function {} seems stuck "
2699 "in infinite recursion".format(var.name))
2700
2701 var._n_expansions += 1
2702 res = self._expand_whole(self.variables[fn].value, args)
2703 var._n_expansions -= 1
2704 return res
2705
2706 if fn in self._functions:
2707 # Built-in or user-defined function
2708
2709 py_fn, min_arg, max_arg = self._functions[fn]
2710
2711 if len(args) - 1 < min_arg or \
2712 (max_arg is not None and len(args) - 1 > max_arg):
2713
2714 if min_arg == max_arg:
2715 expected_args = min_arg
2716 elif max_arg is None:
2717 expected_args = "{} or more".format(min_arg)
2718 else:
2719 expected_args = "{}-{}".format(min_arg, max_arg)
2720
2721 raise KconfigError("{}:{}: bad number of arguments in call "
2722 "to {}, expected {}, got {}"
2723 .format(self._filename, self._linenr, fn,
2724 expected_args, len(args) - 1))
2725
2726 return py_fn(self, *args)
2727
2728 # Environment variables are tried last
2729 if fn in os.environ:
2730 self.env_vars.add(fn)
2731 return os.environ[fn]
2732
2733 return ""
2734
2735 #
2736 # Parsing
2737 #
2738
2739 def _make_and(self, e1, e2):
2740 # Constructs an AND (&&) expression. Performs trivial simplification.
2741
2742 if e1 is self.y:
2743 return e2
2744
2745 if e2 is self.y:
2746 return e1
2747
2748 if e1 is self.n or e2 is self.n:
2749 return self.n
2750
2751 return (AND, e1, e2)
2752
2753 def _make_or(self, e1, e2):
2754 # Constructs an OR (||) expression. Performs trivial simplification.
2755
2756 if e1 is self.n:
2757 return e2
2758
2759 if e2 is self.n:
2760 return e1
2761
2762 if e1 is self.y or e2 is self.y:
2763 return self.y
2764
2765 return (OR, e1, e2)
2766
2767 def _parse_block(self, end_token, parent, prev):
2768 # Parses a block, which is the contents of either a file or an if,
2769 # menu, or choice statement.
2770 #
2771 # end_token:
2772 # The token that ends the block, e.g. _T_ENDIF ("endif") for ifs.
2773 # None for files.
2774 #
2775 # parent:
2776 # The parent menu node, corresponding to a menu, Choice, or 'if'.
2777 # 'if's are flattened after parsing.
2778 #
2779 # prev:
2780 # The previous menu node. New nodes will be added after this one (by
2781 # modifying their 'next' pointer).
2782 #
2783 # 'prev' is reused to parse a list of child menu nodes (for a menu or
2784 # Choice): After parsing the children, the 'next' pointer is assigned
2785 # to the 'list' pointer to "tilt up" the children above the node.
2786 #
2787 # Returns the final menu node in the block (or 'prev' if the block is
2788 # empty). This allows chaining.
2789
2790 while self._next_line():
2791 t0 = self._tokens[0]
2792
2793 if t0 is _T_CONFIG or t0 is _T_MENUCONFIG:
2794 # The tokenizer allocates Symbol objects for us
2795 sym = self._tokens[1]
2796
2797 if sym.__class__ is not Symbol or sym.is_constant:
2798 self._parse_error("missing or bad symbol name")
2799
2800 if self._tokens[2] is not None:
2801 self._trailing_tokens_error()
2802
2803 self.defined_syms.append(sym)
2804
2805 node = MenuNode()
2806 node.kconfig = self
2807 node.item = sym
2808 node.is_menuconfig = (t0 is _T_MENUCONFIG)
2809 node.prompt = node.help = node.list = None
2810 node.parent = parent
2811 node.filename = self._filename
2812 node.linenr = self._linenr
2813 node.include_path = self._include_path
2814
2815 sym.nodes.append(node)
2816
2817 self._parse_properties(node)
2818
2819 if node.is_menuconfig and not node.prompt:
2820 self._warn("the menuconfig symbol {} has no prompt"
2821 .format(_name_and_loc(sym)))
2822
2823 # Equivalent to
2824 #
2825 # prev.next = node
2826 # prev = node
2827 #
2828 # due to tricky Python semantics. The order matters.
2829 prev.next = prev = node
2830
2831 elif t0 is None:
2832 # Blank line
2833 continue
2834
2835 elif t0 in _SOURCE_TOKENS:
2836 pattern = self._expect_str_and_eol()
2837
2838 if t0 in _REL_SOURCE_TOKENS:
2839 # Relative source
2840 pattern = join(dirname(self._filename), pattern)
2841
[cf2f109]2842 # - glob() doesn't support globbing relative to a directory, so
2843 # we need to prepend $srctree to 'pattern'. Use join()
2844 # instead of '+' so that an absolute path in 'pattern' is
2845 # preserved.
2846 #
2847 # - Sort the glob results to ensure a consistent ordering of
2848 # Kconfig symbols, which indirectly ensures a consistent
2849 # ordering in e.g. .config files
2850 filenames = sorted(iglob(join(self._srctree_prefix, pattern)))
[f596dde]2851
2852 if not filenames and t0 in _OBL_SOURCE_TOKENS:
2853 raise KconfigError(
2854 "{}:{}: '{}' not found (in '{}'). Check that "
2855 "environment variables are set correctly (e.g. "
2856 "$srctree, which is {}). Also note that unset "
2857 "environment variables expand to the empty string."
2858 .format(self._filename, self._linenr, pattern,
2859 self._line.strip(),
2860 "set to '{}'".format(self.srctree)
2861 if self.srctree else "unset or blank"))
2862
2863 for filename in filenames:
[cf2f109]2864 self._enter_file(filename)
[f596dde]2865 prev = self._parse_block(None, parent, prev)
2866 self._leave_file()
2867
2868 elif t0 is end_token:
[cf2f109]2869 # Reached the end of the block. Terminate the final node and
2870 # return it.
[f596dde]2871
2872 if self._tokens[1] is not None:
2873 self._trailing_tokens_error()
2874
2875 prev.next = None
2876 return prev
2877
2878 elif t0 is _T_IF:
2879 node = MenuNode()
2880 node.item = node.prompt = None
2881 node.parent = parent
2882 node.dep = self._expect_expr_and_eol()
2883
2884 self._parse_block(_T_ENDIF, node, node)
2885 node.list = node.next
2886
2887 prev.next = prev = node
2888
2889 elif t0 is _T_MENU:
2890 node = MenuNode()
2891 node.kconfig = self
2892 node.item = t0 # _T_MENU == MENU
2893 node.is_menuconfig = True
2894 node.prompt = (self._expect_str_and_eol(), self.y)
2895 node.visibility = self.y
2896 node.parent = parent
2897 node.filename = self._filename
2898 node.linenr = self._linenr
2899 node.include_path = self._include_path
2900
2901 self.menus.append(node)
2902
2903 self._parse_properties(node)
2904 self._parse_block(_T_ENDMENU, node, node)
2905 node.list = node.next
2906
2907 prev.next = prev = node
2908
2909 elif t0 is _T_COMMENT:
2910 node = MenuNode()
2911 node.kconfig = self
2912 node.item = t0 # _T_COMMENT == COMMENT
2913 node.is_menuconfig = False
2914 node.prompt = (self._expect_str_and_eol(), self.y)
2915 node.list = None
2916 node.parent = parent
2917 node.filename = self._filename
2918 node.linenr = self._linenr
2919 node.include_path = self._include_path
2920
2921 self.comments.append(node)
2922
2923 self._parse_properties(node)
2924
2925 prev.next = prev = node
2926
2927 elif t0 is _T_CHOICE:
2928 if self._tokens[1] is None:
2929 choice = Choice()
2930 choice.direct_dep = self.n
2931 else:
2932 # Named choice
2933 name = self._expect_str_and_eol()
2934 choice = self.named_choices.get(name)
2935 if not choice:
2936 choice = Choice()
2937 choice.name = name
2938 choice.direct_dep = self.n
2939 self.named_choices[name] = choice
2940
2941 self.choices.append(choice)
2942
2943 choice.kconfig = self
2944
2945 node = MenuNode()
2946 node.kconfig = self
2947 node.item = choice
2948 node.is_menuconfig = True
2949 node.prompt = node.help = None
2950 node.parent = parent
2951 node.filename = self._filename
2952 node.linenr = self._linenr
2953 node.include_path = self._include_path
2954
2955 choice.nodes.append(node)
2956
2957 self._parse_properties(node)
2958 self._parse_block(_T_ENDCHOICE, node, node)
2959 node.list = node.next
2960
2961 prev.next = prev = node
2962
2963 elif t0 is _T_MAINMENU:
2964 self.top_node.prompt = (self._expect_str_and_eol(), self.y)
2965
2966 else:
2967 # A valid endchoice/endif/endmenu is caught by the 'end_token'
2968 # check above
2969 self._parse_error(
2970 "no corresponding 'choice'" if t0 is _T_ENDCHOICE else
2971 "no corresponding 'if'" if t0 is _T_ENDIF else
2972 "no corresponding 'menu'" if t0 is _T_ENDMENU else
2973 "unrecognized construct")
2974
2975 # End of file reached. Terminate the final node and return it.
2976
2977 if end_token:
2978 raise KconfigError(
2979 "expected '{}' at end of '{}'"
2980 .format("endchoice" if end_token is _T_ENDCHOICE else
2981 "endif" if end_token is _T_ENDIF else
2982 "endmenu",
2983 self._filename))
2984
2985 prev.next = None
2986 return prev
2987
2988 def _parse_cond(self):
2989 # Parses an optional 'if <expr>' construct and returns the parsed
2990 # <expr>, or self.y if the next token is not _T_IF
2991
2992 expr = self._parse_expr(True) if self._check_token(_T_IF) else self.y
2993
2994 if self._tokens[self._tokens_i] is not None:
2995 self._trailing_tokens_error()
2996
2997 return expr
2998
2999 def _parse_properties(self, node):
3000 # Parses and adds properties to the MenuNode 'node' (type, 'prompt',
3001 # 'default's, etc.) Properties are later copied up to symbols and
3002 # choices in a separate pass after parsing, in e.g.
3003 # _add_props_to_sym().
3004 #
3005 # An older version of this code added properties directly to symbols
3006 # and choices instead of to their menu nodes (and handled dependency
3007 # propagation simultaneously), but that loses information on where a
3008 # property is added when a symbol or choice is defined in multiple
3009 # locations. Some Kconfig configuration systems rely heavily on such
3010 # symbols, and better docs can be generated by keeping track of where
3011 # properties are added.
3012 #
3013 # node:
3014 # The menu node we're parsing properties on
3015
3016 # Dependencies from 'depends on'. Will get propagated to the properties
3017 # below.
3018 node.dep = self.y
3019
3020 while self._next_line():
3021 t0 = self._tokens[0]
3022
3023 if t0 in _TYPE_TOKENS:
3024 # Relies on '_T_BOOL is BOOL', etc., to save a conversion
3025 self._set_type(node, t0)
3026 if self._tokens[1] is not None:
3027 self._parse_prompt(node)
3028
3029 elif t0 is _T_DEPENDS:
3030 if not self._check_token(_T_ON):
3031 self._parse_error("expected 'on' after 'depends'")
3032
3033 node.dep = self._make_and(node.dep,
3034 self._expect_expr_and_eol())
3035
3036 elif t0 is _T_HELP:
3037 self._parse_help(node)
3038
3039 elif t0 is _T_SELECT:
3040 if node.item.__class__ is not Symbol:
3041 self._parse_error("only symbols can select")
3042
3043 node.selects.append((self._expect_nonconst_sym(),
3044 self._parse_cond()))
3045
3046 elif t0 is None:
3047 # Blank line
3048 continue
3049
3050 elif t0 is _T_DEFAULT:
3051 node.defaults.append((self._parse_expr(False),
3052 self._parse_cond()))
3053
3054 elif t0 in _DEF_TOKEN_TO_TYPE:
3055 self._set_type(node, _DEF_TOKEN_TO_TYPE[t0])
3056 node.defaults.append((self._parse_expr(False),
3057 self._parse_cond()))
3058
3059 elif t0 is _T_PROMPT:
3060 self._parse_prompt(node)
3061
3062 elif t0 is _T_RANGE:
3063 node.ranges.append((self._expect_sym(), self._expect_sym(),
3064 self._parse_cond()))
3065
3066 elif t0 is _T_IMPLY:
3067 if node.item.__class__ is not Symbol:
3068 self._parse_error("only symbols can imply")
3069
3070 node.implies.append((self._expect_nonconst_sym(),
3071 self._parse_cond()))
3072
3073 elif t0 is _T_VISIBLE:
3074 if not self._check_token(_T_IF):
3075 self._parse_error("expected 'if' after 'visible'")
3076
3077 node.visibility = self._make_and(node.visibility,
3078 self._expect_expr_and_eol())
3079
3080 elif t0 is _T_OPTION:
3081 if self._check_token(_T_ENV):
3082 if not self._check_token(_T_EQUAL):
3083 self._parse_error("expected '=' after 'env'")
3084
3085 env_var = self._expect_str_and_eol()
3086 node.item.env_var = env_var
3087
3088 if env_var in os.environ:
3089 node.defaults.append(
3090 (self._lookup_const_sym(os.environ[env_var]),
3091 self.y))
3092 else:
3093 self._warn("{1} has 'option env=\"{0}\"', "
3094 "but the environment variable {0} is not "
3095 "set".format(node.item.name, env_var),
3096 self._filename, self._linenr)
3097
3098 if env_var != node.item.name:
3099 self._warn("Kconfiglib expands environment variables "
3100 "in strings directly, meaning you do not "
3101 "need 'option env=...' \"bounce\" symbols. "
3102 "For compatibility with the C tools, "
3103 "rename {} to {} (so that the symbol name "
3104 "matches the environment variable name)."
3105 .format(node.item.name, env_var),
3106 self._filename, self._linenr)
3107
3108 elif self._check_token(_T_DEFCONFIG_LIST):
3109 if not self.defconfig_list:
3110 self.defconfig_list = node.item
3111 else:
3112 self._warn("'option defconfig_list' set on multiple "
3113 "symbols ({0} and {1}). Only {0} will be "
3114 "used.".format(self.defconfig_list.name,
3115 node.item.name),
3116 self._filename, self._linenr)
3117
3118 elif self._check_token(_T_MODULES):
3119 # To reduce warning spam, only warn if 'option modules' is
3120 # set on some symbol that isn't MODULES, which should be
3121 # safe. I haven't run into any projects that make use
3122 # modules besides the kernel yet, and there it's likely to
3123 # keep being called "MODULES".
3124 if node.item is not self.modules:
3125 self._warn("the 'modules' option is not supported. "
3126 "Let me know if this is a problem for you, "
3127 "as it wouldn't be that hard to implement. "
3128 "Note that modules are supported -- "
3129 "Kconfiglib just assumes the symbol name "
3130 "MODULES, like older versions of the C "
3131 "implementation did when 'option modules' "
3132 "wasn't used.",
3133 self._filename, self._linenr)
3134
3135 elif self._check_token(_T_ALLNOCONFIG_Y):
3136 if node.item.__class__ is not Symbol:
3137 self._parse_error("the 'allnoconfig_y' option is only "
3138 "valid for symbols")
3139
3140 node.item.is_allnoconfig_y = True
3141
3142 else:
3143 self._parse_error("unrecognized option")
3144
3145 elif t0 is _T_OPTIONAL:
3146 if node.item.__class__ is not Choice:
3147 self._parse_error('"optional" is only valid for choices')
3148
3149 node.item.is_optional = True
3150
3151 else:
3152 # Reuse the tokens for the non-property line later
3153 self._reuse_tokens = True
3154 return
3155
3156 def _set_type(self, node, new_type):
[cf2f109]3157 # UNKNOWN is falsy
[f596dde]3158 if node.item.orig_type and node.item.orig_type is not new_type:
3159 self._warn("{} defined with multiple types, {} will be used"
3160 .format(_name_and_loc(node.item),
3161 TYPE_TO_STR[new_type]))
3162
3163 node.item.orig_type = new_type
3164
3165 def _parse_prompt(self, node):
3166 # 'prompt' properties override each other within a single definition of
3167 # a symbol, but additional prompts can be added by defining the symbol
3168 # multiple times
3169
3170 if node.prompt:
3171 self._warn(_name_and_loc(node.item) +
3172 " defined with multiple prompts in single location")
3173
3174 prompt = self._tokens[1]
3175 self._tokens_i = 2
3176
3177 if prompt.__class__ is not str:
3178 self._parse_error("expected prompt string")
3179
3180 if prompt != prompt.strip():
3181 self._warn(_name_and_loc(node.item) +
3182 " has leading or trailing whitespace in its prompt")
3183
3184 # This avoid issues for e.g. reStructuredText documentation, where
3185 # '*prompt *' is invalid
3186 prompt = prompt.strip()
3187
3188 node.prompt = (prompt, self._parse_cond())
3189
3190 def _parse_help(self, node):
3191 if node.help is not None:
3192 self._warn(_name_and_loc(node.item) + " defined with more than "
3193 "one help text -- only the last one will be used")
3194
3195 # Micro-optimization. This code is pretty hot.
3196 readline = self._readline
3197
3198 # Find first non-blank (not all-space) line and get its
3199 # indentation
3200
3201 while 1:
3202 line = readline()
3203 self._linenr += 1
3204 if not line:
3205 self._empty_help(node, line)
3206 return
3207 if not line.isspace():
3208 break
3209
3210 len_ = len # Micro-optimization
3211
3212 # Use a separate 'expline' variable here and below to avoid stomping on
3213 # any tabs people might've put deliberately into the first line after
3214 # the help text
3215 expline = line.expandtabs()
3216 indent = len_(expline) - len_(expline.lstrip())
3217 if not indent:
3218 self._empty_help(node, line)
3219 return
3220
3221 # The help text goes on till the first non-blank line with less indent
3222 # than the first line
3223
3224 # Add the first line
3225 lines = [expline[indent:]]
3226 add_line = lines.append # Micro-optimization
3227
3228 while 1:
3229 line = readline()
3230 if line.isspace():
3231 # No need to preserve the exact whitespace in these
3232 add_line("\n")
3233 elif not line:
3234 # End of file
3235 break
3236 else:
3237 expline = line.expandtabs()
3238 if len_(expline) - len_(expline.lstrip()) < indent:
3239 break
3240 add_line(expline[indent:])
3241
3242 self._linenr += len_(lines)
3243 node.help = "".join(lines).rstrip()
3244 if line:
3245 self._line_after_help(line)
3246
3247 def _empty_help(self, node, line):
3248 self._warn(_name_and_loc(node.item) +
3249 " has 'help' but empty help text")
3250 node.help = ""
3251 if line:
3252 self._line_after_help(line)
3253
3254 def _parse_expr(self, transform_m):
3255 # Parses an expression from the tokens in Kconfig._tokens using a
3256 # simple top-down approach. See the module docstring for the expression
3257 # format.
3258 #
3259 # transform_m:
3260 # True if m should be rewritten to m && MODULES. See the
3261 # Kconfig.eval_string() documentation.
3262
3263 # Grammar:
3264 #
3265 # expr: and_expr ['||' expr]
3266 # and_expr: factor ['&&' and_expr]
3267 # factor: <symbol> ['='/'!='/'<'/... <symbol>]
3268 # '!' factor
3269 # '(' expr ')'
3270 #
3271 # It helps to think of the 'expr: and_expr' case as a single-operand OR
3272 # (no ||), and of the 'and_expr: factor' case as a single-operand AND
3273 # (no &&). Parsing code is always a bit tricky.
3274
3275 # Mind dump: parse_factor() and two nested loops for OR and AND would
3276 # work as well. The straightforward implementation there gives a
3277 # (op, (op, (op, A, B), C), D) parse for A op B op C op D. Representing
3278 # expressions as (op, [list of operands]) instead goes nicely with that
3279 # version, but is wasteful for short expressions and complicates
3280 # expression evaluation and other code that works on expressions (more
3281 # complicated code likely offsets any performance gain from less
3282 # recursion too). If we also try to optimize the list representation by
3283 # merging lists when possible (e.g. when ANDing two AND expressions),
3284 # we end up allocating a ton of lists instead of reusing expressions,
3285 # which is bad.
3286
3287 and_expr = self._parse_and_expr(transform_m)
3288
3289 # Return 'and_expr' directly if we have a "single-operand" OR.
3290 # Otherwise, parse the expression on the right and make an OR node.
3291 # This turns A || B || C || D into (OR, A, (OR, B, (OR, C, D))).
3292 return and_expr \
3293 if not self._check_token(_T_OR) else \
3294 (OR, and_expr, self._parse_expr(transform_m))
3295
3296 def _parse_and_expr(self, transform_m):
3297 factor = self._parse_factor(transform_m)
3298
3299 # Return 'factor' directly if we have a "single-operand" AND.
3300 # Otherwise, parse the right operand and make an AND node. This turns
3301 # A && B && C && D into (AND, A, (AND, B, (AND, C, D))).
3302 return factor \
3303 if not self._check_token(_T_AND) else \
3304 (AND, factor, self._parse_and_expr(transform_m))
3305
3306 def _parse_factor(self, transform_m):
3307 token = self._tokens[self._tokens_i]
3308 self._tokens_i += 1
3309
3310 if token.__class__ is Symbol:
3311 # Plain symbol or relation
3312
3313 if self._tokens[self._tokens_i] not in _RELATIONS:
3314 # Plain symbol
3315
3316 # For conditional expressions ('depends on <expr>',
3317 # '... if <expr>', etc.), m is rewritten to m && MODULES.
3318 if transform_m and token is self.m:
3319 return (AND, self.m, self.modules)
3320
3321 return token
3322
3323 # Relation
3324 #
3325 # _T_EQUAL, _T_UNEQUAL, etc., deliberately have the same values as
3326 # EQUAL, UNEQUAL, etc., so we can just use the token directly
3327 self._tokens_i += 1
3328 return (self._tokens[self._tokens_i - 1], token,
3329 self._expect_sym())
3330
3331 if token is _T_NOT:
3332 # token == _T_NOT == NOT
3333 return (token, self._parse_factor(transform_m))
3334
3335 if token is _T_OPEN_PAREN:
3336 expr_parse = self._parse_expr(transform_m)
3337 if self._check_token(_T_CLOSE_PAREN):
3338 return expr_parse
3339
3340 self._parse_error("malformed expression")
3341
3342 #
3343 # Caching and invalidation
3344 #
3345
3346 def _build_dep(self):
3347 # Populates the Symbol/Choice._dependents sets, which contain all other
3348 # items (symbols and choices) that immediately depend on the item in
3349 # the sense that changing the value of the item might affect the value
3350 # of the dependent items. This is used for caching/invalidation.
3351 #
3352 # The calculated sets might be larger than necessary as we don't do any
3353 # complex analysis of the expressions.
3354
3355 make_depend_on = _make_depend_on # Micro-optimization
3356
3357 # Only calculate _dependents for defined symbols. Constant and
3358 # undefined symbols could theoretically be selected/implied, but it
3359 # wouldn't change their value, so it's not a true dependency.
3360 for sym in self.unique_defined_syms:
3361 # Symbols depend on the following:
3362
3363 # The prompt conditions
3364 for node in sym.nodes:
3365 if node.prompt:
3366 make_depend_on(sym, node.prompt[1])
3367
3368 # The default values and their conditions
3369 for value, cond in sym.defaults:
3370 make_depend_on(sym, value)
3371 make_depend_on(sym, cond)
3372
3373 # The reverse and weak reverse dependencies
3374 make_depend_on(sym, sym.rev_dep)
3375 make_depend_on(sym, sym.weak_rev_dep)
3376
3377 # The ranges along with their conditions
3378 for low, high, cond in sym.ranges:
3379 make_depend_on(sym, low)
3380 make_depend_on(sym, high)
3381 make_depend_on(sym, cond)
3382
3383 # The direct dependencies. This is usually redundant, as the direct
3384 # dependencies get propagated to properties, but it's needed to get
3385 # invalidation solid for 'imply', which only checks the direct
3386 # dependencies (even if there are no properties to propagate it
3387 # to).
3388 make_depend_on(sym, sym.direct_dep)
3389
3390 # In addition to the above, choice symbols depend on the choice
3391 # they're in, but that's handled automatically since the Choice is
3392 # propagated to the conditions of the properties before
3393 # _build_dep() runs.
3394
3395 for choice in self.unique_choices:
3396 # Choices depend on the following:
3397
3398 # The prompt conditions
3399 for node in choice.nodes:
3400 if node.prompt:
3401 make_depend_on(choice, node.prompt[1])
3402
3403 # The default symbol conditions
3404 for _, cond in choice.defaults:
3405 make_depend_on(choice, cond)
3406
3407 def _add_choice_deps(self):
3408 # Choices also depend on the choice symbols themselves, because the
3409 # y-mode selection of the choice might change if a choice symbol's
3410 # visibility changes.
3411 #
3412 # We add these dependencies separately after dependency loop detection.
3413 # The invalidation algorithm can handle the resulting
3414 # <choice symbol> <-> <choice> dependency loops, but they make loop
3415 # detection awkward.
3416
3417 for choice in self.unique_choices:
3418 for sym in choice.syms:
3419 sym._dependents.add(choice)
3420
3421 def _invalidate_all(self):
3422 # Undefined symbols never change value and don't need to be
3423 # invalidated, so we can just iterate over defined symbols.
3424 # Invalidating constant symbols would break things horribly.
3425 for sym in self.unique_defined_syms:
3426 sym._invalidate()
3427
3428 for choice in self.unique_choices:
3429 choice._invalidate()
3430
3431 #
3432 # Post-parsing menu tree processing, including dependency propagation and
3433 # implicit submenu creation
3434 #
3435
3436 def _finalize_tree(self, node, visible_if):
3437 # Propagates properties and dependencies, creates implicit menus (see
3438 # kconfig-language.txt), removes 'if' nodes, and finalizes choices.
3439 # This pretty closely mirrors menu_finalize() from the C
3440 # implementation, with some minor tweaks (MenuNode holds lists of
3441 # properties instead of each property having a MenuNode pointer, for
3442 # example).
3443 #
3444 # node:
3445 # The current "parent" menu node, from which we propagate
3446 # dependencies
3447 #
3448 # visible_if:
3449 # Dependencies from 'visible if' on parent menus. These are added to
3450 # the prompts of symbols and choices.
3451
3452 if node.list:
3453 # The menu node is a choice, menu, or if. Finalize each child in
3454 # it.
3455
3456 if node.item is MENU:
3457 visible_if = self._make_and(visible_if, node.visibility)
3458
3459 # Propagate the menu node's dependencies to each child menu node.
3460 #
3461 # The recursive _finalize_tree() calls assume that the current
3462 # "level" in the tree has already had dependencies propagated. This
3463 # makes e.g. implicit submenu creation easier, because it needs to
3464 # look ahead.
3465 self._propagate_deps(node, visible_if)
3466
3467 # Finalize the children
3468 cur = node.list
3469 while cur:
3470 self._finalize_tree(cur, visible_if)
3471 cur = cur.next
3472
3473 elif node.item.__class__ is Symbol:
3474 # Add the node's non-node-specific properties (defaults, ranges,
3475 # etc.) to the Symbol
3476 self._add_props_to_sym(node)
3477
3478 # See if we can create an implicit menu rooted at the Symbol and
3479 # finalize each child menu node in that menu if so, like for the
3480 # choice/menu/if case above
3481 cur = node
3482 while cur.next and _auto_menu_dep(node, cur.next):
3483 # This also makes implicit submenu creation work recursively,
3484 # with implicit menus inside implicit menus
3485 self._finalize_tree(cur.next, visible_if)
3486 cur = cur.next
3487 cur.parent = node
3488
3489 if cur is not node:
3490 # Found symbols that should go in an implicit submenu. Tilt
3491 # them up above us.
3492 node.list = node.next
3493 node.next = cur.next
3494 cur.next = None
3495
3496
3497 if node.list:
3498 # We have a parent node with individually finalized child nodes. Do
3499 # final steps to finalize this "level" in the menu tree.
3500 _flatten(node.list)
3501 _remove_ifs(node)
3502
3503 # Empty choices (node.list None) are possible, so this needs to go
3504 # outside
3505 if node.item.__class__ is Choice:
3506 # Add the node's non-node-specific properties to the choice, like
3507 # _add_props_to_sym() does
3508 choice = node.item
3509 choice.direct_dep = self._make_or(choice.direct_dep, node.dep)
3510 choice.defaults += node.defaults
3511
3512 _finalize_choice(node)
3513
3514 def _propagate_deps(self, node, visible_if):
3515 # Propagates 'node's dependencies to its child menu nodes
3516
3517 # If the parent node holds a Choice, we use the Choice itself as the
3518 # parent dependency. This makes sense as the value (mode) of the choice
3519 # limits the visibility of the contained choice symbols. The C
3520 # implementation works the same way.
3521 #
3522 # Due to the similar interface, Choice works as a drop-in replacement
3523 # for Symbol here.
3524 basedep = node.item if node.item.__class__ is Choice else node.dep
3525
3526 cur = node.list
3527 while cur:
[cf2f109]3528 dep = cur.dep = self._make_and(cur.dep, basedep)
[f596dde]3529
3530 if cur.item.__class__ in _SYMBOL_CHOICE:
[cf2f109]3531 # Propagate 'visible if' and dependencies to the prompt
[f596dde]3532 if cur.prompt:
3533 cur.prompt = (cur.prompt[0],
[cf2f109]3534 self._make_and(
3535 cur.prompt[1],
3536 self._make_and(visible_if, dep)))
[f596dde]3537
3538 # Propagate dependencies to defaults
3539 if cur.defaults:
3540 cur.defaults = [(default, self._make_and(cond, dep))
3541 for default, cond in cur.defaults]
3542
3543 # Propagate dependencies to ranges
3544 if cur.ranges:
3545 cur.ranges = [(low, high, self._make_and(cond, dep))
3546 for low, high, cond in cur.ranges]
3547
3548 # Propagate dependencies to selects
3549 if cur.selects:
3550 cur.selects = [(target, self._make_and(cond, dep))
3551 for target, cond in cur.selects]
3552
3553 # Propagate dependencies to implies
3554 if cur.implies:
3555 cur.implies = [(target, self._make_and(cond, dep))
3556 for target, cond in cur.implies]
3557
[cf2f109]3558 elif cur.prompt: # Not a symbol/choice
3559 # Propagate dependencies to the prompt. 'visible if' is only
3560 # propagated to symbols/choices.
3561 cur.prompt = (cur.prompt[0],
3562 self._make_and(cur.prompt[1], dep))
[f596dde]3563
3564 cur = cur.next
3565
3566 def _add_props_to_sym(self, node):
3567 # Copies properties from the menu node 'node' up to its contained
3568 # symbol, and adds (weak) reverse dependencies to selected/implied
3569 # symbols.
3570 #
3571 # This can't be rolled into _propagate_deps(), because that function
3572 # traverses the menu tree roughly breadth-first, meaning properties on
3573 # symbols defined in multiple locations could end up in the wrong
3574 # order.
3575
3576 sym = node.item
3577
3578 # See the Symbol class docstring
3579 sym.direct_dep = self._make_or(sym.direct_dep, node.dep)
3580
3581 sym.defaults += node.defaults
3582 sym.ranges += node.ranges
3583 sym.selects += node.selects
3584 sym.implies += node.implies
3585
3586 # Modify the reverse dependencies of the selected symbol
3587 for target, cond in node.selects:
3588 target.rev_dep = self._make_or(
3589 target.rev_dep,
3590 self._make_and(sym, cond))
3591
3592 # Modify the weak reverse dependencies of the implied
3593 # symbol
3594 for target, cond in node.implies:
3595 target.weak_rev_dep = self._make_or(
3596 target.weak_rev_dep,
3597 self._make_and(sym, cond))
3598
3599 #
3600 # Misc.
3601 #
3602
3603 def _check_sym_sanity(self):
3604 # Checks various symbol properties that are handiest to check after
3605 # parsing. Only generates errors and warnings.
3606
3607 def num_ok(sym, type_):
3608 # Returns True if the (possibly constant) symbol 'sym' is valid as a value
3609 # for a symbol of type type_ (INT or HEX)
3610
3611 # 'not sym.nodes' implies a constant or undefined symbol, e.g. a plain
3612 # "123"
3613 if not sym.nodes:
3614 return _is_base_n(sym.name, _TYPE_TO_BASE[type_])
3615
3616 return sym.orig_type is type_
3617
3618 for sym in self.unique_defined_syms:
3619 if sym.orig_type in _BOOL_TRISTATE:
3620 # A helper function could be factored out here, but keep it
3621 # speedy/straightforward
3622
3623 for target_sym, _ in sym.selects:
3624 if target_sym.orig_type not in _BOOL_TRISTATE_UNKNOWN:
3625 self._warn("{} selects the {} symbol {}, which is not "
3626 "bool or tristate"
3627 .format(_name_and_loc(sym),
3628 TYPE_TO_STR[target_sym.orig_type],
3629 _name_and_loc(target_sym)))
3630
3631 for target_sym, _ in sym.implies:
3632 if target_sym.orig_type not in _BOOL_TRISTATE_UNKNOWN:
3633 self._warn("{} implies the {} symbol {}, which is not "
3634 "bool or tristate"
3635 .format(_name_and_loc(sym),
3636 TYPE_TO_STR[target_sym.orig_type],
3637 _name_and_loc(target_sym)))
3638
3639 elif sym.orig_type in _STRING_INT_HEX:
3640 for default, _ in sym.defaults:
3641 if default.__class__ is not Symbol:
3642 raise KconfigError(
3643 "the {} symbol {} has a malformed default {} -- expected "
3644 "a single symbol"
3645 .format(TYPE_TO_STR[sym.orig_type], _name_and_loc(sym),
3646 expr_str(default)))
3647
3648 if sym.orig_type is STRING:
3649 if not default.is_constant and not default.nodes and \
3650 not default.name.isupper():
3651 # 'default foo' on a string symbol could be either a symbol
3652 # reference or someone leaving out the quotes. Guess that
3653 # the quotes were left out if 'foo' isn't all-uppercase
3654 # (and no symbol named 'foo' exists).
3655 self._warn("style: quotes recommended around "
3656 "default value for string symbol "
3657 + _name_and_loc(sym))
3658
3659 elif not num_ok(default, sym.orig_type): # INT/HEX
3660 self._warn("the {0} symbol {1} has a non-{0} default {2}"
3661 .format(TYPE_TO_STR[sym.orig_type],
3662 _name_and_loc(sym),
3663 _name_and_loc(default)))
3664
3665 if sym.selects or sym.implies:
3666 self._warn("the {} symbol {} has selects or implies"
3667 .format(TYPE_TO_STR[sym.orig_type],
3668 _name_and_loc(sym)))
3669
3670 else: # UNKNOWN
3671 self._warn("{} defined without a type"
3672 .format(_name_and_loc(sym)))
3673
3674
3675 if sym.ranges:
3676 if sym.orig_type not in _INT_HEX:
3677 self._warn(
3678 "the {} symbol {} has ranges, but is not int or hex"
3679 .format(TYPE_TO_STR[sym.orig_type],
3680 _name_and_loc(sym)))
3681 else:
3682 for low, high, _ in sym.ranges:
3683 if not num_ok(low, sym.orig_type) or \
3684 not num_ok(high, sym.orig_type):
3685
3686 self._warn("the {0} symbol {1} has a non-{0} "
3687 "range [{2}, {3}]"
3688 .format(TYPE_TO_STR[sym.orig_type],
3689 _name_and_loc(sym),
3690 _name_and_loc(low),
3691 _name_and_loc(high)))
3692
3693 def _check_choice_sanity(self):
3694 # Checks various choice properties that are handiest to check after
3695 # parsing. Only generates errors and warnings.
3696
3697 def warn_select_imply(sym, expr, expr_type):
3698 msg = "the choice symbol {} is {} by the following symbols, but " \
3699 "select/imply has no effect on choice symbols" \
3700 .format(_name_and_loc(sym), expr_type)
3701
3702 # si = select/imply
3703 for si in split_expr(expr, OR):
3704 msg += "\n - " + _name_and_loc(split_expr(si, AND)[0])
3705
3706 self._warn(msg)
3707
3708 for choice in self.unique_choices:
3709 if choice.orig_type not in _BOOL_TRISTATE:
3710 self._warn("{} defined with type {}"
3711 .format(_name_and_loc(choice),
3712 TYPE_TO_STR[choice.orig_type]))
3713
3714 for node in choice.nodes:
3715 if node.prompt:
3716 break
3717 else:
3718 self._warn(_name_and_loc(choice) + " defined without a prompt")
3719
3720 for default, _ in choice.defaults:
3721 if default.__class__ is not Symbol:
3722 raise KconfigError(
3723 "{} has a malformed default {}"
3724 .format(_name_and_loc(choice), expr_str(default)))
3725
3726 if default.choice is not choice:
3727 self._warn("the default selection {} of {} is not "
3728 "contained in the choice"
3729 .format(_name_and_loc(default),
3730 _name_and_loc(choice)))
3731
3732 for sym in choice.syms:
3733 if sym.defaults:
3734 self._warn("default on the choice symbol {} will have "
3735 "no effect, as defaults do not affect choice "
3736 "symbols".format(_name_and_loc(sym)))
3737
3738 if sym.rev_dep is not sym.kconfig.n:
3739 warn_select_imply(sym, sym.rev_dep, "selected")
3740
3741 if sym.weak_rev_dep is not sym.kconfig.n:
3742 warn_select_imply(sym, sym.weak_rev_dep, "implied")
3743
3744 for node in sym.nodes:
3745 if node.parent.item is choice:
3746 if not node.prompt:
3747 self._warn("the choice symbol {} has no prompt"
3748 .format(_name_and_loc(sym)))
3749
3750 elif node.prompt:
3751 self._warn("the choice symbol {} is defined with a "
3752 "prompt outside the choice"
3753 .format(_name_and_loc(sym)))
3754
3755 def _parse_error(self, msg):
3756 raise KconfigError("{}couldn't parse '{}': {}".format(
3757 "" if self._filename is None else
3758 "{}:{}: ".format(self._filename, self._linenr),
3759 self._line.strip(), msg))
3760
3761 def _trailing_tokens_error(self):
3762 self._parse_error("extra tokens at end of line")
3763
3764 def _open(self, filename, mode):
3765 # open() wrapper:
3766 #
3767 # - Enable universal newlines mode on Python 2 to ease
3768 # interoperability between Linux and Windows. It's already the
3769 # default on Python 3.
3770 #
3771 # The "U" flag would currently work for both Python 2 and 3, but it's
3772 # deprecated on Python 3, so play it future-safe.
3773 #
[cf2f109]3774 # io.open() defaults to universal newlines on Python 2 (and is an
3775 # alias for open() on Python 3), but it returns 'unicode' strings and
3776 # slows things down:
[f596dde]3777 #
3778 # Parsing x86 Kconfigs on Python 2
3779 #
3780 # with open(..., "rU"):
3781 #
3782 # real 0m0.930s
3783 # user 0m0.905s
3784 # sys 0m0.025s
3785 #
3786 # with io.open():
3787 #
3788 # real 0m1.069s
3789 # user 0m1.040s
3790 # sys 0m0.029s
3791 #
3792 # There's no appreciable performance difference between "r" and
3793 # "rU" for parsing performance on Python 2.
3794 #
3795 # - For Python 3, force the encoding. Forcing the encoding on Python 2
3796 # turns strings into Unicode strings, which gets messy. Python 2
3797 # doesn't decode regular strings anyway.
3798 return open(filename, "rU" if mode == "r" else mode) if _IS_PY2 else \
3799 open(filename, mode, encoding=self._encoding)
3800
3801 def _check_undef_syms(self):
3802 # Prints warnings for all references to undefined symbols within the
3803 # Kconfig files
3804
3805 def is_num(s):
3806 # Returns True if the string 's' looks like a number.
3807 #
3808 # Internally, all operands in Kconfig are symbols, only undefined symbols
3809 # (which numbers usually are) get their name as their value.
3810 #
3811 # Only hex numbers that start with 0x/0X are classified as numbers.
3812 # Otherwise, symbols whose names happen to contain only the letters A-F
3813 # would trigger false positives.
3814
3815 try:
3816 int(s)
3817 except ValueError:
3818 if not s.startswith(("0x", "0X")):
3819 return False
3820
3821 try:
3822 int(s, 16)
3823 except ValueError:
3824 return False
3825
3826 return True
3827
3828 for sym in (self.syms.viewvalues if _IS_PY2 else self.syms.values)():
3829 # - sym.nodes empty means the symbol is undefined (has no
3830 # definition locations)
3831 #
3832 # - Due to Kconfig internals, numbers show up as undefined Kconfig
3833 # symbols, but shouldn't be flagged
3834 #
3835 # - The MODULES symbol always exists
3836 if not sym.nodes and not is_num(sym.name) and \
3837 sym.name != "MODULES":
3838
3839 msg = "undefined symbol {}:".format(sym.name)
3840 for node in self.node_iter():
3841 if sym in node.referenced:
3842 msg += "\n\n- Referenced at {}:{}:\n\n{}" \
3843 .format(node.filename, node.linenr, node)
3844 self._warn(msg)
3845
3846 def _warn(self, msg, filename=None, linenr=None):
3847 # For printing general warnings
3848
[cf2f109]3849 if not self.warn:
3850 return
[f596dde]3851
[cf2f109]3852 msg = "warning: " + msg
3853 if filename is not None:
3854 msg = "{}:{}: {}".format(filename, linenr, msg)
[f596dde]3855
[cf2f109]3856 self.warnings.append(msg)
3857 if self.warn_to_stderr:
3858 sys.stderr.write(msg + "\n")
[f596dde]3859
3860
3861class Symbol(object):
3862 """
3863 Represents a configuration symbol:
3864
3865 (menu)config FOO
3866 ...
3867
3868 The following attributes are available. They should be viewed as read-only,
3869 and some are implemented through @property magic (but are still efficient
3870 to access due to internal caching).
3871
3872 Note: Prompts, help texts, and locations are stored in the Symbol's
3873 MenuNode(s) rather than in the Symbol itself. Check the MenuNode class and
3874 the Symbol.nodes attribute. This organization matches the C tools.
3875
3876 name:
3877 The name of the symbol, e.g. "FOO" for 'config FOO'.
3878
3879 type:
3880 The type of the symbol. One of BOOL, TRISTATE, STRING, INT, HEX, UNKNOWN.
3881 UNKNOWN is for undefined symbols, (non-special) constant symbols, and
3882 symbols defined without a type.
3883
3884 When running without modules (MODULES having the value n), TRISTATE
3885 symbols magically change type to BOOL. This also happens for symbols
3886 within choices in "y" mode. This matches the C tools, and makes sense for
3887 menuconfig-like functionality.
3888
3889 orig_type:
3890 The type as given in the Kconfig file, without any magic applied. Used
3891 when printing the symbol.
3892
3893 str_value:
3894 The value of the symbol as a string. Gives the value for string/int/hex
3895 symbols. For bool/tristate symbols, gives "n", "m", or "y".
3896
3897 This is the symbol value that's used in relational expressions
3898 (A = B, A != B, etc.)
3899
3900 Gotcha: For int/hex symbols, the exact format of the value must often be
3901 preserved (e.g., when writing a .config file), hence why you can't get it
3902 directly as an int. Do int(int_sym.str_value) or
3903 int(hex_sym.str_value, 16) to get the integer value.
3904
3905 tri_value:
3906 The tristate value of the symbol as an integer. One of 0, 1, 2,
3907 representing n, m, y. Always 0 (n) for non-bool/tristate symbols.
3908
3909 This is the symbol value that's used outside of relation expressions
3910 (A, !A, A && B, A || B).
3911
3912 assignable:
3913 A tuple containing the tristate user values that can currently be
3914 assigned to the symbol (that would be respected), ordered from lowest (0,
3915 representing n) to highest (2, representing y). This corresponds to the
3916 selections available in the menuconfig interface. The set of assignable
3917 values is calculated from the symbol's visibility and selects/implies.
3918
3919 Returns the empty set for non-bool/tristate symbols and for symbols with
3920 visibility n. The other possible values are (0, 2), (0, 1, 2), (1, 2),
3921 (1,), and (2,). A (1,) or (2,) result means the symbol is visible but
3922 "locked" to m or y through a select, perhaps in combination with the
3923 visibility. menuconfig represents this as -M- and -*-, respectively.
3924
3925 For string/hex/int symbols, check if Symbol.visibility is non-0 (non-n)
3926 instead to determine if the value can be changed.
3927
3928 Some handy 'assignable' idioms:
3929
3930 # Is 'sym' an assignable (visible) bool/tristate symbol?
3931 if sym.assignable:
3932 # What's the highest value it can be assigned? [-1] in Python
3933 # gives the last element.
3934 sym_high = sym.assignable[-1]
3935
3936 # The lowest?
3937 sym_low = sym.assignable[0]
3938
3939 # Can the symbol be set to at least m?
3940 if sym.assignable[-1] >= 1:
3941 ...
3942
3943 # Can the symbol be set to m?
3944 if 1 in sym.assignable:
3945 ...
3946
3947 visibility:
3948 The visibility of the symbol. One of 0, 1, 2, representing n, m, y. See
3949 the module documentation for an overview of symbol values and visibility.
3950
3951 user_value:
3952 The user value of the symbol. None if no user value has been assigned
3953 (via Kconfig.load_config() or Symbol.set_value()).
3954
3955 Holds 0, 1, or 2 for bool/tristate symbols, and a string for the other
3956 symbol types.
3957
3958 WARNING: Do not assign directly to this. It will break things. Use
3959 Symbol.set_value().
3960
3961 config_string:
3962 The .config assignment string that would get written out for the symbol
3963 by Kconfig.write_config(). Returns the empty string if no .config
3964 assignment would get written out.
3965
3966 In general, visible symbols, symbols with (active) defaults, and selected
3967 symbols get written out. This includes all non-n-valued bool/tristate
3968 symbols, and all visible string/int/hex symbols.
3969
3970 Symbols with the (no longer needed) 'option env=...' option generate no
3971 configuration output, and neither does the special
3972 'option defconfig_list' symbol.
3973
3974 Tip: This field is useful when generating custom configuration output,
3975 even for non-.config-like formats. To write just the symbols that would
3976 get written out to .config files, do this:
3977
3978 if sym.config_string:
3979 *Write symbol, e.g. by looking sym.str_value*
3980
3981 This is a superset of the symbols written out by write_autoconf().
3982 That function skips all n-valued symbols.
3983
3984 There usually won't be any great harm in just writing all symbols either,
3985 though you might get some special symbols and possibly some "redundant"
3986 n-valued symbol entries in there.
3987
3988 nodes:
3989 A list of MenuNodes for this symbol. Will contain a single MenuNode for
3990 most symbols. Undefined and constant symbols have an empty nodes list.
3991 Symbols defined in multiple locations get one node for each location.
3992
3993 choice:
3994 Holds the parent Choice for choice symbols, and None for non-choice
3995 symbols. Doubles as a flag for whether a symbol is a choice symbol.
3996
3997 defaults:
3998 List of (default, cond) tuples for the symbol's 'default' properties. For
3999 example, 'default A && B if C || D' is represented as
4000 ((AND, A, B), (OR, C, D)). If no condition was given, 'cond' is
4001 self.kconfig.y.
4002
4003 Note that 'depends on' and parent dependencies are propagated to
4004 'default' conditions.
4005
4006 selects:
4007 List of (symbol, cond) tuples for the symbol's 'select' properties. For
4008 example, 'select A if B && C' is represented as (A, (AND, B, C)). If no
4009 condition was given, 'cond' is self.kconfig.y.
4010
4011 Note that 'depends on' and parent dependencies are propagated to 'select'
4012 conditions.
4013
4014 implies:
4015 Like 'selects', for imply.
4016
4017 ranges:
4018 List of (low, high, cond) tuples for the symbol's 'range' properties. For
4019 example, 'range 1 2 if A' is represented as (1, 2, A). If there is no
[cf2f109]4020 condition, 'cond' is self.kconfig.y.
[f596dde]4021
4022 Note that 'depends on' and parent dependencies are propagated to 'range'
4023 conditions.
4024
4025 Gotcha: 1 and 2 above will be represented as (undefined) Symbols rather
4026 than plain integers. Undefined symbols get their name as their string
4027 value, so this works out. The C tools work the same way.
4028
4029 rev_dep:
4030 Reverse dependency expression from other symbols selecting this symbol.
4031 Multiple selections get ORed together. A condition on a select is ANDed
4032 with the selecting symbol.
4033
4034 For example, if A has 'select FOO' and B has 'select FOO if C', then
4035 FOO's rev_dep will be (OR, A, (AND, B, C)).
4036
4037 weak_rev_dep:
4038 Like rev_dep, for imply.
4039
4040 direct_dep:
[cf2f109]4041 The direct ('depends on') dependencies for the symbol, or self.kconfig.y
4042 if there are no direct dependencies.
[f596dde]4043
[cf2f109]4044 This attribute includes any dependencies from surrounding menus and if's.
4045 Those get propagated to the direct dependencies, and the resulting direct
4046 dependencies in turn get propagated to the conditions of all properties.
4047
4048 If the symbol is defined in multiple locations, the dependencies from the
4049 different locations get ORed together.
[f596dde]4050
4051 referenced:
4052 A set() with all symbols and choices referenced in the properties and
4053 property conditions of the symbol.
4054
[cf2f109]4055 Also includes dependencies from surrounding menus and if's, because those
4056 get propagated to the symbol (see the 'Intro to symbol values' section in
4057 the module docstring).
4058
[f596dde]4059 Choices appear in the dependencies of choice symbols.
4060
[cf2f109]4061 For the following definitions, only B and not C appears in A's
4062 'referenced'. To get transitive references, you'll have to recursively
4063 expand 'references' until no new items appear.
4064
4065 config A
4066 bool
4067 depends on B
4068
4069 config B
4070 bool
4071 depends on C
4072
4073 config C
4074 bool
4075
4076 See the Symbol.direct_dep attribute if you're only interested in the
4077 direct dependencies of the symbol (its 'depends on'). You can extract the
4078 symbols in it with the global expr_items() function.
4079
[f596dde]4080 env_var:
4081 If the Symbol has an 'option env="FOO"' option, this contains the name
4082 ("FOO") of the environment variable. None for symbols without no
4083 'option env'.
4084
4085 'option env="FOO"' acts like a 'default' property whose value is the
4086 value of $FOO.
4087
4088 Symbols with 'option env' are never written out to .config files, even if
4089 they are visible. env_var corresponds to a flag called SYMBOL_AUTO in the
4090 C implementation.
4091
4092 is_allnoconfig_y:
4093 True if the symbol has 'option allnoconfig_y' set on it. This has no
4094 effect internally (except when printing symbols), but can be checked by
4095 scripts.
4096
4097 is_constant:
4098 True if the symbol is a constant (quoted) symbol.
4099
4100 kconfig:
4101 The Kconfig instance this symbol is from.
4102 """
4103 __slots__ = (
4104 "_cached_assignable",
4105 "_cached_str_val",
4106 "_cached_tri_val",
4107 "_cached_vis",
4108 "_dependents",
4109 "_old_val",
4110 "_visited",
4111 "_was_set",
4112 "_write_to_conf",
4113 "choice",
4114 "defaults",
4115 "direct_dep",
4116 "env_var",
4117 "implies",
4118 "is_allnoconfig_y",
4119 "is_constant",
4120 "kconfig",
4121 "name",
4122 "nodes",
4123 "orig_type",
4124 "ranges",
4125 "rev_dep",
4126 "selects",
4127 "user_value",
4128 "weak_rev_dep",
4129 )
4130
4131 #
4132 # Public interface
4133 #
4134
4135 @property
4136 def type(self):
4137 """
4138 See the class documentation.
4139 """
4140 if self.orig_type is TRISTATE and \
4141 ((self.choice and self.choice.tri_value == 2) or
4142 not self.kconfig.modules.tri_value):
4143
4144 return BOOL
4145
4146 return self.orig_type
4147
4148 @property
4149 def str_value(self):
4150 """
4151 See the class documentation.
4152 """
4153 if self._cached_str_val is not None:
4154 return self._cached_str_val
4155
4156 if self.orig_type in _BOOL_TRISTATE:
4157 # Also calculates the visibility, so invalidation safe
4158 self._cached_str_val = TRI_TO_STR[self.tri_value]
4159 return self._cached_str_val
4160
4161 # As a quirk of Kconfig, undefined symbols get their name as their
4162 # string value. This is why things like "FOO = bar" work for seeing if
4163 # FOO has the value "bar".
4164 if not self.orig_type: # UNKNOWN
4165 self._cached_str_val = self.name
4166 return self.name
4167
4168 val = ""
4169 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4170 # function call (property magic)
4171 vis = self.visibility
4172
4173 self._write_to_conf = (vis != 0)
4174
4175 if self.orig_type in _INT_HEX:
4176 # The C implementation checks the user value against the range in a
4177 # separate code path (post-processing after loading a .config).
4178 # Checking all values here instead makes more sense for us. It
4179 # requires that we check for a range first.
4180
4181 base = _TYPE_TO_BASE[self.orig_type]
4182
4183 # Check if a range is in effect
4184 for low_expr, high_expr, cond in self.ranges:
4185 if expr_value(cond):
4186 has_active_range = True
4187
4188 # The zeros are from the C implementation running strtoll()
4189 # on empty strings
4190 low = int(low_expr.str_value, base) if \
4191 _is_base_n(low_expr.str_value, base) else 0
4192 high = int(high_expr.str_value, base) if \
4193 _is_base_n(high_expr.str_value, base) else 0
4194
4195 break
4196 else:
4197 has_active_range = False
4198
4199 # Defaults are used if the symbol is invisible, lacks a user value,
4200 # or has an out-of-range user value
4201 use_defaults = True
4202
4203 if vis and self.user_value:
4204 user_val = int(self.user_value, base)
4205 if has_active_range and not low <= user_val <= high:
4206 num2str = str if base == 10 else hex
4207 self.kconfig._warn(
4208 "user value {} on the {} symbol {} ignored due to "
4209 "being outside the active range ([{}, {}]) -- falling "
4210 "back on defaults"
4211 .format(num2str(user_val), TYPE_TO_STR[self.orig_type],
4212 _name_and_loc(self),
4213 num2str(low), num2str(high)))
4214 else:
4215 # If the user value is well-formed and satisfies range
4216 # contraints, it is stored in exactly the same form as
4217 # specified in the assignment (with or without "0x", etc.)
4218 val = self.user_value
4219 use_defaults = False
4220
4221 if use_defaults:
4222 # No user value or invalid user value. Look at defaults.
4223
4224 # Used to implement the warning below
4225 has_default = False
4226
4227 for sym, cond in self.defaults:
4228 if expr_value(cond):
4229 has_default = self._write_to_conf = True
4230
4231 val = sym.str_value
4232
4233 if _is_base_n(val, base):
4234 val_num = int(val, base)
4235 else:
4236 val_num = 0 # strtoll() on empty string
4237
4238 break
4239 else:
4240 val_num = 0 # strtoll() on empty string
4241
4242 # This clamping procedure runs even if there's no default
4243 if has_active_range:
4244 clamp = None
4245 if val_num < low:
4246 clamp = low
4247 elif val_num > high:
4248 clamp = high
4249
4250 if clamp is not None:
4251 # The value is rewritten to a standard form if it is
4252 # clamped
4253 val = str(clamp) \
4254 if self.orig_type is INT else \
4255 hex(clamp)
4256
4257 if has_default:
4258 num2str = str if base == 10 else hex
4259 self.kconfig._warn(
4260 "default value {} on {} clamped to {} due to "
4261 "being outside the active range ([{}, {}])"
4262 .format(val_num, _name_and_loc(self),
4263 num2str(clamp), num2str(low),
4264 num2str(high)))
4265
4266 elif self.orig_type is STRING:
4267 if vis and self.user_value is not None:
4268 # If the symbol is visible and has a user value, use that
4269 val = self.user_value
4270 else:
4271 # Otherwise, look at defaults
4272 for sym, cond in self.defaults:
4273 if expr_value(cond):
4274 val = sym.str_value
4275 self._write_to_conf = True
4276 break
4277
4278 # env_var corresponds to SYMBOL_AUTO in the C implementation, and is
4279 # also set on the defconfig_list symbol there. Test for the
4280 # defconfig_list symbol explicitly instead here, to avoid a nonsensical
4281 # env_var setting and the defconfig_list symbol being printed
4282 # incorrectly. This code is pretty cold anyway.
4283 if self.env_var is not None or self is self.kconfig.defconfig_list:
4284 self._write_to_conf = False
4285
4286 self._cached_str_val = val
4287 return val
4288
4289 @property
4290 def tri_value(self):
4291 """
4292 See the class documentation.
4293 """
4294 if self._cached_tri_val is not None:
4295 return self._cached_tri_val
4296
4297 if self.orig_type not in _BOOL_TRISTATE:
4298 if self.orig_type: # != UNKNOWN
4299 # Would take some work to give the location here
4300 self.kconfig._warn(
4301 "The {} symbol {} is being evaluated in a logical context "
4302 "somewhere. It will always evaluate to n."
4303 .format(TYPE_TO_STR[self.orig_type], _name_and_loc(self)))
4304
4305 self._cached_tri_val = 0
4306 return 0
4307
4308 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4309 # function call (property magic)
4310 vis = self.visibility
4311 self._write_to_conf = (vis != 0)
4312
4313 val = 0
4314
4315 if not self.choice:
4316 # Non-choice symbol
4317
4318 if vis and self.user_value is not None:
4319 # If the symbol is visible and has a user value, use that
4320 val = min(self.user_value, vis)
4321
4322 else:
4323 # Otherwise, look at defaults and weak reverse dependencies
4324 # (implies)
4325
4326 for default, cond in self.defaults:
4327 dep_val = expr_value(cond)
4328 if dep_val:
4329 val = min(expr_value(default), dep_val)
4330 if val:
4331 self._write_to_conf = True
4332 break
4333
4334 # Weak reverse dependencies are only considered if our
4335 # direct dependencies are met
4336 dep_val = expr_value(self.weak_rev_dep)
4337 if dep_val and expr_value(self.direct_dep):
4338 val = max(dep_val, val)
4339 self._write_to_conf = True
4340
4341 # Reverse (select-related) dependencies take precedence
4342 dep_val = expr_value(self.rev_dep)
4343 if dep_val:
4344 if expr_value(self.direct_dep) < dep_val:
4345 self._warn_select_unsatisfied_deps()
4346
4347 val = max(dep_val, val)
4348 self._write_to_conf = True
4349
4350 # m is promoted to y for (1) bool symbols and (2) symbols with a
4351 # weak_rev_dep (from imply) of y
4352 if val == 1 and \
4353 (self.type is BOOL or expr_value(self.weak_rev_dep) == 2):
4354 val = 2
4355
4356 elif vis == 2:
4357 # Visible choice symbol in y-mode choice. The choice mode limits
4358 # the visibility of choice symbols, so it's sufficient to just
4359 # check the visibility of the choice symbols themselves.
4360 val = 2 if self.choice.selection is self else 0
4361
4362 elif vis and self.user_value:
4363 # Visible choice symbol in m-mode choice, with set non-0 user value
4364 val = 1
4365
4366 self._cached_tri_val = val
4367 return val
4368
4369 @property
4370 def assignable(self):
4371 """
4372 See the class documentation.
4373 """
4374 if self._cached_assignable is None:
4375 self._cached_assignable = self._assignable()
4376
4377 return self._cached_assignable
4378
4379 @property
4380 def visibility(self):
4381 """
4382 See the class documentation.
4383 """
4384 if self._cached_vis is None:
4385 self._cached_vis = _visibility(self)
4386
4387 return self._cached_vis
4388
4389 @property
4390 def config_string(self):
4391 """
4392 See the class documentation.
4393 """
[cf2f109]4394 # _write_to_conf is determined when the value is calculated. This is a
4395 # hidden function call due to property magic.
[f596dde]4396 val = self.str_value
4397 if not self._write_to_conf:
4398 return ""
4399
4400 if self.orig_type in _BOOL_TRISTATE:
4401 return "{}{}={}\n" \
4402 .format(self.kconfig.config_prefix, self.name, val) \
4403 if val != "n" else \
4404 "# {}{} is not set\n" \
4405 .format(self.kconfig.config_prefix, self.name)
4406
4407 if self.orig_type in _INT_HEX:
4408 return "{}{}={}\n" \
4409 .format(self.kconfig.config_prefix, self.name, val)
4410
4411 # sym.orig_type is STRING
4412 return '{}{}="{}"\n' \
4413 .format(self.kconfig.config_prefix, self.name, escape(val))
4414
4415 def set_value(self, value):
4416 """
4417 Sets the user value of the symbol.
4418
4419 Equal in effect to assigning the value to the symbol within a .config
4420 file. For bool and tristate symbols, use the 'assignable' attribute to
4421 check which values can currently be assigned. Setting values outside
4422 'assignable' will cause Symbol.user_value to differ from
4423 Symbol.str/tri_value (be truncated down or up).
4424
4425 Setting a choice symbol to 2 (y) sets Choice.user_selection to the
4426 choice symbol in addition to setting Symbol.user_value.
4427 Choice.user_selection is considered when the choice is in y mode (the
4428 "normal" mode).
4429
4430 Other symbols that depend (possibly indirectly) on this symbol are
4431 automatically recalculated to reflect the assigned value.
4432
4433 value:
4434 The user value to give to the symbol. For bool and tristate symbols,
4435 n/m/y can be specified either as 0/1/2 (the usual format for tristate
4436 values in Kconfiglib) or as one of the strings "n"/"m"/"y". For other
4437 symbol types, pass a string.
4438
4439 Values that are invalid for the type (such as "foo" or 1 (m) for a
4440 BOOL or "0x123" for an INT) are ignored and won't be stored in
4441 Symbol.user_value. Kconfiglib will print a warning by default for
4442 invalid assignments, and set_value() will return False.
4443
4444 Returns True if the value is valid for the type of the symbol, and
4445 False otherwise. This only looks at the form of the value. For BOOL and
4446 TRISTATE symbols, check the Symbol.assignable attribute to see what
4447 values are currently in range and would actually be reflected in the
4448 value of the symbol. For other symbol types, check whether the
4449 visibility is non-n.
4450 """
4451 # If the new user value matches the old, nothing changes, and we can
4452 # save some work.
4453 #
4454 # This optimization is skipped for choice symbols: Setting a choice
4455 # symbol's user value to y might change the state of the choice, so it
4456 # wouldn't be safe (symbol user values always match the values set in a
4457 # .config file or via set_value(), and are never implicitly updated).
4458 if value == self.user_value and not self.choice:
4459 self._was_set = True
4460 return True
4461
4462 # Check if the value is valid for our type
4463 if not (self.orig_type is BOOL and value in (2, 0, "y", "n") or
4464 self.orig_type is TRISTATE and value in (2, 1, 0, "y", "m", "n") or
4465 (value.__class__ is str and
4466 (self.orig_type is STRING or
4467 self.orig_type is INT and _is_base_n(value, 10) or
4468 self.orig_type is HEX and _is_base_n(value, 16)
4469 and int(value, 16) >= 0))):
4470
4471 # Display tristate values as n, m, y in the warning
4472 self.kconfig._warn(
4473 "the value {} is invalid for {}, which has type {} -- "
4474 "assignment ignored"
4475 .format(TRI_TO_STR[value] if value in (0, 1, 2) else
4476 "'{}'".format(value),
4477 _name_and_loc(self), TYPE_TO_STR[self.orig_type]))
4478
4479 return False
4480
4481 if self.orig_type in _BOOL_TRISTATE and value in ("y", "m", "n"):
4482 value = STR_TO_TRI[value]
4483
4484 self.user_value = value
4485 self._was_set = True
4486
4487 if self.choice and value == 2:
4488 # Setting a choice symbol to y makes it the user selection of the
4489 # choice. Like for symbol user values, the user selection is not
4490 # guaranteed to match the actual selection of the choice, as
4491 # dependencies come into play.
4492 self.choice.user_selection = self
4493 self.choice._was_set = True
4494 self.choice._rec_invalidate()
4495 else:
4496 self._rec_invalidate_if_has_prompt()
4497
4498 return True
4499
4500 def unset_value(self):
4501 """
[cf2f109]4502 Removes any user value from the symbol, as if the symbol had never
4503 gotten a user value via Kconfig.load_config() or Symbol.set_value().
[f596dde]4504 """
4505 if self.user_value is not None:
4506 self.user_value = None
4507 self._rec_invalidate_if_has_prompt()
4508
4509 @property
4510 def referenced(self):
4511 """
4512 See the class documentation.
4513 """
4514 return {item for node in self.nodes for item in node.referenced}
4515
4516 def __repr__(self):
4517 """
4518 Returns a string with information about the symbol (including its name,
4519 value, visibility, and location(s)) when it is evaluated on e.g. the
4520 interactive Python prompt.
4521 """
4522 fields = ["symbol " + self.name, TYPE_TO_STR[self.type]]
4523
4524 for node in self.nodes:
4525 if node.prompt:
4526 fields.append('"{}"'.format(node.prompt[0]))
4527
4528 # Only add quotes for non-bool/tristate symbols
4529 fields.append("value " +
4530 (self.str_value
4531 if self.orig_type in _BOOL_TRISTATE else
4532 '"{}"'.format(self.str_value)))
4533
4534 if not self.is_constant:
4535 # These aren't helpful to show for constant symbols
4536
4537 if self.user_value is not None:
4538 # Only add quotes for non-bool/tristate symbols
4539 fields.append("user value " +
4540 (TRI_TO_STR[self.user_value]
4541 if self.orig_type in _BOOL_TRISTATE else
4542 '"{}"'.format(self.user_value)))
4543
4544 fields.append("visibility " + TRI_TO_STR[self.visibility])
4545
4546 if self.choice:
4547 fields.append("choice symbol")
4548
4549 if self.is_allnoconfig_y:
4550 fields.append("allnoconfig_y")
4551
4552 if self is self.kconfig.defconfig_list:
4553 fields.append("is the defconfig_list symbol")
4554
4555 if self.env_var is not None:
4556 fields.append("from environment variable " + self.env_var)
4557
4558 if self is self.kconfig.modules:
4559 fields.append("is the modules symbol")
4560
4561 fields.append("direct deps " +
4562 TRI_TO_STR[expr_value(self.direct_dep)])
4563
4564 if self.nodes:
4565 for node in self.nodes:
4566 fields.append("{}:{}".format(node.filename, node.linenr))
4567 else:
4568 fields.append("constant" if self.is_constant else "undefined")
4569
4570 return "<{}>".format(", ".join(fields))
4571
4572 def __str__(self):
4573 """
[cf2f109]4574 Returns a string representation of the symbol when it is printed.
4575 Matches the Kconfig format, with any parent dependencies propagated to
4576 the 'depends on' condition.
[f596dde]4577
4578 The string is constructed by joining the strings returned by
4579 MenuNode.__str__() for each of the symbol's menu nodes, so symbols
4580 defined in multiple locations will return a string with all
4581 definitions.
4582
4583 The returned string does not end in a newline. An empty string is
4584 returned for undefined and constant symbols.
4585 """
4586 return self.custom_str(standard_sc_expr_str)
4587
4588 def custom_str(self, sc_expr_str_fn):
4589 """
4590 Works like Symbol.__str__(), but allows a custom format to be used for
4591 all symbol/choice references. See expr_str().
4592 """
4593 return "\n\n".join(node.custom_str(sc_expr_str_fn)
4594 for node in self.nodes)
4595
4596 #
4597 # Private methods
4598 #
4599
4600 def __init__(self):
4601 """
4602 Symbol constructor -- not intended to be called directly by Kconfiglib
4603 clients.
4604 """
4605 # These attributes are always set on the instance from outside and
4606 # don't need defaults:
4607 # kconfig
4608 # direct_dep
4609 # is_constant
4610 # name
4611 # rev_dep
4612 # weak_rev_dep
4613
4614 self.orig_type = UNKNOWN
4615 self.defaults = []
4616 self.selects = []
4617 self.implies = []
4618 self.ranges = []
4619
4620 self.nodes = []
4621
4622 self.user_value = \
4623 self.choice = \
4624 self.env_var = \
4625 self._cached_str_val = self._cached_tri_val = self._cached_vis = \
4626 self._cached_assignable = None
4627
4628 # _write_to_conf is calculated along with the value. If True, the
4629 # Symbol gets a .config entry.
4630
4631 self.is_allnoconfig_y = \
4632 self._was_set = \
4633 self._write_to_conf = False
4634
4635 # See Kconfig._build_dep()
4636 self._dependents = set()
4637
4638 # Used during dependency loop detection and (independently) in
4639 # node_iter()
4640 self._visited = 0
4641
4642 def _assignable(self):
4643 # Worker function for the 'assignable' attribute
4644
4645 if self.orig_type not in _BOOL_TRISTATE:
4646 return ()
4647
4648 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
4649 # function call (property magic)
4650 vis = self.visibility
4651 if not vis:
4652 return ()
4653
4654 rev_dep_val = expr_value(self.rev_dep)
4655
4656 if vis == 2:
4657 if self.choice:
4658 return (2,)
4659
4660 if not rev_dep_val:
4661 if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
4662 return (0, 2)
4663 return (0, 1, 2)
4664
4665 if rev_dep_val == 2:
4666 return (2,)
4667
4668 # rev_dep_val == 1
4669
4670 if self.type is BOOL or expr_value(self.weak_rev_dep) == 2:
4671 return (2,)
4672 return (1, 2)
4673
4674 # vis == 1
4675
4676 # Must be a tristate here, because bool m visibility gets promoted to y
4677
4678 if not rev_dep_val:
4679 return (0, 1) if expr_value(self.weak_rev_dep) != 2 else (0, 2)
4680
4681 if rev_dep_val == 2:
4682 return (2,)
4683
4684 # vis == rev_dep_val == 1
4685
4686 return (1,)
4687
4688 def _invalidate(self):
4689 # Marks the symbol as needing to be recalculated
4690
4691 self._cached_str_val = self._cached_tri_val = self._cached_vis = \
4692 self._cached_assignable = None
4693
4694 def _rec_invalidate(self):
4695 # Invalidates the symbol and all items that (possibly) depend on it
4696
4697 if self is self.kconfig.modules:
4698 # Invalidating MODULES has wide-ranging effects
4699 self.kconfig._invalidate_all()
4700 else:
4701 self._invalidate()
4702
4703 for item in self._dependents:
4704 # _cached_vis doubles as a flag that tells us whether 'item'
4705 # has cached values, because it's calculated as a side effect
4706 # of calculating all other (non-constant) cached values.
4707 #
4708 # If item._cached_vis is None, it means there can't be cached
4709 # values on other items that depend on 'item', because if there
4710 # were, some value on 'item' would have been calculated and
4711 # item._cached_vis set as a side effect. It's therefore safe to
4712 # stop the invalidation at symbols with _cached_vis None.
4713 #
4714 # This approach massively speeds up scripts that set a lot of
4715 # values, vs simply invalidating all possibly dependent symbols
4716 # (even when you already have a list of all the dependent
4717 # symbols, because some symbols get huge dependency trees).
4718 #
4719 # This gracefully handles dependency loops too, which is nice
4720 # for choices, where the choice depends on the choice symbols
4721 # and vice versa.
4722 if item._cached_vis is not None:
4723 item._rec_invalidate()
4724
4725 def _rec_invalidate_if_has_prompt(self):
4726 # Invalidates the symbol and its dependent symbols, but only if the
4727 # symbol has a prompt. User values never have an effect on promptless
4728 # symbols, so we skip invalidation for them as an optimization.
4729 #
4730 # This also prevents constant (quoted) symbols from being invalidated
4731 # if set_value() is called on them, which would cause them to lose
4732 # their value and break things.
4733 #
4734 # Prints a warning if the symbol has no prompt. In some contexts (e.g.
4735 # when loading a .config files) assignments to promptless symbols are
4736 # normal and expected, so the warning can be disabled.
4737
4738 for node in self.nodes:
4739 if node.prompt:
4740 self._rec_invalidate()
4741 return
4742
[cf2f109]4743 if self.kconfig._warn_no_prompt:
[f596dde]4744 self.kconfig._warn(_name_and_loc(self) + " has no prompt, meaning "
4745 "user values have no effect on it")
4746
4747 def _str_default(self):
4748 # write_min_config() helper function. Returns the value the symbol
4749 # would get from defaults if it didn't have a user value. Uses exactly
4750 # the same algorithm as the C implementation (though a bit cleaned up),
4751 # for compatibility.
4752
4753 if self.orig_type in _BOOL_TRISTATE:
4754 val = 0
4755
4756 # Defaults, selects, and implies do not affect choice symbols
4757 if not self.choice:
4758 for default, cond in self.defaults:
4759 cond_val = expr_value(cond)
4760 if cond_val:
4761 val = min(expr_value(default), cond_val)
4762 break
4763
4764 val = max(expr_value(self.rev_dep),
4765 expr_value(self.weak_rev_dep),
4766 val)
4767
4768 # Transpose mod to yes if type is bool (possibly due to modules
4769 # being disabled)
4770 if val == 1 and self.type is BOOL:
4771 val = 2
4772
4773 return TRI_TO_STR[val]
4774
4775 if self.orig_type in _STRING_INT_HEX:
4776 for default, cond in self.defaults:
4777 if expr_value(cond):
4778 return default.str_value
4779
4780 return ""
4781
4782 def _warn_select_unsatisfied_deps(self):
4783 # Helper for printing an informative warning when a symbol with
4784 # unsatisfied direct dependencies (dependencies from 'depends on', ifs,
4785 # and menus) is selected by some other symbol. Also warn if a symbol
4786 # whose direct dependencies evaluate to m is selected to y.
4787
4788 msg = "{} has direct dependencies {} with value {}, but is " \
4789 "currently being {}-selected by the following symbols:" \
4790 .format(_name_and_loc(self), expr_str(self.direct_dep),
4791 TRI_TO_STR[expr_value(self.direct_dep)],
4792 TRI_TO_STR[expr_value(self.rev_dep)])
4793
4794 # The reverse dependencies from each select are ORed together
4795 for select in split_expr(self.rev_dep, OR):
4796 if expr_value(select) <= expr_value(self.direct_dep):
4797 # Only include selects that exceed the direct dependencies
4798 continue
4799
4800 # - 'select A if B' turns into A && B
4801 # - 'select A' just turns into A
4802 #
4803 # In both cases, we can split on AND and pick the first operand
4804 selecting_sym = split_expr(select, AND)[0]
4805
4806 msg += "\n - {}, with value {}, direct dependencies {} " \
4807 "(value: {})" \
4808 .format(_name_and_loc(selecting_sym),
4809 selecting_sym.str_value,
4810 expr_str(selecting_sym.direct_dep),
4811 TRI_TO_STR[expr_value(selecting_sym.direct_dep)])
4812
4813 if select.__class__ is tuple:
4814 msg += ", and select condition {} (value: {})" \
4815 .format(expr_str(select[2]),
4816 TRI_TO_STR[expr_value(select[2])])
4817
4818 self.kconfig._warn(msg)
4819
4820
4821class Choice(object):
4822 """
4823 Represents a choice statement:
4824
4825 choice
4826 ...
4827 endchoice
4828
4829 The following attributes are available on Choice instances. They should be
4830 treated as read-only, and some are implemented through @property magic (but
4831 are still efficient to access due to internal caching).
4832
4833 Note: Prompts, help texts, and locations are stored in the Choice's
4834 MenuNode(s) rather than in the Choice itself. Check the MenuNode class and
4835 the Choice.nodes attribute. This organization matches the C tools.
4836
4837 name:
4838 The name of the choice, e.g. "FOO" for 'choice FOO', or None if the
4839 Choice has no name.
4840
4841 type:
4842 The type of the choice. One of BOOL, TRISTATE, UNKNOWN. UNKNOWN is for
4843 choices defined without a type where none of the contained symbols have a
4844 type either (otherwise the choice inherits the type of the first symbol
4845 defined with a type).
4846
4847 When running without modules (CONFIG_MODULES=n), TRISTATE choices
4848 magically change type to BOOL. This matches the C tools, and makes sense
4849 for menuconfig-like functionality.
4850
4851 orig_type:
4852 The type as given in the Kconfig file, without any magic applied. Used
4853 when printing the choice.
4854
4855 tri_value:
4856 The tristate value (mode) of the choice. A choice can be in one of three
4857 modes:
4858
4859 0 (n) - The choice is disabled and no symbols can be selected. For
4860 visible choices, this mode is only possible for choices with
4861 the 'optional' flag set (see kconfig-language.txt).
4862
4863 1 (m) - Any number of choice symbols can be set to m, the rest will
4864 be n.
4865
4866 2 (y) - One symbol will be y, the rest n.
4867
4868 Only tristate choices can be in m mode. The visibility of the choice is
4869 an upper bound on the mode, and the mode in turn is an upper bound on the
4870 visibility of the choice symbols.
4871
4872 To change the mode, use Choice.set_value().
4873
4874 Implementation note:
4875 The C tools internally represent choices as a type of symbol, with
4876 special-casing in many code paths. This is why there is a lot of
4877 similarity to Symbol. The value (mode) of a choice is really just a
4878 normal symbol value, and an implicit reverse dependency forces its
4879 lower bound to m for visible non-optional choices (the reverse
4880 dependency is 'm && <visibility>').
4881
4882 Symbols within choices get the choice propagated as a dependency to
4883 their properties. This turns the mode of the choice into an upper bound
4884 on e.g. the visibility of choice symbols, and explains the gotcha
4885 related to printing choice symbols mentioned in the module docstring.
4886
4887 Kconfiglib uses a separate Choice class only because it makes the code
4888 and interface less confusing (especially in a user-facing interface).
4889 Corresponding attributes have the same name in the Symbol and Choice
4890 classes, for consistency and compatibility.
4891
4892 assignable:
4893 See the symbol class documentation. Gives the assignable values (modes).
4894
4895 visibility:
4896 See the Symbol class documentation. Acts on the value (mode).
4897
4898 selection:
4899 The Symbol instance of the currently selected symbol. None if the Choice
4900 is not in y mode or has no selected symbol (due to unsatisfied
4901 dependencies on choice symbols).
4902
4903 WARNING: Do not assign directly to this. It will break things. Call
4904 sym.set_value(2) on the choice symbol you want to select instead.
4905
4906 user_value:
4907 The value (mode) selected by the user through Choice.set_value(). Either
4908 0, 1, or 2, or None if the user hasn't selected a mode. See
4909 Symbol.user_value.
4910
4911 WARNING: Do not assign directly to this. It will break things. Use
4912 Choice.set_value() instead.
4913
4914 user_selection:
4915 The symbol selected by the user (by setting it to y). Ignored if the
4916 choice is not in y mode, but still remembered so that the choice "snaps
4917 back" to the user selection if the mode is changed back to y. This might
4918 differ from 'selection' due to unsatisfied dependencies.
4919
4920 WARNING: Do not assign directly to this. It will break things. Call
4921 sym.set_value(2) on the choice symbol to be selected instead.
4922
4923 syms:
4924 List of symbols contained in the choice.
4925
4926 Obscure gotcha: If a symbol depends on the previous symbol within a
4927 choice so that an implicit menu is created, it won't be a choice symbol,
4928 and won't be included in 'syms'.
4929
4930 nodes:
4931 A list of MenuNodes for this choice. In practice, the list will probably
4932 always contain a single MenuNode, but it is possible to give a choice a
4933 name and define it in multiple locations.
4934
4935 defaults:
4936 List of (symbol, cond) tuples for the choice's 'defaults' properties. For
4937 example, 'default A if B && C' is represented as (A, (AND, B, C)). If
[cf2f109]4938 there is no condition, 'cond' is self.kconfig.y.
[f596dde]4939
4940 Note that 'depends on' and parent dependencies are propagated to
4941 'default' conditions.
4942
4943 direct_dep:
4944 See Symbol.direct_dep.
4945
4946 referenced:
4947 A set() with all symbols referenced in the properties and property
4948 conditions of the choice.
4949
[cf2f109]4950 Also includes dependencies from surrounding menus and if's, because those
4951 get propagated to the choice (see the 'Intro to symbol values' section in
4952 the module docstring).
[f596dde]4953
4954 is_optional:
4955 True if the choice has the 'optional' flag set on it and can be in
4956 n mode.
4957
4958 kconfig:
4959 The Kconfig instance this choice is from.
4960 """
4961 __slots__ = (
4962 "_cached_assignable",
4963 "_cached_selection",
4964 "_cached_vis",
4965 "_dependents",
4966 "_visited",
4967 "_was_set",
4968 "defaults",
4969 "direct_dep",
4970 "is_constant",
4971 "is_optional",
4972 "kconfig",
4973 "name",
4974 "nodes",
4975 "orig_type",
4976 "syms",
4977 "user_selection",
4978 "user_value",
4979 )
4980
4981 #
4982 # Public interface
4983 #
4984
4985 @property
4986 def type(self):
4987 """
4988 Returns the type of the choice. See Symbol.type.
4989 """
4990 if self.orig_type is TRISTATE and not self.kconfig.modules.tri_value:
4991 return BOOL
4992
4993 return self.orig_type
4994
4995 @property
4996 def str_value(self):
4997 """
4998 See the class documentation.
4999 """
5000 return TRI_TO_STR[self.tri_value]
5001
5002 @property
5003 def tri_value(self):
5004 """
5005 See the class documentation.
5006 """
5007 # This emulates a reverse dependency of 'm && visibility' for
5008 # non-optional choices, which is how the C implementation does it
5009
5010 val = 0 if self.is_optional else 1
5011
5012 if self.user_value is not None:
5013 val = max(val, self.user_value)
5014
5015 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
5016 # function call (property magic)
5017 val = min(val, self.visibility)
5018
5019 # Promote m to y for boolean choices
5020 return 2 if val == 1 and self.type is BOOL else val
5021
5022 @property
5023 def assignable(self):
5024 """
5025 See the class documentation.
5026 """
5027 if self._cached_assignable is None:
5028 self._cached_assignable = self._assignable()
5029
5030 return self._cached_assignable
5031
5032 @property
5033 def visibility(self):
5034 """
5035 See the class documentation.
5036 """
5037 if self._cached_vis is None:
5038 self._cached_vis = _visibility(self)
5039
5040 return self._cached_vis
5041
5042 @property
5043 def selection(self):
5044 """
5045 See the class documentation.
5046 """
5047 if self._cached_selection is _NO_CACHED_SELECTION:
5048 self._cached_selection = self._selection()
5049
5050 return self._cached_selection
5051
5052 def set_value(self, value):
5053 """
5054 Sets the user value (mode) of the choice. Like for Symbol.set_value(),
5055 the visibility might truncate the value. Choices without the 'optional'
5056 attribute (is_optional) can never be in n mode, but 0/"n" is still
5057 accepted since it's not a malformed value (though it will have no
5058 effect).
5059
5060 Returns True if the value is valid for the type of the choice, and
5061 False otherwise. This only looks at the form of the value. Check the
5062 Choice.assignable attribute to see what values are currently in range
5063 and would actually be reflected in the mode of the choice.
5064 """
5065 if value == self.user_value:
5066 # We know the value must be valid if it was successfully set
5067 # previously
5068 self._was_set = True
5069 return True
5070
5071 if not ((self.orig_type is BOOL and value in (2, 0, "y", "n") ) or
5072 (self.orig_type is TRISTATE and value in (2, 1, 0, "y", "m", "n"))):
5073
5074 # Display tristate values as n, m, y in the warning
5075 self.kconfig._warn(
5076 "the value {} is invalid for {}, which has type {} -- "
5077 "assignment ignored"
5078 .format(TRI_TO_STR[value] if value in (0, 1, 2) else
5079 "'{}'".format(value),
5080 _name_and_loc(self),
5081 TYPE_TO_STR[self.orig_type]))
5082
5083 return False
5084
5085 if value in ("y", "m", "n"):
5086 value = STR_TO_TRI[value]
5087
5088 self.user_value = value
5089 self._was_set = True
5090 self._rec_invalidate()
5091
5092 return True
5093
5094 def unset_value(self):
5095 """
5096 Resets the user value (mode) and user selection of the Choice, as if
5097 the user had never touched the mode or any of the choice symbols.
5098 """
5099 if self.user_value is not None or self.user_selection:
5100 self.user_value = self.user_selection = None
5101 self._rec_invalidate()
5102
5103 @property
5104 def referenced(self):
5105 """
5106 See the class documentation.
5107 """
5108 return {item for node in self.nodes for item in node.referenced}
5109
5110 def __repr__(self):
5111 """
5112 Returns a string with information about the choice when it is evaluated
5113 on e.g. the interactive Python prompt.
5114 """
5115 fields = ["choice " + self.name if self.name else "choice",
5116 TYPE_TO_STR[self.type]]
5117
5118 for node in self.nodes:
5119 if node.prompt:
5120 fields.append('"{}"'.format(node.prompt[0]))
5121
5122 fields.append("mode " + self.str_value)
5123
5124 if self.user_value is not None:
5125 fields.append('user mode {}'.format(TRI_TO_STR[self.user_value]))
5126
5127 if self.selection:
5128 fields.append("{} selected".format(self.selection.name))
5129
5130 if self.user_selection:
5131 user_sel_str = "{} selected by user" \
5132 .format(self.user_selection.name)
5133
5134 if self.selection is not self.user_selection:
5135 user_sel_str += " (overridden)"
5136
5137 fields.append(user_sel_str)
5138
5139 fields.append("visibility " + TRI_TO_STR[self.visibility])
5140
5141 if self.is_optional:
5142 fields.append("optional")
5143
5144 for node in self.nodes:
5145 fields.append("{}:{}".format(node.filename, node.linenr))
5146
5147 return "<{}>".format(", ".join(fields))
5148
5149 def __str__(self):
5150 """
[cf2f109]5151 Returns a string representation of the choice when it is printed.
5152 Matches the Kconfig format (though without the contained choice
5153 symbols), with any parent dependencies propagated to the 'depends on'
5154 condition.
[f596dde]5155
5156 The returned string does not end in a newline.
5157
5158 See Symbol.__str__() as well.
5159 """
5160 return self.custom_str(standard_sc_expr_str)
5161
5162 def custom_str(self, sc_expr_str_fn):
5163 """
5164 Works like Choice.__str__(), but allows a custom format to be used for
5165 all symbol/choice references. See expr_str().
5166 """
5167 return "\n\n".join(node.custom_str(sc_expr_str_fn)
5168 for node in self.nodes)
5169
5170 #
5171 # Private methods
5172 #
5173
5174 def __init__(self):
5175 """
5176 Choice constructor -- not intended to be called directly by Kconfiglib
5177 clients.
5178 """
5179 # These attributes are always set on the instance from outside and
5180 # don't need defaults:
5181 # direct_dep
5182 # kconfig
5183
5184 self.orig_type = UNKNOWN
5185 self.syms = []
5186 self.defaults = []
5187
5188 self.nodes = []
5189
5190 self.name = \
5191 self.user_value = self.user_selection = \
5192 self._cached_vis = self._cached_assignable = None
5193
5194 self._cached_selection = _NO_CACHED_SELECTION
5195
5196 # is_constant is checked by _make_depend_on(). Just set it to avoid
5197 # having to special-case choices.
5198 self.is_constant = self.is_optional = False
5199
5200 # See Kconfig._build_dep()
5201 self._dependents = set()
5202
5203 # Used during dependency loop detection
5204 self._visited = 0
5205
5206 def _assignable(self):
5207 # Worker function for the 'assignable' attribute
5208
5209 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
5210 # function call (property magic)
5211 vis = self.visibility
5212
5213 if not vis:
5214 return ()
5215
5216 if vis == 2:
5217 if not self.is_optional:
5218 return (2,) if self.type is BOOL else (1, 2)
5219 return (0, 2) if self.type is BOOL else (0, 1, 2)
5220
5221 # vis == 1
5222
5223 return (0, 1) if self.is_optional else (1,)
5224
5225 def _selection(self):
5226 # Worker function for the 'selection' attribute
5227
5228 # Warning: See Symbol._rec_invalidate(), and note that this is a hidden
5229 # function call (property magic)
5230 if self.tri_value != 2:
5231 # Not in y mode, so no selection
5232 return None
5233
5234 # Use the user selection if it's visible
5235 if self.user_selection and self.user_selection.visibility:
5236 return self.user_selection
5237
5238 # Otherwise, check if we have a default
5239 return self._get_selection_from_defaults()
5240
5241 def _get_selection_from_defaults(self):
5242 # Check if we have a default
5243 for sym, cond in self.defaults:
5244 # The default symbol must be visible too
5245 if expr_value(cond) and sym.visibility:
5246 return sym
5247
5248 # Otherwise, pick the first visible symbol, if any
5249 for sym in self.syms:
5250 if sym.visibility:
5251 return sym
5252
5253 # Couldn't find a selection
5254 return None
5255
5256 def _invalidate(self):
5257 self._cached_vis = self._cached_assignable = None
5258 self._cached_selection = _NO_CACHED_SELECTION
5259
5260 def _rec_invalidate(self):
5261 # See Symbol._rec_invalidate()
5262
5263 self._invalidate()
5264
5265 for item in self._dependents:
5266 if item._cached_vis is not None:
5267 item._rec_invalidate()
5268
5269
5270class MenuNode(object):
5271 """
5272 Represents a menu node in the configuration. This corresponds to an entry
5273 in e.g. the 'make menuconfig' interface, though non-visible choices, menus,
5274 and comments also get menu nodes. If a symbol or choice is defined in
5275 multiple locations, it gets one menu node for each location.
5276
5277 The top-level menu node, corresponding to the implicit top-level menu, is
5278 available in Kconfig.top_node.
5279
5280 The menu nodes for a Symbol or Choice can be found in the
5281 Symbol/Choice.nodes attribute. Menus and comments are represented as plain
5282 menu nodes, with their text stored in the prompt attribute (prompt[0]).
5283 This mirrors the C implementation.
5284
5285 The following attributes are available on MenuNode instances. They should
5286 be viewed as read-only.
5287
5288 item:
5289 Either a Symbol, a Choice, or one of the constants MENU and COMMENT.
5290 Menus and comments are represented as plain menu nodes. Ifs are collapsed
5291 (matching the C implementation) and do not appear in the final menu tree.
5292
5293 next:
5294 The following menu node. None if there is no following node.
5295
5296 list:
5297 The first child menu node. None if there are no children.
5298
5299 Choices and menus naturally have children, but Symbols can also have
5300 children because of menus created automatically from dependencies (see
5301 kconfig-language.txt).
5302
5303 parent:
5304 The parent menu node. None if there is no parent.
5305
5306 prompt:
5307 A (string, cond) tuple with the prompt for the menu node and its
5308 conditional expression (which is self.kconfig.y if there is no
5309 condition). None if there is no prompt.
5310
5311 For symbols and choices, the prompt is stored in the MenuNode rather than
5312 the Symbol or Choice instance. For menus and comments, the prompt holds
5313 the text.
5314
5315 defaults:
5316 The 'default' properties for this particular menu node. See
5317 symbol.defaults.
5318
5319 When evaluating defaults, you should use Symbol/Choice.defaults instead,
5320 as it include properties from all menu nodes (a symbol/choice can have
5321 multiple definition locations/menu nodes). MenuNode.defaults is meant for
5322 documentation generation.
5323
5324 selects:
5325 Like MenuNode.defaults, for selects.
5326
5327 implies:
5328 Like MenuNode.defaults, for implies.
5329
5330 ranges:
5331 Like MenuNode.defaults, for ranges.
5332
[cf2f109]5333 orig_prompt:
5334 orig_defaults:
5335 orig_selects:
5336 orig_implies:
5337 orig_ranges:
5338 These work the like the corresponding attributes without orig_*, but omit
5339 any dependencies propagated from 'depends on' and surrounding 'if's (the
5340 direct dependencies, stored in MenuNode.dep).
5341
5342 One use for this is generating less cluttered documentation, by only
5343 showing the direct dependencies in one place.
5344
[f596dde]5345 help:
5346 The help text for the menu node for Symbols and Choices. None if there is
5347 no help text. Always stored in the node rather than the Symbol or Choice.
5348 It is possible to have a separate help text at each location if a symbol
5349 is defined in multiple locations.
5350
5351 Trailing whitespace (including a final newline) is stripped from the help
5352 text. This was not the case before Kconfiglib 10.21.0, where the format
5353 was undocumented.
5354
5355 dep:
[cf2f109]5356 The direct ('depends on') dependencies for the menu node, or
5357 self.kconfig.y if there are no direct dependencies.
5358
5359 This attribute includes any dependencies from surrounding menus and if's.
5360 Those get propagated to the direct dependencies, and the resulting direct
5361 dependencies in turn get propagated to the conditions of all properties.
[f596dde]5362
5363 If a symbol or choice is defined in multiple locations, only the
5364 properties defined at a particular location get the corresponding
5365 MenuNode.dep dependencies propagated to them.
5366
5367 visibility:
5368 The 'visible if' dependencies for the menu node (which must represent a
5369 menu), or self.kconfig.y if there are no 'visible if' dependencies.
5370 'visible if' dependencies are recursively propagated to the prompts of
5371 symbols and choices within the menu.
5372
5373 referenced:
5374 A set() with all symbols and choices referenced in the properties and
5375 property conditions of the menu node.
5376
5377 Also includes dependencies inherited from surrounding menus and if's.
5378 Choices appear in the dependencies of choice symbols.
5379
5380 is_menuconfig:
5381 Set to True if the children of the menu node should be displayed in a
5382 separate menu. This is the case for the following items:
5383
5384 - Menus (node.item == MENU)
5385
5386 - Choices
5387
5388 - Symbols defined with the 'menuconfig' keyword. The children come from
5389 implicitly created submenus, and should be displayed in a separate
5390 menu rather than being indented.
5391
5392 'is_menuconfig' is just a hint on how to display the menu node. It's
5393 ignored internally by Kconfiglib, except when printing symbols.
5394
5395 filename/linenr:
5396 The location where the menu node appears. The filename is relative to
5397 $srctree (or to the current directory if $srctree isn't set), except
5398 absolute paths passed to 'source' and Kconfig.__init__() are preserved.
5399
5400 include_path:
5401 A tuple of (filename, linenr) tuples, giving the locations of the
5402 'source' statements via which the Kconfig file containing this menu node
5403 was included. The first element is the location of the 'source' statement
5404 in the top-level Kconfig file passed to Kconfig.__init__(), etc.
5405
5406 Note that the Kconfig file of the menu node itself isn't included. Check
5407 'filename' and 'linenr' for that.
5408
5409 kconfig:
5410 The Kconfig instance the menu node is from.
5411 """
5412 __slots__ = (
5413 "dep",
5414 "filename",
5415 "help",
5416 "include_path",
5417 "is_menuconfig",
5418 "item",
5419 "kconfig",
5420 "linenr",
5421 "list",
5422 "next",
5423 "parent",
5424 "prompt",
5425 "visibility",
5426
5427 # Properties
5428 "defaults",
5429 "selects",
5430 "implies",
5431 "ranges",
5432 )
5433
5434 def __init__(self):
5435 # Properties defined on this particular menu node. A local 'depends on'
5436 # only applies to these, in case a symbol is defined in multiple
5437 # locations.
5438 self.defaults = []
5439 self.selects = []
5440 self.implies = []
5441 self.ranges = []
5442
[cf2f109]5443 @property
5444 def orig_prompt(self):
5445 """
5446 See the class documentation.
5447 """
5448 if not self.prompt:
5449 return None
5450 return (self.prompt[0], self._strip_dep(self.prompt[1]))
5451
5452 @property
5453 def orig_defaults(self):
5454 """
5455 See the class documentation.
5456 """
5457 return [(default, self._strip_dep(cond))
5458 for default, cond in self.defaults]
5459
5460 @property
5461 def orig_selects(self):
5462 """
5463 See the class documentation.
5464 """
5465 return [(select, self._strip_dep(cond))
5466 for select, cond in self.selects]
5467
5468 @property
5469 def orig_implies(self):
5470 """
5471 See the class documentation.
5472 """
5473 return [(imply, self._strip_dep(cond))
5474 for imply, cond in self.implies]
5475
5476 @property
5477 def orig_ranges(self):
5478 """
5479 See the class documentation.
5480 """
5481 return [(low, high, self._strip_dep(cond))
5482 for low, high, cond in self.ranges]
5483
[f596dde]5484 @property
5485 def referenced(self):
5486 """
5487 See the class documentation.
5488 """
5489 # self.dep is included to catch dependencies from a lone 'depends on'
5490 # when there are no properties to propagate it to
5491 res = expr_items(self.dep)
5492
5493 if self.prompt:
5494 res |= expr_items(self.prompt[1])
5495
5496 if self.item is MENU:
5497 res |= expr_items(self.visibility)
5498
5499 for value, cond in self.defaults:
5500 res |= expr_items(value)
5501 res |= expr_items(cond)
5502
5503 for value, cond in self.selects:
5504 res.add(value)
5505 res |= expr_items(cond)
5506
5507 for value, cond in self.implies:
5508 res.add(value)
5509 res |= expr_items(cond)
5510
5511 for low, high, cond in self.ranges:
5512 res.add(low)
5513 res.add(high)
5514 res |= expr_items(cond)
5515
5516 return res
5517
5518 def __repr__(self):
5519 """
5520 Returns a string with information about the menu node when it is
5521 evaluated on e.g. the interactive Python prompt.
5522 """
5523 fields = []
5524
5525 if self.item.__class__ is Symbol:
5526 fields.append("menu node for symbol " + self.item.name)
5527
5528 elif self.item.__class__ is Choice:
5529 s = "menu node for choice"
5530 if self.item.name is not None:
5531 s += " " + self.item.name
5532 fields.append(s)
5533
5534 elif self.item is MENU:
5535 fields.append("menu node for menu")
5536
5537 else: # self.item is COMMENT
5538 fields.append("menu node for comment")
5539
5540 if self.prompt:
5541 fields.append('prompt "{}" (visibility {})'
5542 .format(self.prompt[0],
5543 TRI_TO_STR[expr_value(self.prompt[1])]))
5544
5545 if self.item.__class__ is Symbol and self.is_menuconfig:
5546 fields.append("is menuconfig")
5547
5548 fields.append("deps " + TRI_TO_STR[expr_value(self.dep)])
5549
5550 if self.item is MENU:
5551 fields.append("'visible if' deps " +
5552 TRI_TO_STR[expr_value(self.visibility)])
5553
5554 if self.item.__class__ in _SYMBOL_CHOICE and self.help is not None:
5555 fields.append("has help")
5556
5557 if self.list:
5558 fields.append("has child")
5559
5560 if self.next:
5561 fields.append("has next")
5562
5563 fields.append("{}:{}".format(self.filename, self.linenr))
5564
5565 return "<{}>".format(", ".join(fields))
5566
5567 def __str__(self):
5568 """
[cf2f109]5569 Returns a string representation of the menu node. Matches the Kconfig
5570 format, with any parent dependencies propagated to the 'depends on'
5571 condition.
[f596dde]5572
5573 The output could (almost) be fed back into a Kconfig parser to redefine
5574 the object associated with the menu node. See the module documentation
5575 for a gotcha related to choice symbols.
5576
5577 For symbols and choices with multiple menu nodes (multiple definition
5578 locations), properties that aren't associated with a particular menu
5579 node are shown on all menu nodes ('option env=...', 'optional' for
5580 choices, etc.).
5581
5582 The returned string does not end in a newline.
5583 """
5584 return self.custom_str(standard_sc_expr_str)
5585
5586 def custom_str(self, sc_expr_str_fn):
5587 """
5588 Works like MenuNode.__str__(), but allows a custom format to be used
5589 for all symbol/choice references. See expr_str().
5590 """
5591 return self._menu_comment_node_str(sc_expr_str_fn) \
5592 if self.item in _MENU_COMMENT else \
5593 self._sym_choice_node_str(sc_expr_str_fn)
5594
5595 def _menu_comment_node_str(self, sc_expr_str_fn):
5596 s = '{} "{}"'.format("menu" if self.item is MENU else "comment",
5597 self.prompt[0])
5598
5599 if self.dep is not self.kconfig.y:
5600 s += "\n\tdepends on {}".format(expr_str(self.dep, sc_expr_str_fn))
5601
5602 if self.item is MENU and self.visibility is not self.kconfig.y:
5603 s += "\n\tvisible if {}".format(expr_str(self.visibility,
5604 sc_expr_str_fn))
5605
5606 return s
5607
5608 def _sym_choice_node_str(self, sc_expr_str_fn):
5609 def indent_add(s):
5610 lines.append("\t" + s)
5611
5612 def indent_add_cond(s, cond):
5613 if cond is not self.kconfig.y:
5614 s += " if " + expr_str(cond, sc_expr_str_fn)
5615 indent_add(s)
5616
5617 sc = self.item
5618
5619 if sc.__class__ is Symbol:
5620 lines = [("menuconfig " if self.is_menuconfig else "config ")
5621 + sc.name]
5622 else:
5623 lines = ["choice " + sc.name if sc.name else "choice"]
5624
[cf2f109]5625 if sc.orig_type and not self.prompt: # sc.orig_type != UNKNOWN
5626 # If there's a prompt, we'll use the '<type> "prompt"' shorthand
5627 # instead
[f596dde]5628 indent_add(TYPE_TO_STR[sc.orig_type])
5629
5630 if self.prompt:
[cf2f109]5631 if sc.orig_type:
5632 prefix = TYPE_TO_STR[sc.orig_type]
5633 else:
5634 # Symbol defined without a type (which generates a warning)
5635 prefix = "prompt"
5636
5637 indent_add_cond(prefix + ' "{}"'.format(escape(self.prompt[0])),
5638 self.orig_prompt[1])
[f596dde]5639
5640 if sc.__class__ is Symbol:
5641 if sc.is_allnoconfig_y:
5642 indent_add("option allnoconfig_y")
5643
5644 if sc is sc.kconfig.defconfig_list:
5645 indent_add("option defconfig_list")
5646
5647 if sc.env_var is not None:
5648 indent_add('option env="{}"'.format(sc.env_var))
5649
5650 if sc is sc.kconfig.modules:
5651 indent_add("option modules")
5652
[cf2f109]5653 for low, high, cond in self.orig_ranges:
[f596dde]5654 indent_add_cond(
5655 "range {} {}".format(sc_expr_str_fn(low),
5656 sc_expr_str_fn(high)),
5657 cond)
5658
[cf2f109]5659 for default, cond in self.orig_defaults:
[f596dde]5660 indent_add_cond("default " + expr_str(default, sc_expr_str_fn),
5661 cond)
5662
5663 if sc.__class__ is Choice and sc.is_optional:
5664 indent_add("optional")
5665
5666 if sc.__class__ is Symbol:
[cf2f109]5667 for select, cond in self.orig_selects:
[f596dde]5668 indent_add_cond("select " + sc_expr_str_fn(select), cond)
5669
[cf2f109]5670 for imply, cond in self.orig_implies:
[f596dde]5671 indent_add_cond("imply " + sc_expr_str_fn(imply), cond)
5672
5673 if self.dep is not sc.kconfig.y:
5674 indent_add("depends on " + expr_str(self.dep, sc_expr_str_fn))
5675
5676 if self.help is not None:
5677 indent_add("help")
5678 for line in self.help.splitlines():
5679 indent_add(" " + line)
5680
5681 return "\n".join(lines)
5682
[cf2f109]5683 def _strip_dep(self, expr):
5684 # Helper function for removing MenuNode.dep from 'expr'. Uses two
5685 # pieces of internal knowledge: (1) Expressions are reused rather than
5686 # copied, and (2) the direct dependencies always appear at the end.
5687
5688 # ... if dep -> ... if y
5689 if self.dep is expr:
5690 return self.kconfig.y
5691
5692 # (AND, X, dep) -> X
5693 if expr.__class__ is tuple and expr[0] is AND and expr[2] is self.dep:
5694 return expr[1]
5695
5696 return expr
5697
[f596dde]5698
5699class Variable(object):
5700 """
5701 Represents a preprocessor variable/function.
5702
5703 The following attributes are available:
5704
5705 name:
5706 The name of the variable.
5707
5708 value:
5709 The unexpanded value of the variable.
5710
5711 expanded_value:
5712 The expanded value of the variable. For simple variables (those defined
5713 with :=), this will equal 'value'. Accessing this property will raise a
5714 KconfigError if the expansion seems to be stuck in a loop.
5715
[cf2f109]5716 Accessing this field is the same as calling expanded_value_w_args() with
5717 no arguments. I hadn't considered function arguments when adding it. It
5718 is retained for backwards compatibility though.
[f596dde]5719
5720 is_recursive:
5721 True if the variable is recursive (defined with =).
5722 """
5723 __slots__ = (
5724 "_n_expansions",
5725 "is_recursive",
5726 "kconfig",
5727 "name",
5728 "value",
5729 )
5730
5731 @property
5732 def expanded_value(self):
5733 """
5734 See the class documentation.
5735 """
5736 return self.expanded_value_w_args()
5737
5738 def expanded_value_w_args(self, *args):
5739 """
5740 Returns the expanded value of the variable/function. Any arguments
5741 passed will be substituted for $(1), $(2), etc.
5742
5743 Raises a KconfigError if the expansion seems to be stuck in a loop.
5744 """
5745 return self.kconfig._fn_val((self.name,) + args)
5746
5747 def __repr__(self):
5748 return "<variable {}, {}, value '{}'>" \
5749 .format(self.name,
5750 "recursive" if self.is_recursive else "immediate",
5751 self.value)
5752
5753
5754class KconfigError(Exception):
[cf2f109]5755 """
5756 Exception raised for Kconfig-related errors.
5757
5758 KconfigError and KconfigSyntaxError are the same class. The
5759 KconfigSyntaxError alias is only maintained for backwards compatibility.
5760 """
[f596dde]5761
5762KconfigSyntaxError = KconfigError # Backwards compatibility
5763
5764
5765class InternalError(Exception):
5766 "Never raised. Kept around for backwards compatibility."
5767
5768
5769# Workaround:
5770#
5771# If 'errno' and 'strerror' are set on IOError, then __str__() always returns
5772# "[Errno <errno>] <strerror>", ignoring any custom message passed to the
5773# constructor. By defining our own subclass, we can use a custom message while
5774# also providing 'errno', 'strerror', and 'filename' to scripts.
5775class _KconfigIOError(IOError):
5776 def __init__(self, ioerror, msg):
5777 self.msg = msg
5778 super(_KconfigIOError, self).__init__(
5779 ioerror.errno, ioerror.strerror, ioerror.filename)
5780
5781 def __str__(self):
5782 return self.msg
5783
5784
5785#
5786# Public functions
5787#
5788
5789
5790def expr_value(expr):
5791 """
5792 Evaluates the expression 'expr' to a tristate value. Returns 0 (n), 1 (m),
5793 or 2 (y).
5794
5795 'expr' must be an already-parsed expression from a Symbol, Choice, or
5796 MenuNode property. To evaluate an expression represented as a string, use
5797 Kconfig.eval_string().
5798
5799 Passing subexpressions of expressions to this function works as expected.
5800 """
5801 if expr.__class__ is not tuple:
5802 return expr.tri_value
5803
5804 if expr[0] is AND:
5805 v1 = expr_value(expr[1])
5806 # Short-circuit the n case as an optimization (~5% faster
5807 # allnoconfig.py and allyesconfig.py, as of writing)
5808 return 0 if not v1 else min(v1, expr_value(expr[2]))
5809
5810 if expr[0] is OR:
5811 v1 = expr_value(expr[1])
5812 # Short-circuit the y case as an optimization
5813 return 2 if v1 == 2 else max(v1, expr_value(expr[2]))
5814
5815 if expr[0] is NOT:
5816 return 2 - expr_value(expr[1])
5817
5818 # Relation
5819 #
5820 # Implements <, <=, >, >= comparisons as well. These were added to
5821 # kconfig in 31847b67 (kconfig: allow use of relations other than
5822 # (in)equality).
5823
5824 rel, v1, v2 = expr
5825
5826 # If both operands are strings...
5827 if v1.orig_type is STRING and v2.orig_type is STRING:
5828 # ...then compare them lexicographically
5829 comp = _strcmp(v1.str_value, v2.str_value)
5830 else:
5831 # Otherwise, try to compare them as numbers
5832 try:
5833 comp = _sym_to_num(v1) - _sym_to_num(v2)
5834 except ValueError:
5835 # Fall back on a lexicographic comparison if the operands don't
5836 # parse as numbers
5837 comp = _strcmp(v1.str_value, v2.str_value)
5838
5839 if rel is EQUAL: return 2*(comp == 0)
5840 if rel is UNEQUAL: return 2*(comp != 0)
5841 if rel is LESS: return 2*(comp < 0)
5842 if rel is LESS_EQUAL: return 2*(comp <= 0)
5843 if rel is GREATER: return 2*(comp > 0)
5844 return 2*(comp >= 0) # rel is GREATER_EQUAL
5845
5846
5847def standard_sc_expr_str(sc):
5848 """
5849 Standard symbol/choice printing function. Uses plain Kconfig syntax, and
5850 displays choices as <choice> (or <choice NAME>, for named choices).
5851
5852 See expr_str().
5853 """
5854 if sc.__class__ is Symbol:
[cf2f109]5855 if sc.is_constant and sc.name not in ("n", "m", "y"):
5856 return '"{}"'.format(escape(sc.name))
5857 return sc.name
[f596dde]5858
5859 # Choice
5860 return "<choice {}>".format(sc.name) if sc.name else "<choice>"
5861
5862
5863def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
5864 """
5865 Returns the string representation of the expression 'expr', as in a Kconfig
5866 file.
5867
5868 Passing subexpressions of expressions to this function works as expected.
5869
5870 sc_expr_str_fn (default: standard_sc_expr_str):
5871 This function is called for every symbol/choice (hence "sc") appearing in
5872 the expression, with the symbol/choice as the argument. It is expected to
5873 return a string to be used for the symbol/choice.
5874
5875 This can be used e.g. to turn symbols/choices into links when generating
5876 documentation, or for printing the value of each symbol/choice after it.
5877
5878 Note that quoted values are represented as constants symbols
5879 (Symbol.is_constant == True).
5880 """
5881 if expr.__class__ is not tuple:
5882 return sc_expr_str_fn(expr)
5883
5884 if expr[0] is AND:
5885 return "{} && {}".format(_parenthesize(expr[1], OR, sc_expr_str_fn),
5886 _parenthesize(expr[2], OR, sc_expr_str_fn))
5887
5888 if expr[0] is OR:
5889 # This turns A && B || C && D into "(A && B) || (C && D)", which is
5890 # redundant, but more readable
5891 return "{} || {}".format(_parenthesize(expr[1], AND, sc_expr_str_fn),
5892 _parenthesize(expr[2], AND, sc_expr_str_fn))
5893
5894 if expr[0] is NOT:
5895 if expr[1].__class__ is tuple:
5896 return "!({})".format(expr_str(expr[1], sc_expr_str_fn))
5897 return "!" + sc_expr_str_fn(expr[1]) # Symbol
5898
5899 # Relation
5900 #
5901 # Relation operands are always symbols (quoted strings are constant
5902 # symbols)
5903 return "{} {} {}".format(sc_expr_str_fn(expr[1]), _REL_TO_STR[expr[0]],
5904 sc_expr_str_fn(expr[2]))
5905
5906
5907def expr_items(expr):
5908 """
5909 Returns a set() of all items (symbols and choices) that appear in the
5910 expression 'expr'.
5911 """
5912
5913 res = set()
5914
5915 def rec(subexpr):
5916 if subexpr.__class__ is tuple:
5917 # AND, OR, NOT, or relation
5918
5919 rec(subexpr[1])
5920
5921 # NOTs only have a single operand
5922 if subexpr[0] is not NOT:
5923 rec(subexpr[2])
5924
5925 else:
5926 # Symbol or choice
5927 res.add(subexpr)
5928
5929 rec(expr)
5930 return res
5931
5932
5933def split_expr(expr, op):
5934 """
5935 Returns a list containing the top-level AND or OR operands in the
5936 expression 'expr', in the same (left-to-right) order as they appear in
5937 the expression.
5938
5939 This can be handy e.g. for splitting (weak) reverse dependencies
5940 from 'select' and 'imply' into individual selects/implies.
5941
5942 op:
5943 Either AND to get AND operands, or OR to get OR operands.
5944
5945 (Having this as an operand might be more future-safe than having two
5946 hardcoded functions.)
5947
5948
5949 Pseudo-code examples:
5950
5951 split_expr( A , OR ) -> [A]
5952 split_expr( A && B , OR ) -> [A && B]
5953 split_expr( A || B , OR ) -> [A, B]
5954 split_expr( A || B , AND ) -> [A || B]
5955 split_expr( A || B || (C && D) , OR ) -> [A, B, C && D]
5956
5957 # Second || is not at the top level
5958 split_expr( A || (B && (C || D)) , OR ) -> [A, B && (C || D)]
5959
5960 # Parentheses don't matter as long as we stay at the top level (don't
5961 # encounter any non-'op' nodes)
5962 split_expr( (A || B) || C , OR ) -> [A, B, C]
5963 split_expr( A || (B || C) , OR ) -> [A, B, C]
5964 """
5965 res = []
5966
5967 def rec(subexpr):
5968 if subexpr.__class__ is tuple and subexpr[0] is op:
5969 rec(subexpr[1])
5970 rec(subexpr[2])
5971 else:
5972 res.append(subexpr)
5973
5974 rec(expr)
5975 return res
5976
5977
5978def escape(s):
5979 r"""
5980 Escapes the string 's' in the same fashion as is done for display in
5981 Kconfig format and when writing strings to a .config file. " and \ are
5982 replaced by \" and \\, respectively.
5983 """
5984 # \ must be escaped before " to avoid double escaping
5985 return s.replace("\\", r"\\").replace('"', r'\"')
5986
5987
5988def unescape(s):
5989 r"""
5990 Unescapes the string 's'. \ followed by any character is replaced with just
5991 that character. Used internally when reading .config files.
5992 """
5993 return _unescape_sub(r"\1", s)
5994
5995# unescape() helper
5996_unescape_sub = re.compile(r"\\(.)").sub
5997
5998
5999def standard_kconfig():
6000 """
6001 Helper for tools. Loads the top-level Kconfig specified as the first
6002 command-line argument, or "Kconfig" if there are no command-line arguments.
6003 Returns the Kconfig instance.
6004
6005 Exits with sys.exit() (which raises a SystemExit exception) and prints a
6006 usage note to stderr if more than one command-line argument is passed.
6007 """
6008 if len(sys.argv) > 2:
6009 sys.exit("usage: {} [Kconfig]".format(sys.argv[0]))
6010
6011 # Only show backtraces for unexpected exceptions
6012 try:
6013 return Kconfig("Kconfig" if len(sys.argv) < 2 else sys.argv[1])
6014 except (IOError, KconfigError) as e:
6015 # Some long exception messages have extra newlines for better
6016 # formatting when reported as an unhandled exception. Strip them here.
6017 sys.exit(str(e).strip())
6018
6019
6020def standard_config_filename():
6021 """
6022 Helper for tools. Returns the value of KCONFIG_CONFIG (which specifies the
6023 .config file to load/save) if it is set, and ".config" otherwise.
6024
[cf2f109]6025 Calling load_config() with filename=None might give the behavior you want,
6026 without having to use this function.
[f596dde]6027 """
6028 return os.environ.get("KCONFIG_CONFIG", ".config")
6029
6030
6031def load_allconfig(kconf, filename):
6032 """
6033 Helper for all*config. Loads (merges) the configuration file specified by
6034 KCONFIG_ALLCONFIG, if any. See Documentation/kbuild/kconfig.txt in the
6035 Linux kernel.
6036
6037 Disables warnings for duplicated assignments within configuration files for
[cf2f109]6038 the duration of the call (kconf.warn_assign_override/warn_assign_redun = False),
6039 and restores the previous warning settings at the end. The
[f596dde]6040 KCONFIG_ALLCONFIG configuration file is expected to override symbols.
6041
6042 Exits with sys.exit() (which raises a SystemExit exception) and prints an
6043 error to stderr if KCONFIG_ALLCONFIG is set but the configuration file
6044 can't be opened.
6045
6046 kconf:
6047 Kconfig instance to load the configuration in.
6048
6049 filename:
6050 Command-specific configuration filename - "allyes.config",
6051 "allno.config", etc.
6052 """
[cf2f109]6053 allconfig = os.environ.get("KCONFIG_ALLCONFIG")
6054 if allconfig is None:
6055 return
6056
[f596dde]6057 def std_msg(e):
6058 # "Upcasts" a _KconfigIOError to an IOError, removing the custom
6059 # __str__() message. The standard message is better here.
6060 return IOError(e.errno, e.strerror, e.filename)
6061
[cf2f109]6062 old_warn_assign_override = kconf.warn_assign_override
6063 old_warn_assign_redun = kconf.warn_assign_redun
6064 kconf.warn_assign_override = kconf.warn_assign_redun = False
[f596dde]6065
[cf2f109]6066 if allconfig in ("", "1"):
6067 try:
6068 print(kconf.load_config(filename, False))
6069 except IOError as e1:
[f596dde]6070 try:
[cf2f109]6071 print(kconf.load_config("all.config", False))
6072 except IOError as e2:
6073 sys.exit("error: KCONFIG_ALLCONFIG is set, but neither {} "
6074 "nor all.config could be opened: {}, {}"
6075 .format(filename, std_msg(e1), std_msg(e2)))
6076 else:
6077 try:
6078 print(kconf.load_config(allconfig, False))
6079 except IOError as e:
6080 sys.exit("error: KCONFIG_ALLCONFIG is set to '{}', which "
6081 "could not be opened: {}"
6082 .format(allconfig, std_msg(e)))
[f596dde]6083
[cf2f109]6084 kconf.warn_assign_override = old_warn_assign_override
6085 kconf.warn_assign_redun = old_warn_assign_redun
[f596dde]6086
6087
6088#
6089# Internal functions
6090#
6091
6092
6093def _visibility(sc):
6094 # Symbols and Choices have a "visibility" that acts as an upper bound on
6095 # the values a user can set for them, corresponding to the visibility in
6096 # e.g. 'make menuconfig'. This function calculates the visibility for the
6097 # Symbol or Choice 'sc' -- the logic is nearly identical.
6098
6099 vis = 0
6100
6101 for node in sc.nodes:
6102 if node.prompt:
6103 vis = max(vis, expr_value(node.prompt[1]))
6104
6105 if sc.__class__ is Symbol and sc.choice:
6106 if sc.choice.orig_type is TRISTATE and \
6107 sc.orig_type is not TRISTATE and sc.choice.tri_value != 2:
6108 # Non-tristate choice symbols are only visible in y mode
6109 return 0
6110
6111 if sc.orig_type is TRISTATE and vis == 1 and sc.choice.tri_value == 2:
6112 # Choice symbols with m visibility are not visible in y mode
6113 return 0
6114
6115 # Promote m to y if we're dealing with a non-tristate (possibly due to
6116 # modules being disabled)
6117 if vis == 1 and sc.type is not TRISTATE:
6118 return 2
6119
6120 return vis
6121
6122
6123def _make_depend_on(sc, expr):
6124 # Adds 'sc' (symbol or choice) as a "dependee" to all symbols in 'expr'.
6125 # Constant symbols in 'expr' are skipped as they can never change value
6126 # anyway.
6127
6128 if expr.__class__ is tuple:
6129 # AND, OR, NOT, or relation
6130
6131 _make_depend_on(sc, expr[1])
6132
6133 # NOTs only have a single operand
6134 if expr[0] is not NOT:
6135 _make_depend_on(sc, expr[2])
6136
6137 elif not expr.is_constant:
6138 # Non-constant symbol, or choice
6139 expr._dependents.add(sc)
6140
6141
6142def _parenthesize(expr, type_, sc_expr_str_fn):
6143 # expr_str() helper. Adds parentheses around expressions of type 'type_'.
6144
6145 if expr.__class__ is tuple and expr[0] is type_:
6146 return "({})".format(expr_str(expr, sc_expr_str_fn))
6147 return expr_str(expr, sc_expr_str_fn)
6148
6149
6150def _ordered_unique(lst):
6151 # Returns 'lst' with any duplicates removed, preserving order. This hacky
6152 # version seems to be a common idiom. It relies on short-circuit evaluation
6153 # and set.add() returning None, which is falsy.
6154
6155 seen = set()
6156 seen_add = seen.add
6157 return [x for x in lst if x not in seen and not seen_add(x)]
6158
6159
6160def _is_base_n(s, n):
6161 try:
6162 int(s, n)
6163 return True
6164 except ValueError:
6165 return False
6166
6167
6168def _strcmp(s1, s2):
6169 # strcmp()-alike that returns -1, 0, or 1
6170
6171 return (s1 > s2) - (s1 < s2)
6172
6173
6174def _sym_to_num(sym):
6175 # expr_value() helper for converting a symbol to a number. Raises
6176 # ValueError for symbols that can't be converted.
6177
6178 # For BOOL and TRISTATE, n/m/y count as 0/1/2. This mirrors 9059a3493ef
6179 # ("kconfig: fix relational operators for bool and tristate symbols") in
6180 # the C implementation.
6181 return sym.tri_value if sym.orig_type in _BOOL_TRISTATE else \
6182 int(sym.str_value, _TYPE_TO_BASE[sym.orig_type])
6183
6184
[cf2f109]6185def _touch_dep_file(path, sym_name):
[f596dde]6186 # If sym_name is MY_SYM_NAME, touches my/sym/name.h. See the sync_deps()
6187 # docstring.
6188
[cf2f109]6189 sym_path = path + os.sep + sym_name.lower().replace("_", os.sep) + ".h"
[f596dde]6190 sym_path_dir = dirname(sym_path)
[cf2f109]6191 if not exists(sym_path_dir):
[f596dde]6192 os.makedirs(sym_path_dir, 0o755)
6193
6194 # A kind of truncating touch, mirroring the C tools
6195 os.close(os.open(
6196 sym_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644))
6197
6198
6199def _save_old(path):
6200 # See write_config()
6201
[cf2f109]6202 def copy(src, dst):
6203 # Import as needed, to save some startup time
6204 import shutil
6205 shutil.copyfile(src, dst)
6206
6207 if islink(path):
6208 # Preserve symlinks
6209 copy_fn = copy
6210 elif hasattr(os, "replace"):
6211 # Python 3 (3.3+) only. Best choice when available, because it
6212 # removes <filename>.old on both *nix and Windows.
6213 copy_fn = os.replace
6214 elif os.name == "posix":
6215 # Removes <filename>.old on POSIX systems
6216 copy_fn = os.rename
6217 else:
6218 # Fall back on copying
6219 copy_fn = copy
[f596dde]6220
6221 try:
[cf2f109]6222 copy_fn(path, path + ".old")
6223 except Exception:
6224 # Ignore errors from 'path' missing as well as other errors.
6225 # <filename>.old file is usually more of a nice-to-have, and not worth
6226 # erroring out over e.g. if <filename>.old happens to be a directory or
6227 # <filename> is something like /dev/null.
[f596dde]6228 pass
6229
6230
6231def _name_and_loc(sc):
6232 # Helper for giving the symbol/choice name and location(s) in e.g. warnings
6233
6234 # Reuse the expression format. That way choices show up as
6235 # '<choice (name, if any)>'
6236 name = standard_sc_expr_str(sc)
6237
6238 if not sc.nodes:
6239 return name + " (undefined)"
6240
6241 return "{} (defined at {})".format(
6242 name,
6243 ", ".join("{}:{}".format(node.filename, node.linenr)
6244 for node in sc.nodes))
6245
6246
6247# Menu manipulation
6248
6249
6250def _expr_depends_on(expr, sym):
6251 # Reimplementation of expr_depends_symbol() from mconf.c. Used to determine
6252 # if a submenu should be implicitly created. This also influences which
6253 # items inside choice statements are considered choice items.
6254
6255 if expr.__class__ is not tuple:
6256 return expr is sym
6257
6258 if expr[0] in _EQUAL_UNEQUAL:
6259 # Check for one of the following:
6260 # sym = m/y, m/y = sym, sym != n, n != sym
6261
6262 left, right = expr[1:]
6263
6264 if right is sym:
6265 left, right = right, left
6266 elif left is not sym:
6267 return False
6268
6269 return (expr[0] is EQUAL and right is sym.kconfig.m or
6270 right is sym.kconfig.y) or \
6271 (expr[0] is UNEQUAL and right is sym.kconfig.n)
6272
6273 return expr[0] is AND and \
6274 (_expr_depends_on(expr[1], sym) or
6275 _expr_depends_on(expr[2], sym))
6276
6277
6278def _auto_menu_dep(node1, node2):
6279 # Returns True if node2 has an "automatic menu dependency" on node1. If
6280 # node2 has a prompt, we check its condition. Otherwise, we look directly
6281 # at node2.dep.
6282
6283 return _expr_depends_on(node2.prompt[1] if node2.prompt else node2.dep,
6284 node1.item)
6285
6286
6287def _flatten(node):
6288 # "Flattens" menu nodes without prompts (e.g. 'if' nodes and non-visible
6289 # symbols with children from automatic menu creation) so that their
6290 # children appear after them instead. This gives a clean menu structure
6291 # with no unexpected "jumps" in the indentation.
6292 #
6293 # Do not flatten promptless choices (which can appear "legitimately" if a
6294 # named choice is defined in multiple locations to add on symbols). It
6295 # looks confusing, and the menuconfig already shows all choice symbols if
6296 # you enter the choice at some location with a prompt.
6297
6298 while node:
6299 if node.list and not node.prompt and \
6300 node.item.__class__ is not Choice:
6301
6302 last_node = node.list
6303 while 1:
6304 last_node.parent = node.parent
6305 if not last_node.next:
6306 break
6307 last_node = last_node.next
6308
6309 last_node.next = node.next
6310 node.next = node.list
6311 node.list = None
6312
6313 node = node.next
6314
6315
6316def _remove_ifs(node):
6317 # Removes 'if' nodes (which can be recognized by MenuNode.item being None),
6318 # which are assumed to already have been flattened. The C implementation
6319 # doesn't bother to do this, but we expose the menu tree directly, and it
6320 # makes it nicer to work with.
6321
6322 cur = node.list
6323 while cur and not cur.item:
6324 cur = cur.next
6325
6326 node.list = cur
6327
6328 while cur:
6329 next = cur.next
6330 while next and not next.item:
6331 next = next.next
6332
6333 # Equivalent to
6334 #
6335 # cur.next = next
6336 # cur = next
6337 #
6338 # due to tricky Python semantics. The order matters.
6339 cur.next = cur = next
6340
6341
6342def _finalize_choice(node):
6343 # Finalizes a choice, marking each symbol whose menu node has the choice as
6344 # the parent as a choice symbol, and automatically determining types if not
6345 # specified.
6346
6347 choice = node.item
6348
6349 cur = node.list
6350 while cur:
6351 if cur.item.__class__ is Symbol:
6352 cur.item.choice = choice
6353 choice.syms.append(cur.item)
6354 cur = cur.next
6355
6356 # If no type is specified for the choice, its type is that of
6357 # the first choice item with a specified type
6358 if not choice.orig_type:
6359 for item in choice.syms:
6360 if item.orig_type:
6361 choice.orig_type = item.orig_type
6362 break
6363
6364 # Each choice item of UNKNOWN type gets the type of the choice
6365 for sym in choice.syms:
6366 if not sym.orig_type:
6367 sym.orig_type = choice.orig_type
6368
6369
6370def _check_dep_loop_sym(sym, ignore_choice):
6371 # Detects dependency loops using depth-first search on the dependency graph
6372 # (which is calculated earlier in Kconfig._build_dep()).
6373 #
6374 # Algorithm:
6375 #
6376 # 1. Symbols/choices start out with _visited = 0, meaning unvisited.
6377 #
6378 # 2. When a symbol/choice is first visited, _visited is set to 1, meaning
6379 # "visited, potentially part of a dependency loop". The recursive
6380 # search then continues from the symbol/choice.
6381 #
6382 # 3. If we run into a symbol/choice X with _visited already set to 1,
6383 # there's a dependency loop. The loop is found on the call stack by
6384 # recording symbols while returning ("on the way back") until X is seen
6385 # again.
6386 #
6387 # 4. Once a symbol/choice and all its dependencies (or dependents in this
6388 # case) have been checked recursively without detecting any loops, its
6389 # _visited is set to 2, meaning "visited, not part of a dependency
6390 # loop".
6391 #
6392 # This saves work if we run into the symbol/choice again in later calls
6393 # to _check_dep_loop_sym(). We just return immediately.
6394 #
6395 # Choices complicate things, as every choice symbol depends on every other
6396 # choice symbol in a sense. When a choice is "entered" via a choice symbol
6397 # X, we visit all choice symbols from the choice except X, and prevent
6398 # immediately revisiting the choice with a flag (ignore_choice).
6399 #
6400 # Maybe there's a better way to handle this (different flags or the
6401 # like...)
6402
6403 if not sym._visited:
6404 # sym._visited == 0, unvisited
6405
6406 sym._visited = 1
6407
6408 for dep in sym._dependents:
6409 # Choices show up in Symbol._dependents when the choice has the
6410 # symbol in a 'prompt' or 'default' condition (e.g.
6411 # 'default ... if SYM').
6412 #
6413 # Since we aren't entering the choice via a choice symbol, all
6414 # choice symbols need to be checked, hence the None.
6415 loop = _check_dep_loop_choice(dep, None) \
6416 if dep.__class__ is Choice \
6417 else _check_dep_loop_sym(dep, False)
6418
6419 if loop:
6420 # Dependency loop found
6421 return _found_dep_loop(loop, sym)
6422
6423 if sym.choice and not ignore_choice:
6424 loop = _check_dep_loop_choice(sym.choice, sym)
6425 if loop:
6426 # Dependency loop found
6427 return _found_dep_loop(loop, sym)
6428
6429 # The symbol is not part of a dependency loop
6430 sym._visited = 2
6431
6432 # No dependency loop found
6433 return None
6434
6435 if sym._visited == 2:
6436 # The symbol was checked earlier and is already known to not be part of
6437 # a dependency loop
6438 return None
6439
6440 # sym._visited == 1, found a dependency loop. Return the symbol as the
6441 # first element in it.
6442 return (sym,)
6443
6444
6445def _check_dep_loop_choice(choice, skip):
6446 if not choice._visited:
6447 # choice._visited == 0, unvisited
6448
6449 choice._visited = 1
6450
6451 # Check for loops involving choice symbols. If we came here via a
6452 # choice symbol, skip that one, as we'd get a false positive
6453 # '<sym FOO> -> <choice> -> <sym FOO>' loop otherwise.
6454 for sym in choice.syms:
6455 if sym is not skip:
6456 # Prevent the choice from being immediately re-entered via the
6457 # "is a choice symbol" path by passing True
6458 loop = _check_dep_loop_sym(sym, True)
6459 if loop:
6460 # Dependency loop found
6461 return _found_dep_loop(loop, choice)
6462
6463 # The choice is not part of a dependency loop
6464 choice._visited = 2
6465
6466 # No dependency loop found
6467 return None
6468
6469 if choice._visited == 2:
6470 # The choice was checked earlier and is already known to not be part of
6471 # a dependency loop
6472 return None
6473
6474 # choice._visited == 1, found a dependency loop. Return the choice as the
6475 # first element in it.
6476 return (choice,)
6477
6478
6479def _found_dep_loop(loop, cur):
6480 # Called "on the way back" when we know we have a loop
6481
6482 # Is the symbol/choice 'cur' where the loop started?
6483 if cur is not loop[0]:
6484 # Nope, it's just a part of the loop
6485 return loop + (cur,)
6486
6487 # Yep, we have the entire loop. Throw an exception that shows it.
6488
6489 msg = "\nDependency loop\n" \
6490 "===============\n\n"
6491
6492 for item in loop:
6493 if item is not loop[0]:
6494 msg += "...depends on "
6495 if item.__class__ is Symbol and item.choice:
6496 msg += "the choice symbol "
6497
6498 msg += "{}, with definition...\n\n{}\n\n" \
6499 .format(_name_and_loc(item), item)
6500
6501 # Small wart: Since we reuse the already calculated
6502 # Symbol/Choice._dependents sets for recursive dependency detection, we
6503 # lose information on whether a dependency came from a 'select'/'imply'
6504 # condition or e.g. a 'depends on'.
6505 #
6506 # This might cause selecting symbols to "disappear". For example,
6507 # a symbol B having 'select A if C' gives a direct dependency from A to
6508 # C, since it corresponds to a reverse dependency of B && C.
6509 #
6510 # Always print reverse dependencies for symbols that have them to make
6511 # sure information isn't lost. I wonder if there's some neat way to
6512 # improve this.
6513
6514 if item.__class__ is Symbol:
6515 if item.rev_dep is not item.kconfig.n:
6516 msg += "(select-related dependencies: {})\n\n" \
6517 .format(expr_str(item.rev_dep))
6518
6519 if item.weak_rev_dep is not item.kconfig.n:
6520 msg += "(imply-related dependencies: {})\n\n" \
6521 .format(expr_str(item.rev_dep))
6522
6523 msg += "...depends again on {}".format(_name_and_loc(loop[0]))
6524
6525 raise KconfigError(msg)
6526
6527
[cf2f109]6528def _decoding_error(e, filename, macro_linenr=None):
6529 # Gives the filename and context for UnicodeDecodeError's, which are a pain
6530 # to debug otherwise. 'e' is the UnicodeDecodeError object.
6531 #
6532 # If the decoding error is for the output of a $(shell,...) command,
6533 # macro_linenr holds the line number where it was run (the exact line
6534 # number isn't available for decoding errors in files).
6535
6536 raise KconfigError(
6537 "\n"
6538 "Malformed {} in {}\n"
6539 "Context: {}\n"
6540 "Problematic data: {}\n"
6541 "Reason: {}".format(
6542 e.encoding,
6543 "'{}'".format(filename) if macro_linenr is None else
6544 "output from macro at {}:{}".format(filename, macro_linenr),
6545 e.object[max(e.start - 40, 0):e.end + 40],
6546 e.object[e.start:e.end],
6547 e.reason))
6548
6549
6550def _warn_verbose_deprecated(fn_name):
6551 sys.stderr.write(
6552 "Deprecation warning: {0}()'s 'verbose' argument has no effect. Since "
6553 "Kconfiglib 12.0.0, the message is returned from {0}() instead, "
6554 "and is always generated. Do e.g. print(kconf.{0}()) if you want to "
6555 "want to show a message like \"Loaded configuration '.config'\" on "
6556 "stdout. The old API required ugly hacks to reuse messages in "
6557 "configuration interfaces.\n".format(fn_name))
6558
6559
[f596dde]6560# Predefined preprocessor functions
6561
6562
6563def _filename_fn(kconf, _):
6564 return kconf._filename
6565
6566
6567def _lineno_fn(kconf, _):
6568 return str(kconf._linenr)
6569
6570
6571def _info_fn(kconf, _, msg):
6572 print("{}:{}: {}".format(kconf._filename, kconf._linenr, msg))
6573
6574 return ""
6575
6576
6577def _warning_if_fn(kconf, _, cond, msg):
6578 if cond == "y":
6579 kconf._warn(msg, kconf._filename, kconf._linenr)
6580
6581 return ""
6582
6583
6584def _error_if_fn(kconf, _, cond, msg):
6585 if cond == "y":
6586 raise KconfigError("{}:{}: {}".format(
6587 kconf._filename, kconf._linenr, msg))
6588
6589 return ""
6590
6591
6592def _shell_fn(kconf, _, command):
6593 # Only import as needed, to save some startup time
6594 import subprocess
6595
6596 stdout, stderr = subprocess.Popen(
6597 command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE
6598 ).communicate()
6599
6600 if not _IS_PY2:
6601 try:
6602 stdout = stdout.decode(kconf._encoding)
6603 stderr = stderr.decode(kconf._encoding)
6604 except UnicodeDecodeError as e:
6605 _decoding_error(e, kconf._filename, kconf._linenr)
6606
6607 if stderr:
6608 kconf._warn("'{}' wrote to stderr: {}".format(
6609 command, "\n".join(stderr.splitlines())),
6610 kconf._filename, kconf._linenr)
6611
6612 # Universal newlines with splitlines() (to prevent e.g. stray \r's in
6613 # command output on Windows), trailing newline removal, and
6614 # newline-to-space conversion.
6615 #
6616 # On Python 3 versions before 3.6, it's not possible to specify the
6617 # encoding when passing universal_newlines=True to Popen() (the 'encoding'
6618 # parameter was added in 3.6), so we do this manual version instead.
6619 return "\n".join(stdout.splitlines()).rstrip("\n").replace("\n", " ")
6620
6621#
6622# Global constants
6623#
6624
6625TRI_TO_STR = {
6626 0: "n",
6627 1: "m",
6628 2: "y",
6629}
6630
6631STR_TO_TRI = {
6632 "n": 0,
6633 "m": 1,
6634 "y": 2,
6635}
6636
6637# Constant representing that there's no cached choice selection. This is
6638# distinct from a cached None (no selection). Any object that's not None or a
6639# Symbol will do. We test this with 'is'.
6640_NO_CACHED_SELECTION = 0
6641
6642# Are we running on Python 2?
6643_IS_PY2 = sys.version_info[0] < 3
6644
6645try:
6646 _UNAME_RELEASE = os.uname()[2]
6647except AttributeError:
6648 # Only import as needed, to save some startup time
6649 import platform
6650 _UNAME_RELEASE = platform.uname()[2]
6651
[cf2f109]6652# The token and type constants below are safe to test with 'is', which is a bit
6653# faster (~30% faster on my machine, and a few % faster for total parsing
[f596dde]6654# time), even without assuming Python's small integer optimization (which
6655# caches small integer objects). The constants end up pointing to unique
6656# integer objects, and since we consistently refer to them via the names below,
6657# we always get the same object.
6658#
6659# Client code should use == though.
6660
6661# Tokens, with values 1, 2, ... . Avoiding 0 simplifies some checks by making
6662# all tokens except empty strings truthy.
6663(
6664 _T_ALLNOCONFIG_Y,
6665 _T_AND,
6666 _T_BOOL,
6667 _T_CHOICE,
6668 _T_CLOSE_PAREN,
6669 _T_COMMENT,
6670 _T_CONFIG,
6671 _T_DEFAULT,
6672 _T_DEFCONFIG_LIST,
6673 _T_DEF_BOOL,
6674 _T_DEF_HEX,
6675 _T_DEF_INT,
6676 _T_DEF_STRING,
6677 _T_DEF_TRISTATE,
6678 _T_DEPENDS,
6679 _T_ENDCHOICE,
6680 _T_ENDIF,
6681 _T_ENDMENU,
6682 _T_ENV,
6683 _T_EQUAL,
6684 _T_GREATER,
6685 _T_GREATER_EQUAL,
6686 _T_HELP,
6687 _T_HEX,
6688 _T_IF,
6689 _T_IMPLY,
6690 _T_INT,
6691 _T_LESS,
6692 _T_LESS_EQUAL,
6693 _T_MAINMENU,
6694 _T_MENU,
6695 _T_MENUCONFIG,
6696 _T_MODULES,
6697 _T_NOT,
6698 _T_ON,
6699 _T_OPEN_PAREN,
6700 _T_OPTION,
6701 _T_OPTIONAL,
6702 _T_OR,
6703 _T_ORSOURCE,
6704 _T_OSOURCE,
6705 _T_PROMPT,
6706 _T_RANGE,
6707 _T_RSOURCE,
6708 _T_SELECT,
6709 _T_SOURCE,
6710 _T_STRING,
6711 _T_TRISTATE,
6712 _T_UNEQUAL,
6713 _T_VISIBLE,
6714) = range(1, 51)
6715
6716# Keyword to token map, with the get() method assigned directly as a small
6717# optimization
6718_get_keyword = {
6719 "---help---": _T_HELP,
6720 "allnoconfig_y": _T_ALLNOCONFIG_Y,
6721 "bool": _T_BOOL,
6722 "boolean": _T_BOOL,
6723 "choice": _T_CHOICE,
6724 "comment": _T_COMMENT,
6725 "config": _T_CONFIG,
6726 "def_bool": _T_DEF_BOOL,
6727 "def_hex": _T_DEF_HEX,
6728 "def_int": _T_DEF_INT,
6729 "def_string": _T_DEF_STRING,
6730 "def_tristate": _T_DEF_TRISTATE,
6731 "default": _T_DEFAULT,
6732 "defconfig_list": _T_DEFCONFIG_LIST,
6733 "depends": _T_DEPENDS,
6734 "endchoice": _T_ENDCHOICE,
6735 "endif": _T_ENDIF,
6736 "endmenu": _T_ENDMENU,
6737 "env": _T_ENV,
6738 "grsource": _T_ORSOURCE, # Backwards compatibility
6739 "gsource": _T_OSOURCE, # Backwards compatibility
6740 "help": _T_HELP,
6741 "hex": _T_HEX,
6742 "if": _T_IF,
6743 "imply": _T_IMPLY,
6744 "int": _T_INT,
6745 "mainmenu": _T_MAINMENU,
6746 "menu": _T_MENU,
6747 "menuconfig": _T_MENUCONFIG,
6748 "modules": _T_MODULES,
6749 "on": _T_ON,
6750 "option": _T_OPTION,
6751 "optional": _T_OPTIONAL,
6752 "orsource": _T_ORSOURCE,
6753 "osource": _T_OSOURCE,
6754 "prompt": _T_PROMPT,
6755 "range": _T_RANGE,
6756 "rsource": _T_RSOURCE,
6757 "select": _T_SELECT,
6758 "source": _T_SOURCE,
6759 "string": _T_STRING,
6760 "tristate": _T_TRISTATE,
6761 "visible": _T_VISIBLE,
6762}.get
6763
6764# The constants below match the value of the corresponding tokens to remove the
6765# need for conversion
6766
6767# Node types
6768MENU = _T_MENU
6769COMMENT = _T_COMMENT
6770
6771# Expression types
6772AND = _T_AND
6773OR = _T_OR
6774NOT = _T_NOT
6775EQUAL = _T_EQUAL
6776UNEQUAL = _T_UNEQUAL
6777LESS = _T_LESS
6778LESS_EQUAL = _T_LESS_EQUAL
6779GREATER = _T_GREATER
6780GREATER_EQUAL = _T_GREATER_EQUAL
6781
6782_REL_TO_STR = {
6783 EQUAL: "=",
6784 UNEQUAL: "!=",
6785 LESS: "<",
6786 LESS_EQUAL: "<=",
6787 GREATER: ">",
6788 GREATER_EQUAL: ">=",
6789}
6790
6791# Symbol/choice types. UNKNOWN is 0 (falsy) to simplify some checks.
6792# Client code shouldn't rely on it though, as it was non-zero in
6793# older versions.
6794UNKNOWN = 0
6795BOOL = _T_BOOL
6796TRISTATE = _T_TRISTATE
6797STRING = _T_STRING
6798INT = _T_INT
6799HEX = _T_HEX
6800
6801TYPE_TO_STR = {
6802 UNKNOWN: "unknown",
6803 BOOL: "bool",
6804 TRISTATE: "tristate",
6805 STRING: "string",
6806 INT: "int",
6807 HEX: "hex",
6808}
6809
6810# Used in comparisons. 0 means the base is inferred from the format of the
6811# string.
6812_TYPE_TO_BASE = {
6813 HEX: 16,
6814 INT: 10,
6815 STRING: 0,
6816 UNKNOWN: 0,
6817}
6818
6819# def_bool -> BOOL, etc.
6820_DEF_TOKEN_TO_TYPE = {
6821 _T_DEF_BOOL: BOOL,
6822 _T_DEF_HEX: HEX,
6823 _T_DEF_INT: INT,
6824 _T_DEF_STRING: STRING,
6825 _T_DEF_TRISTATE: TRISTATE,
6826}
6827
6828# Tokens after which strings are expected. This is used to tell strings from
6829# constant symbol references during tokenization, both of which are enclosed in
6830# quotes.
6831#
6832# Identifier-like lexemes ("missing quotes") are also treated as strings after
6833# these tokens. _T_CHOICE is included to avoid symbols being registered for
6834# named choices.
6835_STRING_LEX = frozenset((
6836 _T_BOOL,
6837 _T_CHOICE,
6838 _T_COMMENT,
6839 _T_HEX,
6840 _T_INT,
6841 _T_MAINMENU,
6842 _T_MENU,
6843 _T_ORSOURCE,
6844 _T_OSOURCE,
6845 _T_PROMPT,
6846 _T_RSOURCE,
6847 _T_SOURCE,
6848 _T_STRING,
6849 _T_TRISTATE,
6850))
6851
6852# Various sets for quick membership tests. Gives a single global lookup and
6853# avoids creating temporary dicts/tuples.
6854
6855_TYPE_TOKENS = frozenset((
6856 _T_BOOL,
6857 _T_TRISTATE,
6858 _T_INT,
6859 _T_HEX,
6860 _T_STRING,
6861))
6862
6863_SOURCE_TOKENS = frozenset((
6864 _T_SOURCE,
6865 _T_RSOURCE,
6866 _T_OSOURCE,
6867 _T_ORSOURCE,
6868))
6869
6870_REL_SOURCE_TOKENS = frozenset((
6871 _T_RSOURCE,
6872 _T_ORSOURCE,
6873))
6874
6875# Obligatory (non-optional) sources
6876_OBL_SOURCE_TOKENS = frozenset((
6877 _T_SOURCE,
6878 _T_RSOURCE,
6879))
6880
6881_BOOL_TRISTATE = frozenset((
6882 BOOL,
6883 TRISTATE,
6884))
6885
6886_BOOL_TRISTATE_UNKNOWN = frozenset((
6887 BOOL,
6888 TRISTATE,
6889 UNKNOWN,
6890))
6891
6892_INT_HEX = frozenset((
6893 INT,
6894 HEX,
6895))
6896
6897_STRING_INT_HEX = frozenset((
6898 STRING,
6899 INT,
6900 HEX,
6901))
6902
6903_SYMBOL_CHOICE = frozenset((
6904 Symbol,
6905 Choice,
6906))
6907
6908_MENU_COMMENT = frozenset((
6909 MENU,
6910 COMMENT,
6911))
6912
6913_EQUAL_UNEQUAL = frozenset((
6914 EQUAL,
6915 UNEQUAL,
6916))
6917
6918_RELATIONS = frozenset((
6919 EQUAL,
6920 UNEQUAL,
6921 LESS,
6922 LESS_EQUAL,
6923 GREATER,
6924 GREATER_EQUAL,
6925))
6926
6927# Helper functions for getting compiled regular expressions, with the needed
6928# matching function returned directly as a small optimization.
6929#
6930# Use ASCII regex matching on Python 3. It's already the default on Python 2.
6931
6932
6933def _re_match(regex):
6934 return re.compile(regex, 0 if _IS_PY2 else re.ASCII).match
6935
6936
6937def _re_search(regex):
6938 return re.compile(regex, 0 if _IS_PY2 else re.ASCII).search
6939
6940
6941# Various regular expressions used during parsing
6942
6943# The initial token on a line. Also eats leading and trailing whitespace, so
6944# that we can jump straight to the next token (or to the end of the line if
6945# there is only one token).
6946#
6947# This regex will also fail to match for empty lines and comment lines.
6948#
6949# '$' is included to detect preprocessor variable assignments with macro
6950# expansions in the left-hand side.
[cf2f109]6951_command_match = _re_match(r"\s*([A-Za-z0-9_$-]+)\s*")
[f596dde]6952
6953# An identifier/keyword after the first token. Also eats trailing whitespace.
6954# '$' is included to detect identifiers containing macro expansions.
[cf2f109]6955_id_keyword_match = _re_match(r"([A-Za-z0-9_$/.-]+)\s*")
[f596dde]6956
6957# A fragment in the left-hand side of a preprocessor variable assignment. These
6958# are the portions between macro expansions ($(foo)). Macros are supported in
6959# the LHS (variable name).
6960_assignment_lhs_fragment_match = _re_match("[A-Za-z0-9_-]*")
6961
6962# The assignment operator and value (right-hand side) in a preprocessor
6963# variable assignment
6964_assignment_rhs_match = _re_match(r"\s*(=|:=|\+=)\s*(.*)")
6965
6966# Special characters/strings while expanding a macro (')', ',', and '$(')
6967_macro_special_search = _re_search(r"\)|,|\$\(")
6968
6969# Special characters/strings while expanding a string (quotes, '\', and '$(')
6970_string_special_search = _re_search(r'"|\'|\\|\$\(')
6971
6972# Special characters/strings while expanding a symbol name. Also includes
6973# end-of-line, in case the macro is the last thing on the line.
6974_name_special_search = _re_search(r'[^$A-Za-z0-9_/.-]|\$\(|$')
6975
6976# A valid right-hand side for an assignment to a string symbol in a .config
6977# file, including escaped characters. Extracts the contents.
6978_conf_string_match = _re_match(r'"((?:[^\\"]|\\.)*)"')
Note: See TracBrowser for help on using the repository browser.