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