正则表达式是不解析器。如果可以的话,最好使用解析器。
一个简单的办法是在解析器倾身ctags:
#! /usr/bin/perl
use warnings;
use strict;
sub usage { "Usage: $0 source-file\n" }
die usage unless @ARGV == 1;
open my $ctags, "-|", "ctags", "-f", "-", @ARGV
or die "$0: failed to start ctags\n";
while (<$ctags>) {
chomp;
my @fields = split /\t/;
next unless $fields[-1] eq "f";
print $fields[0], "\n";
}
采样运行:
$ ./getfuncs prog.cc
AccounntBalance
AccountRetrivalForm
另一种方法涉及G ++的选项-fdump-translation-unit
,导致它倾倒分析树的表示,你可以像下面的例子那样挖掘它。
我们开始与平常前面的问题:
#! /usr/bin/perl
use warnings;
use strict;
处理需要的源文件和任何必需的编译标记的名称。
sub usage { "Usage: $0 source-file [ cflags ]\n" }
翻译单元转储具有简单的格式:
@1 namespace_decl name: @2 srcp: :0
dcls: @3
@2 identifier_node strg: :: lngt: 2
@3 function_decl name: @4 mngl: @5 type: @6
srcp: prog.c:12 chan: @7
args: @8 link: extern
@4 identifier_node strg: AccountRetrivalForm lngt: 19
正如你可以看到,每一个记录开始的标识符,后跟一个类型,然后一个或多个属性。正则表达式和一些哈希转换足以给我们一棵树来检查。
sub read_tu {
my($path) = @_;
my %node;
open my $fh, "<", $path or die "$0: open $path: $!";
my $tu = do { local $/; <$fh> };
my $attrname = qr/\b\w+(?=:)/;
my $attr =
qr/($attrname): \s+ (.+?) # name-value
(?= \s+ $attrname | \s*$) # terminated by whitespace or EOL
/xm;
my $fullnode =
qr/^(@\d+) \s+ (\S+) \s+ # id and type
((?: $attr \s*)+) # one or more attributes
\s*$ # consume entire line
/xm;
while ($tu =~ /$fullnode/g) {
my($id,$type,$attrs) = ($1,$2,$3);
$node{$id} = { TYPE => $type };
while ($attrs =~ /$attr \s*/gx) {
if (exists $node{$id}{$1}) {
$node{$id}{$1} = [ $node{$id}{$1} ] unless ref $node{$id}{$1};
push @{ $node{$id}{$1} } => $2;
}
else {
$node{$id}{$1} = $2;
}
}
}
wantarray ? %node : \%node;
}
在主程序中,我们喂代码至g ++
die usage unless @ARGV >= 1;
my($src,@cflags) = @ARGV;
system("g++", "-c", "-fdump-translation-unit", @cflags, $src) == 0
or die "$0: g++ failed\n";
my @tu = glob "$src.*.tu";
unless (@tu == 1) {
die "$0: expected one $src.*.tu file, but found",
@tu ? ("\n", map(" - $_\n", @tu))
: " none\n";
}
假设一切顺利,那么我们挖出指定的源文件中给出的函数定义。
my $node = read_tu @tu;
sub isfunc {
my($n) = @_;
$n->{TYPE} eq "function_decl"
&&
index($n->{srcp}, "$src:") == 0;
}
sub nameof {
my($n) = @_;
return "<undefined>" unless exists $n->{name};
$n->{name} =~ /^@/
? $node->{ $n->{name} }{strg}
: $n->{name};
}
print "$_\n" for sort
map nameof($_),
grep isfunc($_),
values %$node;
运行示例:
$ ./getfuncs prog.cc -I.
AccounntBalance
AccountRetrivalForm
究竟是你想搭配什么?以(int64)或(void)或(boolean)开头的函数? – GorillaPatch 2010-08-10 13:27:31
@gorillaPatch 我尝试匹配所有可能以int64开头的函数或void或布尔值(这是唯一的三个可能性) – Sreeja 2010-08-10 13:29:59
我很好奇,什么语言是“dis”? – Ether 2010-08-10 15:07:18