This repository has been archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
kconfiglib.py
3462 lines (2809 loc) · 133 KB
/
kconfiglib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This is Kconfiglib, a Python library for scripting, debugging, and extracting
# information from Kconfig-based configuration systems. To view the
# documentation, run
#
# $ pydoc kconfiglib
#
# or, if you prefer HTML,
#
# $ pydoc -w kconfiglib
#
# The examples/ subdirectory contains examples, to be run with e.g.
#
# $ make scriptconfig SCRIPT=Kconfiglib/examples/print_tree.py
#
# Look in testsuite.py for the test suite.
"""
Kconfiglib is a Python library for scripting and extracting information from
Kconfig-based configuration systems. Features include the following:
- Symbol values and properties can be looked up and values assigned
programmatically.
- .config files can be read and written.
- Expressions can be evaluated in the context of a Kconfig configuration.
- Relations between symbols can be quickly determined, such as finding all
symbols that reference a particular symbol.
- Highly compatible with the scripts/kconfig/*conf utilities. The test suite
automatically compares outputs between Kconfiglib and the C implementation
for a large number of cases.
For the Linux kernel, scripts are run using
$ make scriptconfig [ARCH=<arch>] SCRIPT=<path to script> [SCRIPT_ARG=<arg>]
Using the 'scriptconfig' target ensures that required environment variables
(SRCARCH, ARCH, srctree, KERNELVERSION, etc.) are set up correctly.
Scripts receive the name of the Kconfig file to load in sys.argv[1]. As of
Linux 4.1.0-rc5, this is always "Kconfig" from the kernel top-level directory.
If an argument is provided with SCRIPT_ARG, it appears as sys.argv[2].
To get an interactive Python prompt with Kconfiglib preloaded and a Config
object 'c' created, run
$ make iscriptconfig [ARCH=<arch>]
Kconfiglib supports both Python 2 and Python 3. For (i)scriptconfig, the Python
interpreter to use can be passed in PYTHONCMD, which defaults to 'python'. PyPy
works well too, and might give a nice speedup for long-running jobs.
The examples/ directory contains short example scripts, which can be run with
e.g.
$ make scriptconfig SCRIPT=Kconfiglib/examples/print_tree.py
or
$ make scriptconfig SCRIPT=Kconfiglib/examples/help_grep.py SCRIPT_ARG=kernel
testsuite.py contains the test suite. See the top of the script for how to run
it.
Credits: Written by Ulf "Ulfalizer" Magnusson
Send bug reports, suggestions and other feedback to ulfalizer a.t Google's
email service. Don't wrestle with internal APIs. Tell me what you need and I
might add it in a safe way as a client API instead."""
import os
import re
import sys
import platform
# File layout:
#
# Public classes
# Public functions
# Internal classes
# Internal functions
# Internal global constants
# Line length: 79 columns
#
# Public classes
#
class Config(object):
"""Represents a Kconfig configuration, e.g. for i386 or ARM. This is the
set of symbols and other items appearing in the configuration together with
their values. Creating any number of Config objects -- including for
different architectures -- is safe; Kconfiglib has no global state."""
#
# Public interface
#
def __init__(self, filename="Kconfig", base_dir=None, print_warnings=True,
print_undef_assign=False):
"""Creates a new Config object, representing a Kconfig configuration.
Raises Kconfig_Syntax_Error on syntax errors.
filename (default: "Kconfig"): The base Kconfig file of the
configuration. For the Linux kernel, you'll probably want "Kconfig"
from the top-level directory, as environment variables will make
sure the right Kconfig is included from there
(arch/<architecture>/Kconfig). If you are using Kconfiglib via 'make
scriptconfig', the filename of the base base Kconfig file will be in
sys.argv[1].
base_dir (default: None): The base directory relative to which 'source'
statements within Kconfig files will work. For the Linux kernel this
should be the top-level directory of the kernel tree. $-references
to existing environment variables will be expanded.
If None (the default), the environment variable 'srctree' will be
used if set, and the current directory otherwise. 'srctree' is set
by the Linux makefiles to the top-level kernel directory. A default
of "." would not work with an alternative build directory.
print_warnings (default: True): Set to True if warnings related to this
configuration should be printed to stderr. This can be changed later
with Config.set_print_warnings(). It is provided as a constructor
argument since warnings might be generated during parsing.
print_undef_assign (default: False): Set to True if informational
messages related to assignments to undefined symbols should be
printed to stderr for this configuration. Can be changed later with
Config.set_print_undef_assign()."""
# The set of all symbols, indexed by name (a string)
self.syms = {}
# Python 2/3 compatibility hack. This is the only one needed.
self.syms_iter = self.syms.values if sys.version_info[0] >= 3 else \
self.syms.itervalues
# The set of all defined symbols in the configuration in the order they
# appear in the Kconfig files. This excludes the special symbols n, m,
# and y as well as symbols that are referenced but never defined.
self.kconfig_syms = []
# The set of all named choices (yes, choices can have names), indexed
# by name (a string)
self.named_choices = {}
# Lists containing all choices, menus and comments in the configuration
self.choices = []
self.menus = []
self.comments = []
def register_special_symbol(type_, name, val):
sym = Symbol()
sym.is_special_ = True
sym.is_defined_ = True
sym.config = self
sym.name = name
sym.type = type_
sym.cached_val = val
self.syms[name] = sym
return sym
# The special symbols n, m and y, used as shorthand for "n", "m" and
# "y"
self.n = register_special_symbol(TRISTATE, "n", "n")
self.m = register_special_symbol(TRISTATE, "m", "m")
self.y = register_special_symbol(TRISTATE, "y", "y")
# DEFCONFIG_LIST uses this
# changed os.uname to platform.uname for compatibility with Windows
register_special_symbol(STRING, "UNAME_RELEASE", platform.uname()[2])
# The symbol with "option defconfig_list" set, containing a list of
# default .config files
self.defconfig_sym = None
# See Symbol.get_(src)arch()
self.arch = os.environ.get("ARCH")
self.srcarch = os.environ.get("SRCARCH")
# If you set CONFIG_ in the environment, Kconfig will prefix all symbols
# with its value when saving the configuration, instead of using the default, "CONFIG_".
self.config_prefix = os.environ.get("CONFIG_")
if self.config_prefix is None:
self.config_prefix = "CONFIG_"
# See Config.__init__(). We need this for get_defconfig_filename().
self.srctree = os.environ.get("srctree")
if self.srctree is None:
self.srctree = "."
self.filename = filename
self.base_dir = self.srctree if base_dir is None else \
os.path.expandvars(base_dir)
# The 'mainmenu' text
self.mainmenu_text = None
# The filename of the most recently loaded .config file
self.config_filename = None
# The textual header of the most recently loaded .config, uncommented
self.config_header = None
self.print_warnings = print_warnings
self.print_undef_assign = print_undef_assign
# For parsing routines that stop when finding a line belonging to a
# different construct, these holds that line and the tokenized version
# of that line. The purpose is to avoid having to re-tokenize the line,
# which is inefficient and causes problems when recording references to
# symbols.
self.end_line = None
self.end_line_tokens = None
# See the comment in _parse_expr().
self._cur_item = None
self._line = None
self._filename = None
self._linenr = None
self._transform_m = None
# Parse the Kconfig files
self.top_block = self._parse_file(filename, None, None, None)
# Build Symbol.dep for all symbols
self._build_dep()
def get_arch(self):
"""Returns the value the environment variable ARCH had at the time the
Config instance was created, or None if ARCH was not set. For the
kernel, this corresponds to the architecture being built for, with
values such as "i386" or "mips"."""
return self.arch
def get_srcarch(self):
"""Returns the value the environment variable SRCARCH had at the time
the Config instance was created, or None if SRCARCH was not set. For
the kernel, this corresponds to the particular arch/ subdirectory
containing architecture-specific code."""
return self.srcarch
def get_srctree(self):
"""Returns the value the environment variable srctree had at the time
the Config instance was created, or None if srctree was not defined.
This variable points to the source directory and is used when building
in a separate directory."""
return self.srctree
def get_base_dir(self):
"""Returns the base directory relative to which 'source' statements
will work, passed as an argument to Config.__init__()."""
return self.base_dir
def get_kconfig_filename(self):
"""Returns the name of the (base) kconfig file this configuration was
loaded from."""
return self.filename
def get_config_filename(self):
"""Returns the filename of the most recently loaded configuration file,
or None if no configuration has been loaded."""
return self.config_filename
def get_config_header(self):
"""Returns the (uncommented) textual header of the .config file most
recently loaded with load_config(). Returns None if no .config file has
been loaded or if the most recently loaded .config file has no header.
The header consists of all lines up to but not including the first line
that either
1. Does not start with "#"
2. Has the form "# CONFIG_FOO is not set."
"""
return self.config_header
def get_mainmenu_text(self):
"""Returns the text of the 'mainmenu' statement (with $-references to
symbols replaced by symbol values), or None if the configuration has no
'mainmenu' statement."""
return None if self.mainmenu_text is None else \
self._expand_sym_refs(self.mainmenu_text)
def get_defconfig_filename(self):
"""Returns the name of the defconfig file, which is the first existing
file in the list given in a symbol having 'option defconfig_list' set.
$-references to symbols will be expanded ("$FOO bar" -> "foo bar" if
FOO has the value "foo"). Returns None in case of no defconfig file.
Setting 'option defconfig_list' on multiple symbols currently results
in undefined behavior.
If the environment variable 'srctree' was set when the Config was
created, get_defconfig_filename() will first look relative to that
directory before looking in the current directory; see
Config.__init__().
WARNING: A wart here is that scripts/kconfig/Makefile sometimes uses
the --defconfig=<defconfig> option when calling the C implementation of
e.g. 'make defconfig'. This option overrides the 'option
defconfig_list' symbol, meaning the result from
get_defconfig_filename() might not match what 'make defconfig' would
use. That probably ought to be worked around somehow, so that this
function always gives the "expected" result."""
if self.defconfig_sym is None:
return None
for filename, cond_expr in self.defconfig_sym.def_exprs:
if self._eval_expr(cond_expr) == "y":
filename = self._expand_sym_refs(filename)
# We first look in $srctree. os.path.join() won't work here as
# an absolute path in filename would override $srctree.
srctree_filename = os.path.normpath(self.srctree + "/" +
filename)
if os.path.exists(srctree_filename):
return srctree_filename
if os.path.exists(filename):
return filename
return None
def get_symbol(self, name):
"""Returns the symbol with name 'name', or None if no such symbol
appears in the configuration. An alternative shorthand is conf[name],
where conf is a Config instance, though that will instead raise
KeyError if the symbol does not exist."""
return self.syms.get(name)
def __getitem__(self, name):
"""Returns the symbol with name 'name'. Raises KeyError if the symbol
does not appear in the configuration."""
return self.syms[name]
def get_symbols(self, all_symbols=True):
"""Returns a list of symbols from the configuration. An alternative for
iterating over all defined symbols (in the order of definition) is
for sym in config:
...
which relies on Config implementing __iter__() and is equivalent to
for sym in config.get_symbols(False):
...
all_symbols (default: True): If True, all symbols -- including special
and undefined symbols -- will be included in the result, in an
undefined order. If False, only symbols actually defined and not
merely referred to in the configuration will be included in the
result, and will appear in the order that they are defined within
the Kconfig configuration files."""
return list(self.syms.values()) if all_symbols else self.kconfig_syms
def __iter__(self):
"""Convenience function for iterating over the set of all defined
symbols in the configuration, used like
for sym in conf:
...
The iteration happens in the order of definition within the Kconfig
configuration files. Symbols only referred to but not defined will not
be included, nor will the special symbols n, m, and y. If you want to
include such symbols as well, see config.get_symbols()."""
return iter(self.kconfig_syms)
def get_choices(self):
"""Returns a list containing all choice statements in the
configuration, in the order they appear in the Kconfig files."""
return self.choices
def get_menus(self):
"""Returns a list containing all menus in the configuration, in the
order they appear in the Kconfig files."""
return self.menus
def get_comments(self):
"""Returns a list containing all comments in the configuration, in the
order they appear in the Kconfig files."""
return self.comments
def get_top_level_items(self):
"""Returns a list containing the items (symbols, menus, choices, and
comments) at the top level of the configuration -- that is, all items
that do not appear within a menu or choice. The items appear in the
same order as within the configuration."""
return self.top_block
def load_config(self, filename, replace=True):
"""Loads symbol values from a file in the familiar .config format.
Equivalent to calling Symbol.set_user_value() to set each of the
values.
"# CONFIG_FOO is not set" within a .config file is treated specially
and sets the user value of FOO to 'n'. The C implementation works the
same way.
filename: The .config file to load. $-references to existing
environment variables will be expanded. For scripts to work even when
an alternative build directory is used with the Linux kernel, you
need to refer to the top-level kernel directory with "$srctree".
replace (default: True): True if the configuration should replace the
old configuration; False if it should add to it."""
# Regular expressions for parsing .config files
_set_re_match = re.compile(r"{}(\w+)=(.*)".format(self.config_prefix)).match
_unset_re_match = re.compile(r"# {}(\w+) is not set".format(self.config_prefix)).match
# Put this first so that a missing file doesn't screw up our state
filename = os.path.expandvars(filename)
line_feeder = _FileFeed(filename)
self.config_filename = filename
#
# Read header
#
def is_header_line(line):
return line is not None and line.startswith("#") and \
not _unset_re_match(line)
self.config_header = None
line = line_feeder.peek_next()
if is_header_line(line):
self.config_header = ""
while is_header_line(line_feeder.peek_next()):
self.config_header += line_feeder.get_next()[1:]
# Remove trailing newline
if self.config_header.endswith("\n"):
self.config_header = self.config_header[:-1]
#
# Read assignments. Hotspot for some workloads.
#
def warn_override(filename, linenr, name, old_user_val, new_user_val):
self._warn('overriding the value of {0}. '
'Old value: "{1}", new value: "{2}".'
.format(name, old_user_val, new_user_val),
filename, linenr)
# Invalidate everything to keep things simple. It might be possible to
# improve performance for the case where multiple configurations are
# loaded by only invalidating a symbol (and its dependent symbols) if
# the new user value differs from the old. One complication would be
# that symbols not mentioned in the .config must lose their user value
# when replace = True, which is the usual case.
if replace:
self.unset_user_values()
else:
self._invalidate_all()
while 1:
line = line_feeder.get_next()
if line is None:
return
line = line.rstrip()
set_match = _set_re_match(line)
if set_match:
name, val = set_match.groups()
if val.startswith('"'):
if len(val) < 2 or val[-1] != '"':
_parse_error(line, "malformed string literal",
line_feeder.filename, line_feeder.linenr)
# Strip quotes and remove escapings. The unescaping
# procedure should be safe since " can only appear as \"
# inside the string.
val = val[1:-1].replace('\\"', '"').replace("\\\\", "\\")
if name in self.syms:
sym = self.syms[name]
if sym.user_val is not None:
warn_override(line_feeder.filename, line_feeder.linenr,
name, sym.user_val, val)
if sym.is_choice_sym:
user_mode = sym.parent.user_mode
if user_mode is not None and user_mode != val:
self._warn("assignment to {0} changes mode of "
'containing choice from "{1}" to "{2}".'
.format(name, val, user_mode),
line_feeder.filename,
line_feeder.linenr)
sym._set_user_value_no_invalidate(val, True)
else:
if self.print_undef_assign:
_stderr_msg('note: attempt to assign the value "{0}" '
"to the undefined symbol {1}."
.format(val, name),
line_feeder.filename, line_feeder.linenr)
else:
unset_match = _unset_re_match(line)
if unset_match:
name = unset_match.group(1)
if name in self.syms:
sym = self.syms[name]
if sym.user_val is not None:
warn_override(line_feeder.filename,
line_feeder.linenr,
name, sym.user_val, "n")
sym._set_user_value_no_invalidate("n", True)
def write_config(self, filename, header=None):
"""Writes out symbol values in the familiar .config format.
Kconfiglib makes sure the format matches what the C implementation
would generate, down to whitespace. This eases testing.
filename: The filename under which to save the configuration.
header (default: None): A textual header that will appear at the
beginning of the file, with each line commented out automatically.
None means no header."""
for sym in self.syms_iter():
sym.already_written = False
with open(filename, "w") as f:
# Write header
if header is not None:
f.write(_comment(header))
f.write("\n")
# Build and write configuration
conf_strings = []
_make_block_conf(self.top_block, conf_strings.append)
f.write("\n".join(conf_strings))
f.write("\n")
def eval(self, s):
"""Returns the value of the expression 's' -- where 's' is represented
as a string -- in the context of the configuration. Raises
Kconfig_Syntax_Error if syntax errors are detected in 's'.
For example, if FOO and BAR are tristate symbols at least one of which
has the value "y", then config.eval("y && (FOO || BAR)") => "y"
This function always yields a tristate value. To get the value of
non-bool, non-tristate symbols, use Symbol.get_value().
The result of this function is consistent with how evaluation works for
conditional expressions in the configuration as well as in the C
implementation. "m" and m are rewritten as '"m" && MODULES' and 'm &&
MODULES', respectively, and a result of "m" will get promoted to "y" if
we're running without modules.
Syntax checking is somewhat lax, partly to be compatible with lax
parsing in the C implementation."""
return self._eval_expr(self._parse_expr(self._tokenize(s, True), # Feed
None, # Current symbol/choice
s)) # line
def unset_user_values(self):
"""Resets the values of all symbols, as if Config.load_config() or
Symbol.set_user_value() had never been called."""
for sym in self.syms_iter():
sym._unset_user_value_no_recursive_invalidate()
def set_print_warnings(self, print_warnings):
"""Determines whether warnings related to this configuration (for
things like attempting to assign illegal values to symbols with
Symbol.set_user_value()) should be printed to stderr.
print_warnings: True if warnings should be printed."""
self.print_warnings = print_warnings
def set_print_undef_assign(self, print_undef_assign):
"""Determines whether informational messages related to assignments to
undefined symbols should be printed to stderr for this configuration.
print_undef_assign: If True, such messages will be printed."""
self.print_undef_assign = print_undef_assign
def __str__(self):
"""Returns a string containing various information about the Config."""
return _lines("Configuration",
"File : " +
self.filename,
"Base directory : " +
self.base_dir,
"Value of $ARCH at creation time : " +
("(not set)" if self.arch is None else self.arch),
"Value of $SRCARCH at creation time : " +
("(not set)" if self.srcarch is None else
self.srcarch),
"Source tree (derived from $srctree;",
"defaults to '.' if $srctree isn't set) : " +
self.srctree,
"Most recently loaded .config : " +
("(no .config loaded)"
if self.config_filename is None else
self.config_filename),
"Print warnings : " +
BOOL_STR[self.print_warnings],
"Print assignments to undefined symbols : " +
BOOL_STR[self.print_undef_assign])
#
# Private methods
#
#
# Kconfig parsing
#
def _parse_file(self, filename, parent, deps, visible_if_deps, res=None):
"""Parses the Kconfig file 'filename'. Returns a list with the Items in
the file. See _parse_block() for the meaning of the parameters."""
return self._parse_block(_FileFeed(filename), None, parent, deps,
visible_if_deps, res)
def _parse_block(self, line_feeder, end_marker, parent, deps,
visible_if_deps, res=None):
"""Parses a block, which is the contents of either a file or an if,
menu, or choice statement. Returns a list with the Items in the block.
line_feeder: A _FileFeed instance feeding lines from a file. The
Kconfig language is line-based in practice.
end_marker: The token that ends the block, e.g. T_ENDIF ("endif") for
ifs. None for files.
parent: The enclosing menu or choice, or None if we're at the top
level.
deps: Dependencies from enclosing menus, choices and ifs.
visible_if_deps (default: None): 'visible if' dependencies from
enclosing menus.
res (default: None): The list to add items to. If None, a new list is
created to hold the items."""
block = [] if res is None else res
while 1:
# Do we already have a tokenized line that we determined wasn't
# part of whatever we were parsing earlier? See comment in
# Config.__init__().
if self.end_line is not None:
line = self.end_line
tokens = self.end_line_tokens
tokens.unget_all()
self.end_line = None
self.end_line_tokens = None
else:
line = line_feeder.get_next()
if line is None:
if end_marker is not None:
raise Kconfig_Syntax_Error("Unexpected end of file {0}"
.format(line_feeder.filename))
return block
tokens = self._tokenize(line, False, line_feeder.filename,
line_feeder.linenr)
t0 = tokens.get_next()
if t0 is None:
continue
# Cases are ordered roughly by frequency, which speeds things up a
# bit
if t0 == T_CONFIG or t0 == T_MENUCONFIG:
# The tokenizer will automatically allocate a new Symbol object
# for any new names it encounters, so we don't need to worry
# about that here.
sym = tokens.get_next()
# Symbols defined in multiple places get the parent of their
# first definition. However, for symbols whose parents are
# choice statements, the choice statement takes precedence.
if not sym.is_defined_ or isinstance(parent, Choice):
sym.parent = parent
sym.is_defined_ = True
self.kconfig_syms.append(sym)
block.append(sym)
self._parse_properties(line_feeder, sym, deps, visible_if_deps)
elif t0 == T_SOURCE:
kconfig_file = tokens.get_next()
exp_kconfig_file = self._expand_sym_refs(kconfig_file)
f = os.path.join(self.base_dir, exp_kconfig_file)
if not os.path.exists(f):
raise IOError('{0}:{1}: sourced file "{2}" (expands to '
'"{3}") not found. Perhaps base_dir '
'(argument to Config.__init__(), currently '
'"{4}") is set to the wrong value.'
.format(line_feeder.filename,
line_feeder.linenr,
kconfig_file, exp_kconfig_file,
self.base_dir))
# Add items to the same block
self._parse_file(f, parent, deps, visible_if_deps, block)
elif t0 == end_marker:
# We have reached the end of the block
return block
elif t0 == T_IF:
# If statements are treated as syntactic sugar for adding
# dependencies to enclosed items and do not have an explicit
# object representation.
dep_expr = self._parse_expr(tokens, None, line,
line_feeder.filename,
line_feeder.linenr)
# Add items to the same block
self._parse_block(line_feeder, T_ENDIF, parent,
_make_and(dep_expr, deps),
visible_if_deps, block)
elif t0 == T_COMMENT:
comment = Comment()
comment.config = self
comment.parent = parent
comment.filename = line_feeder.filename
comment.linenr = line_feeder.linenr
comment.text = tokens.get_next()
self.comments.append(comment)
block.append(comment)
self._parse_properties(line_feeder, comment, deps,
visible_if_deps)
elif t0 == T_MENU:
menu = Menu()
menu.config = self
menu.parent = parent
menu.filename = line_feeder.filename
menu.linenr = line_feeder.linenr
menu.title = tokens.get_next()
self.menus.append(menu)
block.append(menu)
# Parse properties and contents
self._parse_properties(line_feeder, menu, deps,
visible_if_deps)
menu.block = self._parse_block(line_feeder, T_ENDMENU, menu,
menu.dep_expr,
_make_and(visible_if_deps,
menu.visible_if_expr))
elif t0 == T_CHOICE:
name = tokens.get_next()
if name is None:
choice = Choice()
self.choices.append(choice)
else:
# Named choice
choice = self.named_choices.get(name)
if choice is None:
choice = Choice()
choice.name = name
self.named_choices[name] = choice
self.choices.append(choice)
choice.config = self
choice.parent = parent
choice.def_locations.append((line_feeder.filename,
line_feeder.linenr))
# Parse properties and contents
self._parse_properties(line_feeder, choice, deps,
visible_if_deps)
choice.block = self._parse_block(line_feeder, T_ENDCHOICE,
choice, deps, visible_if_deps)
choice._determine_actual_symbols()
# If no type is specified for the choice, its type is that of
# the first choice item with a specified type
if choice.type == UNKNOWN:
for item in choice.actual_symbols:
if item.type != UNKNOWN:
choice.type = item.type
break
# Each choice item of UNKNOWN type gets the type of the choice
for item in choice.actual_symbols:
if item.type == UNKNOWN:
item.type = choice.type
block.append(choice)
elif t0 == T_MAINMENU:
text = tokens.get_next()
if self.mainmenu_text is not None:
self._warn("overriding 'mainmenu' text. "
'Old value: "{0}", new value: "{1}".'
.format(self.mainmenu_text, text),
line_feeder.filename, line_feeder.linenr)
self.mainmenu_text = text
else:
_parse_error(line, "unrecognized construct",
line_feeder.filename, line_feeder.linenr)
def _parse_properties(self, line_feeder, stmt, deps, visible_if_deps):
"""Parsing of properties for symbols, menus, choices, and comments.
Takes care of propagating dependencies from enclosing menus and ifs."""
def parse_val_and_cond(tokens, line, filename, linenr):
"""Parses '<expr1> if <expr2>' constructs, where the 'if' part is
optional. Returns a tuple containing the parsed expressions, with
None as the second element if the 'if' part is missing."""
return (self._parse_expr(tokens, stmt, line, filename, linenr,
False),
self._parse_expr(tokens, stmt, line, filename, linenr)
if tokens.check(T_IF) else None)
# In case the symbol is defined in multiple locations, we need to
# remember what prompts, defaults, and selects are new for this
# definition, as "depends on" should only apply to the local
# definition.
new_prompt = None
new_def_exprs = []
new_selects = []
# Dependencies from 'depends on' statements
depends_on_expr = None
while 1:
line = line_feeder.get_next()
if line is None:
break
filename = line_feeder.filename
linenr = line_feeder.linenr
tokens = self._tokenize(line, False, filename, linenr)
t0 = tokens.get_next()
if t0 is None:
continue
# Cases are ordered roughly by frequency, which speeds things up a
# bit
if t0 == T_DEPENDS:
if not tokens.check(T_ON):
_parse_error(line, 'expected "on" after "depends"',
filename, linenr)
parsed_deps = self._parse_expr(tokens, stmt, line, filename,
linenr)
if isinstance(stmt, (Menu, Comment)):
stmt.orig_deps = _make_and(stmt.orig_deps, parsed_deps)
else:
depends_on_expr = _make_and(depends_on_expr, parsed_deps)
elif t0 == T_HELP:
# Find first non-blank (not all-space) line and get its
# indentation
line = line_feeder.next_nonblank()
if line is None:
stmt.help = ""
break
indent = _indentation(line)
if indent == 0:
# If the first non-empty lines has zero indent, there is no
# help text
stmt.help = ""
line_feeder.unget()
break
# The help text goes on till the first non-empty line with less
# indent
help_lines = [_deindent(line, indent)]
while 1:
line = line_feeder.get_next()
if line is None or \
(not line.isspace() and _indentation(line) < indent):
stmt.help = "".join(help_lines)
break
help_lines.append(_deindent(line, indent))
if line is None:
break
line_feeder.unget()
elif t0 == T_SELECT:
target = tokens.get_next()
stmt.referenced_syms.add(target)
stmt.selected_syms.add(target)
new_selects.append(
(target,
self._parse_expr(tokens, stmt, line, filename, linenr)
if tokens.check(T_IF) else None))
elif t0 in (T_BOOL, T_TRISTATE, T_INT, T_HEX, T_STRING):
stmt.type = TOKEN_TO_TYPE[t0]
if tokens.peek_next() is not None:
new_prompt = parse_val_and_cond(tokens, line, filename,
linenr)
elif t0 == T_DEFAULT:
new_def_exprs.append(parse_val_and_cond(tokens, line, filename,
linenr))
elif t0 == T_DEF_BOOL:
stmt.type = BOOL
if tokens.peek_next() is not None:
new_def_exprs.append(parse_val_and_cond(tokens, line,
filename, linenr))
elif t0 == T_PROMPT:
# 'prompt' properties override each other within a single
# definition of a symbol, but additional prompts can be added
# by defining the symbol multiple times; hence 'new_prompt'
# instead of 'prompt'.
new_prompt = parse_val_and_cond(tokens, line, filename, linenr)
elif t0 == T_RANGE:
low = tokens.get_next()
high = tokens.get_next()
stmt.referenced_syms.add(low)
stmt.referenced_syms.add(high)
stmt.ranges.append(
(low, high,
self._parse_expr(tokens, stmt, line, filename, linenr)
if tokens.check(T_IF) else None))
elif t0 == T_DEF_TRISTATE:
stmt.type = TRISTATE
if tokens.peek_next() is not None:
new_def_exprs.append(parse_val_and_cond(tokens, line,
filename, linenr))
elif t0 == T_OPTION:
if tokens.check(T_ENV) and tokens.check(T_EQUAL):
env_var = tokens.get_next()
stmt.is_special_ = True
stmt.is_from_env = True
if env_var not in os.environ:
self._warn("The symbol {0} references the "
"non-existent environment variable {1} and "
"will get the empty string as its value. "
"If you're using Kconfiglib via "
"'make (i)scriptconfig', it should have "
"set up the environment correctly for you. "
"If you still got this message, that "
"might be an error, and you should email "
"ulfalizer a.t Google's email service."""
.format(stmt.name, env_var),
filename, linenr)
stmt.cached_val = ""
else:
stmt.cached_val = os.environ[env_var]
elif tokens.check(T_DEFCONFIG_LIST):
self.defconfig_sym = stmt
elif tokens.check(T_MODULES):
# To reduce warning spam, only warn if 'option modules' is
# set on some symbol that isn't MODULES, which should be
# safe. I haven't run into any projects that make use
# modules besides the kernel yet, and there it's likely to
# keep being called "MODULES".
if stmt.name != "MODULES":
self._warn("the 'modules' option is not supported. "
"Let me know if this is a problem for you; "
"it shouldn't be that hard to implement. "
"(Note that modules are still supported -- "
"Kconfiglib just assumes the symbol name "
"MODULES, like older versions of the C "
"implementation did when 'option modules' "
"wasn't used.)",
filename, linenr)
elif tokens.check(T_ALLNOCONFIG_Y):
if not isinstance(stmt, Symbol):
_parse_error(line,
"the 'allnoconfig_y' option is only "
"valid for symbols",
filename, linenr)
stmt.allnoconfig_y = True
else:
_parse_error(line, "unrecognized option", filename, linenr)