有的项目组为了逃避变态的代码规范对CC圈复杂度的限制,定义了IF_NULL_RETURN_X() IF_ERR_RETURN()这样的宏,被发现后勒令不许使用,问我能不能写个脚本把那些宏展开(NND干嘛那么怕那些变态规范啊,看,现在又得改回去了吧),想了想用shell好像不是很容易,不是个把钟头就能写出来的,手上也有其他事情,就没应下来
今天放假,想起这件事情,来了兴趣,好好想了想觉得应该用perl,翻出小骆驼,倒腾了一下午,,
用法:
将希望展开的宏函数的定义,拷贝到当前目录下的macro.txt文件中
然后运行./macro_expasion.pl
就会把指定文件/目录中.c文件里的相应的宏函数展开
#!/usr/bin/perl
use File::Find;
use File::Copy;
if (@ARGV <= 0) {
print "Usage:\n";
print "\t$0 \n";
exit;
}
my $macro_file = "macro.txt";
if (! -f $macro_file) {
print "$macro_file is not exist!\n";
exit;
}
my %macro = &read_macro_file($macro_file);
while (my($proto, $body) = each %macro) {
print("<$proto>\n");
print("\t/$body/\n");
}
print "--------------------------------------------------------------------------------\n";
my @files;
my $extention = ".bak";
my @dirs = @ARGV;
for (@dirs) {
print "$_: no such file or directory!\n" if (! -e);
}
find(sub { push(@files, $File::Find::name) if /\.c$/ && !/\.bak$/}, @dirs);
for (@files) {
my $file = $_;
my $bakfile = $file . $extention;
print $file . "\n";
copy $file, $bakfile or die "Copy failed: $!";
open FO, $bakfile or die "Cannot open '$bakfile': $!";
open FN, ">$file" or die "Cannot open '$file': $!";
my @protos = keys %macro;
while (my $line = ) {
my $is_macro_want_to_;
$is_macro_want_to_ = 0;
my ($proto, $body);
foreach $proto (@protos) {
if ($line =~ /\b$proto ?\(/) {
my ($tmp_args) = ($line =~ /\((.*)\)/);
my @args = split /[, ]+/, $tmp_args;
my ($indent) = ($line =~ /^([ \t]+)/);
$body = $macro{$proto};
my ($tmp_pargs) = ($body =~ /^\((.*)\)-_-/);
my @pargs = split /[, ]+/, $tmp_pargs;
$body =~ s/^\(.*\)-_-//;
$body =~ s/#NL/\n$indent/g;
for (my $i = 0; $i < @args; $i++) {
$body =~ s/\b$pargs[$i]\b/$args[$i]/g;
}
print FN "$indent$body\n"
or die "write '$file' err: $!";
$is_macro_want_to_ = 1;
last;
}
}
if (! $is_macro_want_to_) {
print FN $line or die "write '$file' err: $!";
}
}
close FN;
close FO;
#unlink $bakfile;
}
sub read_macro_file($) {
my %macro;
my ($proto, $body);
my $macro_file = $_[0];
open MACRO_FILE, $macro_file or die "Cannot open '$macro_file': $!";
while () {
chomp;
next if (/^ *$/);
if (/^#define/) {
($proto, $body) =
m/ *#define +([a-zA-Z_][a-zA-Z0-9_]*) *(\(.*\))/;
$macro{$proto} = $body . "-_-";
} else {
s/ *\\$/#NL/;
$macro{$proto} .= $_;
}
}
close MACRO_FILE;
return %macro;
}
|
文件: | macro_expand.zip |
大小: | 3KB |
下载: | 下载 |
|
阅读(1450) | 评论(0) | 转发(0) |