3 # Selectively preprocess #ifdef / #ifndef statements.
5 # ifdef [-Dname] ... [-Uname] ... [file] ...
7 # This scans the file(s), looking for #ifdef and #ifndef preprocessor
8 # commands that test for one of the names mentioned in the -D and -U
9 # options. On standard output it writes a copy of the input file(s)
10 # minus those code sections that are suppressed by the selected
11 # combination of defined/undefined symbols. The #if(n)def/#else/#else
12 # lines themselfs (if the #if(n)def tests for one of the mentioned
13 # names) are removed as well.
15 # Features: Arbitrary nesting of recognized and unrecognized
16 # preprocesor statements works correctly. Unrecognized #if* commands
17 # are left in place, so it will never remove too much, only too
18 # little. It does accept whitespace around the '#' character.
20 # Restrictions: There should be no comments or other symbols on the
21 # #if(n)def lines. The effect of #define/#undef commands in the input
22 # file or in included files is not taken into account. Tests using
23 # #if and the defined() pseudo function are not recognized. The #elif
24 # command is not recognized. Improperly nesting is not detected.
25 # Lines that look like preprocessor commands but which are actually
26 # part of comments or string literals will be mistaken for
27 # preprocessor commands.
38 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'D:U:')
48 process(sys
.stdin
, sys
.stdout
)
51 process(f
, sys
.stdout
)
54 def process(fpi
, fpo
):
55 keywords
= ('if', 'ifdef', 'ifndef', 'else', 'endif')
61 while line
[-2:] == '\\\n':
62 nextline
= fpi
.readline()
63 if not nextline
: break
64 line
= line
+ nextline
65 tmp
= string
.strip(line
)
67 if ok
: fpo
.write(line
)
69 tmp
= string
.strip(tmp
[1:])
70 words
= string
.split(tmp
)
72 if keyword
not in keywords
:
73 if ok
: fpo
.write(line
)
75 if keyword
in ('ifdef', 'ifndef') and len(words
) == 2:
76 if keyword
== 'ifdef':
82 stack
.append((ok
, ko
, word
))
85 stack
.append((ok
, not ko
, word
))
88 stack
.append((ok
, -1, word
))
89 if ok
: fpo
.write(line
)
91 stack
.append((ok
, -1, ''))
92 if ok
: fpo
.write(line
)
93 elif keyword
== 'else' and stack
:
94 s_ok
, s_ko
, s_word
= stack
[-1]
96 if ok
: fpo
.write(line
)
101 stack
[-1] = s_ok
, s_ko
, s_word
102 elif keyword
== 'endif' and stack
:
103 s_ok
, s_ko
, s_word
= stack
[-1]
105 if ok
: fpo
.write(line
)
109 sys
.stderr
.write('Unknown keyword %s\n' % keyword
)
111 sys
.stderr
.write('stack: %s\n' % stack
)