freebsd-src/contrib/unifdef/ifdef-how.pl
Dag-Erling Smørgrav cf1b93786f Add 'contrib/unifdef/' from commit '0da44885831dc0a43c4ca6ff04a2430993cc0a80'
git-subtree-dir: contrib/unifdef
git-subtree-mainline: 3b7ffacdee
git-subtree-split: 0da4488583
(cherry picked from commit fb3ef04d20)

unifdef: Reapply our 61287be181.

(cherry picked from commit 343b776fd0)

unifdef: Reapply our 7102ec5226.

(cherry picked from commit 049b7608f4)
2023-09-07 10:59:35 +02:00

43 lines
899 B
Perl
Executable file

#!/usr/bin/perl
use warnings;
use strict;
if (@ARGV != 2) {
die <<END;
usage: ifdef-how <file> <line>
Print the sequence of preprocessor conditionals which lead to the
given line being retained after preprocessing. There is no output
if the line is always retained. Conditionals that must be true are
printed verbatim; conditionals that musy be false have their
preprocessor keyword prefixed with NOT.
Warning: this program does not parse comments or strings, so it will
not handle tricky code correctly.
END
}
my $file = shift;
my $line = shift;
open my $fh, '<', $file
or die "ifdef-how: open $file: $!\n";
my @stack;
while (<$fh>) {
last if $. == $line;
if (m{^\s*#\s*(if|ifdef|ifndef)\b}) {
push @stack, $_;
}
if (m{^\s*#\s*(elif|else)\b}) {
$stack[-1] =~ s{^(\s*#\s*)(?!NOT)\b}{${1}NOT}gm;
$stack[-1] .= $_;
}
if (m{^\s*#\s*endif\b}) {
pop @stack;
}
}
print @stack;