]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unifdef/ifdef-how.pl
Add 'contrib/unifdef/' from commit '0da44885831dc0a43c4ca6ff04a2430993cc0a80'
[FreeBSD/FreeBSD.git] / contrib / unifdef / ifdef-how.pl
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 if (@ARGV != 2) {
7         die <<END;
8 usage: ifdef-how <file> <line>
9
10 Print the sequence of preprocessor conditionals which lead to the
11 given line being retained after preprocessing. There is no output
12 if the line is always retained. Conditionals that must be true are
13 printed verbatim; conditionals that musy be false have their
14 preprocessor keyword prefixed with NOT.
15
16 Warning: this program does not parse comments or strings, so it will
17 not handle tricky code correctly.
18 END
19 }
20
21 my $file = shift;
22 my $line = shift;
23
24 open my $fh, '<', $file
25     or die "ifdef-how: open $file: $!\n";
26
27 my @stack;
28 while (<$fh>) {
29         last if $. == $line;
30         if (m{^\s*#\s*(if|ifdef|ifndef)\b}) {
31                 push @stack, $_;
32         }
33         if (m{^\s*#\s*(elif|else)\b}) {
34                 $stack[-1] =~ s{^(\s*#\s*)(?!NOT)\b}{${1}NOT}gm;
35                 $stack[-1] .= $_;
36         }
37         if (m{^\s*#\s*endif\b}) {
38                 pop @stack;
39         }
40 }
41
42 print @stack;