Regular expressions are not parsers. It's always better to use a parser if you can.
A simple approach is to lean on the parser in 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";
}
Sample run:
$ ./getfuncs prog.cc
AccounntBalance
AccountRetrivalForm
Another approach involves g++'s option -fdump-translation-unit
that causes it to dump a representation of the parse tree, and you could dig through it as in the following example.
We begin with the usual front matter:
#! /usr/bin/perl
use warnings;
use strict;
Processing requires the name of the source file and any necessary compiler flags.
sub usage { "Usage: $0 source-file [ cflags ]\n" }
The translation-unit dump has a straightforward format:
@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
As you can see, each record begins with an identifier, followed by a type, and then one or more attributes. Regular expressions and a bit of hash twiddling are sufficient to give us a tree to inspect.
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;
}
In the main program, we feed the code to 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";
}
Assuming all went well, we then pluck out the function definitions given in the specified source file.
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;
Example run:
$ ./getfuncs prog.cc -I.
AccounntBalance
AccountRetrivalForm