-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calltree-perl.pl
executable file
·345 lines (283 loc) · 8.93 KB
/
Calltree-perl.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/perl
########## Copyright ##########
# Copyright (C) 2008, NCSA. All rights reserved
#
# Developed by:
# National Center for Supercomputing Applications
# University of Illinois at Urbana/Champaign
# http://www.ncsa.uiuc.edu
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# with the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimers.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimers in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the names of National Center for Supercomputing Applications,
# University of Illinois at Urbana/Champaign, nor the names of its
# contributors may be used to endorse or promote products derived from
# this Software without specific prior written permission.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
# THE SOFTWARE.
#
# http://www.otm.uiuc.edu/node/396
########## Declarations ##########
## Includes ##
use strict;
use GraphViz;
use PPI;
use PPI::Dumper;
use Getopt::Long;
use File::Basename;
use Digest::SHA1 qw(sha1 sha1_hex sha1_base64);
## "Constants" ##
# Colors of the rainbow (ROYGBIV), adjusted so that they contrast with a white
# background.
my @fgcolors = (
'Maroon',
'Firebrick',
'Red',
'SaddleBrown',
'Orange',
'DarkGoldenrod',
'DarkGreen',
'SeaGreen',
'MidnightBlue',
'CornflowerBlue',
'Indigo',
'Violet');
## Command-Line Parameters ##
my $INFILE = undef;
my $OUTFILE = undef;
my $DEBUG = undef;
## Globals ##
my %functions;
########## Functions ##########
sub usage {
print <<EOF;
usage:
$0 -i <inputfile.pl> -o <outfile> [-debug]
<outfile> is the image file to be written. The format is selected
based on the extension of the filename. The supported types
are: .png, .bmp, .cmapx, .imap, .svg, .vrml, .gv, and .txt.
EOF
}
sub bangline {
my $file = shift;
my $bangline;
open BANGLINE, "<$file";
$bangline = <BANGLINE>;
close BANGLINE;
chomp($bangline);
return $bangline;
}
sub wcl {
my $file = shift;
my $linecount = 0;
open WCL, "<$file";
while (<WCL>) { $linecount++; };
close WCL;
return $linecount;
}
sub graphviz_escape {
my $s = shift;
$s =~ s/[\\]/\\\\/g;
$s =~ s/[\"]/\\\"/g;
$s =~ s/[\.]/\\\./g;
return $s;
}
sub elipsis {
my $elipsis = shift;
# Extract the first line from the string we were given
my @lines = split(/\n/, $elipsis);
chomp($lines[0]);
$elipsis = $lines[0];
# Truncate the string:
$elipsis = substr($elipsis, 0, 30);
# Add an elipsis, if anything was removed.
if ( ($#lines > 1) or (length($lines[0]) > length($elipsis)) ) {
$elipsis .= "...";
}
# Done!
return $elipsis;
}
sub calledfrom {
### Pre-Work ###
my $n = shift;
my $word = sprintf("%s", $n);
### Analyze ###
# Walk up the prase tree, until we find solid ground
while ( (not $n->isa('PPI::Document') ) and (not $n->isa('PPI::Statement::Sub')) ) {
$n = $n->parent;
}
### Interpret the results ###
if ( $n->isa('PPI::Document') ) {
# Did we fall through to the root of the document?
# If so, this must have been called from Main.
return "MAIN";
}
elsif ( defined($n->name) and ($n->name ne $word) ) {
# FIXME
return $n->name;
}
else {
# FIXME
return undef;
}
}
########## Main ##########
### Parse the command-line ###
# Read the command-line arguments
GetOptions(
'i=s' => \$INFILE,
'o=s' => \$OUTFILE,
'debug' => \$DEBUG,
'help' => sub { usage() ;}
) or usage();
# Are missing any critical arguments?
if ((not defined $INFILE) or (not defined $OUTFILE)) {
# If critical arguments are missing, quit and display help.
usage();
exit(1);
}
### Parse the Perl input-file ###
# Do the actual parsing
my $Document = PPI::Document->new($INFILE, readonly=>1) or die ("Parser could not read \"$INFILE\"\n");
$Document->index_locations();
# Generate debug output
if (defined $DEBUG) {
my $Dumper = PPI::Dumper->new($Document);
print "--- Begin $INFILE PPI Dump ---\n";
$Dumper->print;
print "--- End $INFILE PPI Dump ---\n\n";
}
### Create the graph data-structure ###
# Generate debug output
if (defined $DEBUG) { print "--- Begin Nodelist ---\n" }
# Create the data-structure
my $g = GraphViz->new(
layout=>'dot',
directed=>1,
overlap=>'orthoyx',
rankdir=>'RL',
concentrate=>1);
# Add the node for $INFILE's Main
my $label = graphviz_escape($INFILE . "\n" . bangline($INFILE) . "\nMAIN\n" . wcl($INFILE) . " lines");
$g -> add_node(
"MAIN",
label=>$label,
shape=>'box',
style=>'bold');
if (defined $DEBUG) { print "MAIN Block: label=>\"$label\"\n"; }
## Read Nodes ##
# Find subroutines and add them to the graph
my $nodes = $Document->find( sub { $_[1]->isa('PPI::Statement::Sub') and $_[1]->name });
foreach (@$nodes) {
## Pre-Work ##
# Retrieve the line-number of the sub declaration:
my $linenumber = $_->location()->[0];
# Record the name of the function we've just seen, so that we can look
# for calls to it:
$functions{$_->name} = 1;
# Pick a color for this node in a deterministic fashion. The
# color-value is derived from the function name. The destination-node
# and all edges leading to it will be the same color:
my $myfgcolor = $fgcolors[unpack("N", sha1($_->name)) % ($#fgcolors+1)];
## Note the edges ##
if (not $_->isa('PPI::Statement::Scheduled')) {
# Debug output
if (defined $DEBUG) { print "Subroutine: ".$_->name."\n"; }
# This node is a regular subroutine
$g->add_node(
$_->name,
label=>graphviz_escape($linenumber.': sub '.$_->name.'{}'),
color=>$myfgcolor,
fontcolor=>$myfgcolor);
}
else {
# Debug output
if (defined $DEBUG) { print "Scheduled Block: ".$_->name."\n"; }
# This node is a BEGIN{}, END{}, or other "scheduled" block
$g->add_node(
$_->name,
label=>graphviz_escape($linenumber.': '.$_->name.'{}'),
shape=>'box',
color=>$myfgcolor,
fontcolor=>$myfgcolor);
$g->add_edge(
"MAIN",
$_->name,
label=>graphviz_escape($linenumber.": Scheduled Block"),
color=>$myfgcolor,
fontcolor=>$myfgcolor);
}
}
if (defined $DEBUG) { print "--- End Nodelist ---\n\n" }
## Edges ##
# Add the edges (calls) from main to the graph
if (defined $DEBUG) { print "--- Begin Edgelist ---\n" }
my $calls = $Document->find( sub { $_[1]->parent->isa('PPI::Statement') and ($_[1]->isa('PPI::Token::Word') or $_[1]->isa('PPI::Token::Symbol') ); }
);
foreach (@$calls) {
# Pre-Work
my $linenumber = $_->location()->[0];
my $bareword=sprintf("%s", $_);
$bareword =~ s/^\&//;
# Is this a Word we're interested in?
if ( not defined $functions{$bareword} ){
# If not, skip it!
next;
}
# See where the word resides in the program-structure, if possible.
my $calledfrom = calledfrom($_);
if (defined $calledfrom) {
# Debug output
if (defined $DEBUG) { print "CAll: ".$calledfrom."->".$bareword."\n"; }
# Color: Pick a color for this edge in a deterministic fashion.
# The color-values is derived from the destination name. The
# destination-node and all edges leading to it will be the same
# color. Without further ado:
my $myfgcolor = $fgcolors[unpack("N", sha1($bareword)) % ($#fgcolors+1)];
# Add the edge to the graph
$g -> add_edge(
$calledfrom,
$bareword,
label=>graphviz_escape("$linenumber: ".elipsis($_->parent->content)),
color=>$myfgcolor,
fontcolor=>$myfgcolor);
}
}
if (defined $DEBUG) { print "--- End Edgelist ---\n\n" }
### Write the graph ###
# In case of debug, dump to stdout
if (defined $DEBUG) {
print "--- Begin Graph Specification ---\n";
print $g->as_debug;
print "--- End Graph Specification ---\n";
}
# Write the image
open(GRAPH, ">$OUTFILE") or die ("Could not create $OUTFILE\n");
if ($OUTFILE =~ /\.png$/) { print GRAPH $g->as_png }
elsif ($OUTFILE =~ /\.bmp$/) { print GRAPH $g->as_wmbp }
elsif ($OUTFILE =~ /\.cmapx$/) { print GRAPH $g->as_cmapx }
elsif ($OUTFILE =~ /\.imap$/) { print GRAPH $g->as_imap }
elsif ($OUTFILE =~ /\.svg$/) { print GRAPH $g->as_svg }
elsif ($OUTFILE =~ /\.vrml$/) { print GRAPH $g->as_vrml }
elsif ($OUTFILE =~ /\.gv$/) { print GRAPH $g->as_debug }
elsif ($OUTFILE =~ /\.txt$/) { print GRAPH $g->as_plain }
else { die("Don't know how to generate $OUTFILE -- unknown extension\n") }
close(GRAPH);