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