-
Notifications
You must be signed in to change notification settings - Fork 84
/
java_calltree.pl
executable file
·1860 lines (1636 loc) · 54.6 KB
/
java_calltree.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
#
# Copyright (c) 2020 Ran Panfeng. All rights reserved.
# Author: satanson
# Email: ranpanf@gmail.com
# Github repository: https://github.com/satanson/cpp_etudes.git
# Usage: show function call hierarchy of java project in the style of Linux utility tree.
#
# Format:
# ./java_calltree.pl <keyword|regex> <filter> <direction(Global_called(1)|Global_calling)> <verbose(0|1)> <depth(num)>
#
# - keyword for exact match, regex for fuzzy match;
# - subtrees whose leaf nodes does not match filter are pruned, default value is '' means match all;
# - direction: 1, in default, show functions Global_called by other functions in callees' perspective; otherwise, show function Global_calling relation in callers' perspective;
# - verbose=0, no file locations output; otherwise succinctly output;
# - depth=num, print max derivation depth.
#
# Examples:
#
# # show all functions (set depth=1 preventing output from overwhelming).
# ./java_calltree.pl '\w+' '' 1 1 1
#
# # show functions Global_calling fdatasync in a backtrace way with depth 3;
# ./java_calltree.pl 'fdatasync' '' 1 1 3
#
# # show functions Global_calling sync_file_range in a backtrace way with depth 3;
# ./java_calltree.pl 'sync_file_range' '' 1 1 3
#
# # show functions Global_calling fsync in a backtrace way with depth 4;
# /java_calltree.pl 'fsync' '' 1 1 4
#
use warnings;
use strict;
use Data::Dumper;
use List::Util qw/max/;
use Storable qw/freeze thaw nstore retrieve/;
sub red_color($) {
my ($msg) = @_;
"\e[95;31;1m$msg\e[m"
}
sub any(&;@) {
my ($pred, @values) = @_;
my $n = () = grep {$_} map {$pred->($_)} @values;
$n > 0;
}
sub all(&;@) {
my ($pred, @values) = @_;
!(any {!$pred->($_)} @values);
}
package RAII {
sub new {
my ($cls, $ref, $unref) = @_;
$ref->();
my $obj = {
unref => $unref,
};
return bless $obj, $cls;
}
sub DESTROY {
local ($., $!, $?, $@, $^E);
my ($obj) = @_;
$obj->{unref}();
}
}
my $Global_isatty = -t STDOUT;
use Cwd qw/abs_path/;
sub get_path_of_script() {
if ($0 !~ qr'/') {
my ($path) = map {chomp;
$_} qx(which $0 2>/dev/null);
return $path;
}
else {
return abs_path($0);
}
}
sub file_newer_than($$) {
my ($file_a, $file_b) = @_;
return 0 unless ((-f $file_a) && (-f $file_b));
return (-M $file_a) < (-M $file_b);
}
sub file_newer_than_script($) {
# return !undef;
file_newer_than(+shift, get_path_of_script());
}
sub get_cached_or_run(&$$;@) {
my ($func, $validate_func, $cached_file, @args) = @_;
if (file_newer_than_script($cached_file)) {
my $result = retrieve($cached_file);
if (defined($result) && ref($result) eq ref([]) && $validate_func->(@$result)) {
return @$result;
}
}
my @result = $func->(@args);
nstore [ @result ], $cached_file;
return @result;
}
sub get_cache_or_run_keyed(\@$$;@) {
my ($key, $file, $func, @args) = @_;
die "Invalid data" unless defined($key) && ref($key) eq ref([]);
die "Invalid func" unless defined($func);
my @key = @$key;
my $expect_key = join "\0", @key;
my $check_key = sub(\%) {
my $data = shift;
return exists $data->{cached_key} && $data->{cached_key} eq $expect_key;
};
my ($data) = get_cached_or_run {
+{ cached_key => $expect_key, cached_data => [ $func->(@args) ] }
} $check_key, $file;
return @{$data->{cached_data}};
}
sub ensure_ag_installed() {
my ($ag_path) = map {chomp;
$_} qx(which ag 2>/dev/null);
if (!defined($ag_path) || (!-e $ag_path)) {
printf STDERR "ag is missing, please install ag at first, refer to https://github.com/ggreer/the_silver_searcher;
the fork https://github.com/satanson/the_silver_searcher provides a --multiline-break options will generate exact
result because the modified ag insert break(--) between two function definitions that are not separated by blank
lines.";
exit 1;
}
}
sub multiline_break_enabled() {
my ($enabled) = map {chomp;
$_} qx(echo enabled|ag --multiline-break enabled 2>/dev/null);
return defined($enabled) && $enabled eq "enabled";
}
sub ensure_safe() {
my ($cwd, $home) = @ENV{qw/PWD HOME/};
my @supported_os = qw/Linux Darwin/;
my %supported_os = map {$_ => 1} @supported_os;
my ($os) = map {
if (defined($_)) {
chomp;
$_
}
else {"UNKNOWN"}
} qx'uname -s 2>/dev/null';
my $supported_os = join "|", @supported_os;
die "Platform '$os' is not supported, run java_calltree.pl in [$supported_os]" unless exists $supported_os{$os};
die "Undefined cwd or home" unless defined($cwd) && defined($home);
die "Never run java_calltree.pl in HOME directory: '$home'" if $cwd eq $home;
die "Never run java_calltree.pl in root directory: '$cwd'" if $cwd eq '/';
my @comp = split qr'/+', $cwd;
die "Never run java_calltree.pl in a directory whose depth <= 2" if scalar(@comp) <= 3;
}
ensure_safe;
ensure_ag_installed;
my $ignore_pattern = join "", map {" --ignore '$_' "}
qw(*test* *benchmark* *CMakeFiles* *contrib/* *third_party/*
*thirdparty/* *3rd-[pP]arty/* *3rd[pP]arty/* *deps/*);
my $java_filename_pattern = qq/'\\.java\$'/;
my $RE_IDENTIFIER = "\\b[A-Za-z_]\\w*\\b";
my $RE_WS = "(?:\\s)";
my $RE_TWO_COLON = "(?::{2})";
my $RE_SCOPED_IDENTIFIER = "(?:$RE_TWO_COLON $RE_WS*)? (?: $RE_IDENTIFIER $RE_WS* $RE_TWO_COLON $RE_WS*)* [~]?$RE_IDENTIFIER" =~ s/ //gr;
sub gen_nested_pair_re($$$) {
my ($L, $R, $others) = @_;
my $simple_case = "$others $L $others $R $others";
my $recursive_case = "$others $L(?-1)*$R $others";
my $nested = "($recursive_case|$simple_case)";
return "(?:$L $others $nested* $others $R)" =~ s/\s+//gr;
}
my $RE_NESTED_PARENTHESES = gen_nested_pair_re("\\(", "\\)", "[^()]*");
my $RE_NESTED_BRACES = gen_nested_pair_re("{", "}", "[^{}]*");
sub gen_re_list($$$) {
my ($re_delimiter, $re_item, $optional) = @_;
my $re = "(?: $re_item (?: $RE_WS* $re_delimiter $RE_WS* $re_item)*? ) $optional";
return $re =~ s/ //gr;
}
sub gen_re_initializer_list_of_ctor() {
my $re_csv = gen_re_list(",", "(?:[^,]+?)", "??");
my $initializer = "(?: $RE_IDENTIFIER $RE_WS* (?: (?: \\( $RE_WS* $re_csv $RE_WS* \\) ) | (?: \\{ $RE_WS* $re_csv $RE_WS* \\} ) ) )";
my $re_csv_initializer = gen_re_list(",", "(?: $initializer )", "");
my $initializer_list = "(?: (?<=\\) ) $RE_WS* : $RE_WS* $re_csv_initializer $RE_WS* (?={) )";
return $initializer_list =~ s/ //gr;
}
my $RE_INITIALIZER_LIST = gen_re_initializer_list_of_ctor();
sub gen_re_overload_operator() {
my $operators = "[-+*/%^&|~!=<>]=?|(?:(?:<<|>>|\\|\\||&&)=?)|<=>|->\\*|->|\\(\\s*\\)|\\[\\s*\\]|\\+\\+|--|,";
my $re = "(?:operator \\s* (?:$operators)\\s*(?=\\())";
return $re =~ s/ //gr;
}
my $RE_OVERLOAD_OPERATOR = gen_re_overload_operator();
sub gen_re_func_def() {
my $re_func_def = "";
$re_func_def .= "^.*?($RE_SCOPED_IDENTIFIER|$RE_OVERLOAD_OPERATOR) $RE_WS* $RE_NESTED_PARENTHESES";
$re_func_def .= "(?:$RE_INITIALIZER_LIST)?";
$re_func_def .= "$RE_WS* $RE_NESTED_BRACES";
$re_func_def =~ s/ //g;
return $re_func_def;
}
sub gen_re_func_def_name() {
my $re_func_def = "";
$re_func_def .= "^.*?($RE_SCOPED_IDENTIFIER|$RE_OVERLOAD_OPERATOR) $RE_WS* $RE_NESTED_PARENTHESES";
$re_func_def =~ s/ //g;
return $re_func_def;
}
my $RE_FUNC_DEFINITION = gen_re_func_def;
my $RE_FUNC_DEFINITION_NAME = gen_re_func_def_name;
sub gen_re_func_call() {
my $cs_tokens = "$RE_WS* (?:(?: $RE_SCOPED_IDENTIFIER $RE_WS* , $RE_WS*)* $RE_SCOPED_IDENTIFIER $RE_WS*)?";
#my $re_func_call = "((?:($RE_SCOPED_IDENTIFIER) $RE_WS *(?:\\($cs_tokens\\))? $RE_WS* (?: \\. | -> | :: ) $RE_WS* )? ($RE_SCOPED_IDENTIFIER)) $RE_WS* [(]";
my $re_func_call = "((?:($RE_SCOPED_IDENTIFIER) $RE_WS (?: \\. | -> | :: ) $RE_WS* )? ($RE_SCOPED_IDENTIFIER)) $RE_WS* [(]";
return $re_func_call =~ s/ //gr;
}
my $RE_FUNC_CALL = gen_re_func_call;
sub gen_re_gcc_attribute() {
my $attr = "(?: $RE_IDENTIFIER (?: $RE_WS* \\([^()]+\\) )? )";
my $attr_list = "(?: $attr (?: $RE_WS* , $RE_WS* $attr $RE_WS*)*)";
my $gcc_attribute = "__attribute__ $RE_WS* \\( \\(? $RE_WS* $attr_list $RE_WS* \\)? \\)";
return $gcc_attribute =~ s/ //gr;
}
my $RE_GCC_ATTRIBUTE = gen_re_gcc_attribute();
sub read_content($) {
my $file_name = shift;
if (-f $file_name) {
open my $handle, "<", $file_name or die "Fail to open '$file_name' for reading: $!";
local $/;
my $content = <$handle>;
close $handle;
return $content;
}
return undef;
}
sub write_content($@) {
my ($file_name, @lines) = @_;
open my $handle, "+>", $file_name or die "Fail to open '$file_name' for writing: $!";
print $handle join("\n", @lines);
close $handle;
}
sub read_lines($) {
my $file_name = shift;
if (-f $file_name) {
open my $handle, "<", $file_name or die "Fail to open '$file_name' for reading: $!";
my @lines = <$handle>;
close $handle;
return \@lines;
}
return undef;
}
## preprocess source file
my $RE_QUOTED_STRING = qr/("([^"]*\\")*[^"]*")/;
my $RE_SINGLE_CHAR = qr/'[\\]?.'/;
my $RE_SLASH_STAR_COMMENT = qr"(/[*]([^/*]*(([*]+|[/]+)[^/*]+)*([*]+|[/]+)?)[*]/)";
my $RE_NESTED_CHARS_IN_SINGLE_QUOTES = qr/'[{}<>()]'/;
my $RE_SINGLE_LINE_COMMENT = qr'/[/\\].*';
my $RE_LEFT_ANGLES = qr'<[<=]+';
my $RE_TEMPLATE_ARGS_1LAYER = qr'((\.?)<\s*((((\w+[\.:]+)*\w+\s*,\s*)*(\w+[\.:]+)*\w+\s*)|\?)\s*>)';
my $RE_CSV_TOKEN = gen_re_list(",", $RE_SCOPED_IDENTIFIER, "??");
my $RE_NOEXCEPT_THROW = qr'(\bthrows\b\s*(((\w+[\.:]+)*\w+\s*,\s*)*(\w+[\.:]+)*\w+\s*)\s*)';
my $RE_MACRO_DEF = qr/(#define([^\n\r]*\\(\n\r?|\r\n?))*([^\n\r]*[^\n\r\\])?((\n\r?)|(\r\n?)|$))/;
sub empty_string_with_blank_lines($) {
q/""/ . (join "\n", map {""} split "\n", $_[0]);
}
sub blank_lines($) {
$_[0] =~ tr/\n\r//cdr;
}
sub replace_single_char($) {
$_[0] =~ s/$RE_SINGLE_CHAR/'x'/gr;
}
sub replace_quoted_string($) {
return $_[0] =~ s/$RE_QUOTED_STRING/&empty_string_with_blank_lines($1)/gemr;
}
sub replace_slash_star_comment($) {
$_[0] =~ s/$RE_SLASH_STAR_COMMENT/&blank_lines($1)/gemr;
}
sub replace_nested_char($) {
$_[0] =~ s/$RE_NESTED_CHARS_IN_SINGLE_QUOTES/'x'/gr;
}
sub replace_single_line_comment($) {
$_[0] =~ s/$RE_SINGLE_LINE_COMMENT//gr;
}
sub replace_left_angles($) {
$_[0] =~ s/$RE_LEFT_ANGLES/++/gr;
}
sub replace_lt($) {
$_[0] =~ s/\s+<\s+/ + /gr;
}
sub replace_whitespaces($) {
($_[0] =~ s/(?:^\s+)|(?:\s+$)//gr) =~ s/(?:(?<=\W)\s+)|(?:\s+(?=\W))/ /gr;
}
sub replace_template_args_1layer($) {
($_[0] =~ s/$RE_TEMPLATE_ARGS_1LAYER/&blank_lines($1)/gemr, $1);
}
my $RE_DECORATOR = qr/\@\w+(\([^()]+\))?/;
sub remove_decorator($) {
$_[0] =~ s/$RE_DECORATOR/ /gr;
}
sub repeat_apply($\&$) {
my ($times, $fun, $arg) = @_;
my ($result, $continue) = $fun->($arg);
if (defined($continue) && $times > 1) {
return &repeat_apply($times - 1, $fun, $result);
}
return $result;
}
sub remove_keywords_and_attributes($) {
$_[0] =~ s/(\b(volatile|const|final|override|public|private|protected|static|synchronized)\b)|\[\[\w+\]\]//gr;
}
sub remove_noexcept_and_throw($) {
$_[0] =~ s/$RE_NOEXCEPT_THROW/&blank_lines($1)/gemr;
}
sub replace_template_args_4layers($) {
repeat_apply(4, &replace_template_args_1layer, $_[0]);
}
#sub remove_gcc_attributes($) {
# $_[0] =~ s/$RE_GCC_ATTRIBUTE//gr;
#}
#
#sub replace_macro_defs($) {
# $_[0] =~ s/$RE_MACRO_DEF/&blank_lines($1)/gemr;
#}
sub preprocess_one_java_file($) {
my $file = shift;
return unless -f $file;
my $content = read_content($file);
return unless defined($content) && length($content) > 0;
$content = replace_quoted_string(replace_single_char(replace_slash_star_comment($content)));
$content = join qq/\n/, map {
replace_whitespaces(replace_lt(replace_left_angles(replace_nested_char(replace_single_line_comment($_)))))
} split qq/\n/, $content;
$content = remove_keywords_and_attributes($content);
#$content = remove_gcc_attributes($content);
$content = replace_template_args_4layers($content);
$content = remove_noexcept_and_throw($content);
$content = remove_decorator($content);
#$content = replace_macro_defs($content);
my $tmp_file = "$file.tmp.created_by_call_tree";
write_content($tmp_file, $content);
rename $tmp_file => $file;
}
sub get_all_java_files() {
return grep {
defined($_) && length($_) > 0 && (-f $_)
} map {
chomp;
$_
} qx(ag -U -G $java_filename_pattern $ignore_pattern -l);
}
sub group_files($@) {
my ($num_groups, @files) = @_;
my $num_files = scalar(@files);
die "Illegal num_groups($num_groups)" if $num_groups < 1;
if ($num_files == 0) {
return;
}
$num_groups = $num_files if $num_files < $num_groups;
my @groups = map {[]} (1 .. $num_groups);
foreach my $i (0 .. ($num_files - 1)) {
push @{$groups[$i % $num_groups]}, $files[$i];
}
return @groups;
}
sub preprocess_java_files(\@) {
my @files = grep {defined($_) && length($_) > 0 && (-f $_) && (-T $_)} @{$_[0]};
foreach my $f (@files) {
my $saved_f = "$f.saved_by_java_calltree";
rename $f => $saved_f;
write_content($f, read_content($saved_f));
preprocess_one_java_file($f);
}
}
sub preprocess_all_java_files() {
my @files = get_all_java_files();
my @groups = group_files(10, @files);
my $num_groups = scalar(@groups);
return if $num_groups < 1;
my @pids = (undef) x $num_groups;
for (my $i = 0; $i < $num_groups; ++$i) {
my @group = @{$groups[$i]};
my $pid = fork();
if ($pid == 0) {
preprocess_java_files(@group);
exit 0;
}
elsif ($pid > 0) {
$pids[$i] = $pid;
}
else {
die "Fail to fork a process: $!";
}
}
for (my $i = 0; $i < $num_groups; ++$i) {
wait;
}
}
sub restore_saved_files() {
my @saved_files = grep {
defined($_) && length($_) > 0 && (-f $_)
} map {
chomp;
$_
} qx(ag -U -G '.+\\.saved_by_java_calltree\$' $ignore_pattern -l);
foreach my $f (@saved_files) {
my $original_f = substr($f, 0, length($f) - length(".saved_by_java_calltree"));
rename $f => $original_f;
}
my @tmp_files = grep {
defined($_) && length($_) > 0 && (-f $_)
} map {
chomp;
$_
} qx(ag -U -G '\\.tmp\\.created_by_java_calltree\$' $ignore_pattern -l);
foreach my $f (@tmp_files) {
unlink $f;
}
}
sub register_abnormal_shutdown_hook() {
my $abnormal_handler = sub {
my $cause = shift;
$cause = red_color($cause);
print qq/Abnormal exit caused by $cause\n/;
@SIG{keys %SIG} = qw/DEFAULT/ x (keys %SIG);
restore_saved_files();
exit 0;
};
my @sig = qw/__DIE__ QUIT INT TERM ABRT/;
@SIG{@sig} = ($abnormal_handler) x scalar(@sig);
}
sub merge_lines_multiline_break_enabled(\@) {
my @lines = @{+shift};
my @three_parts = map {
if (/^([^:]+):(\d+):(.*)$/) {
[ $1, $2, $3 ]
}
else {
undef
}
} @lines;
my ($prev_file, $prev_lineno, $prev_line) = (undef, undef, undef);
# result is array of quadruples: (file, func_start_lineno, func_end_lineno, func_body)
my @result = ();
for (my $i = 0; $i < scalar(@three_parts); ++$i) {
if (!defined($three_parts[$i])) {
if (defined($prev_file)) {
# $i-1 is last line of a match block
push @result, [ $prev_file, $prev_lineno, $three_parts[$i - 1][1], $prev_line ];
($prev_file, $prev_lineno, $prev_line) = (undef, undef, undef);
}
else {
# deplicate multiline-break.
}
}
else {
if (defined($prev_file)) {
# non-first lines of a match block
$prev_line = $prev_line . $three_parts[$i][2];
}
else {
# first line of a match block
($prev_file, $prev_lineno, $prev_line) = @{$three_parts[$i]};
}
}
}
if (defined($prev_file)) {
push @result, [ $prev_file, $prev_lineno, $three_parts[-1][1], $prev_line ];
}
return @result;
}
sub merge_lines_multiline_break_disabled(\@) {
my @lines = @{+shift};
my @three_parts = map {/^([^:]+):(\d+):(.*)$/;
[ $1, $2, $3 ]} @lines;
my ($prev_file, $prev_lineno, $prev_line) = @{$three_parts[0]};
my $prev_lineno_adjacent = $prev_lineno;
my @result = ();
for (my $i = 1; $i < scalar(@three_parts); ++$i) {
my ($file, $lineno, $line) = @{$three_parts[$i]};
if (($file eq $prev_file) && ($prev_lineno_adjacent + 1 == $lineno)) {
$prev_line = $prev_line . $line;
$prev_lineno_adjacent += 1;
}
else {
push @result, [ $prev_file, $prev_lineno, $three_parts[$i][1], $prev_line ];
($prev_file, $prev_lineno, $prev_line) = ($file, $lineno, $line);
$prev_lineno_adjacent = $prev_lineno;
}
}
push @result, [ $prev_file, $prev_lineno, $three_parts[-1][1], $prev_line ];
return @result;
}
sub merge_lines(\@) {
my @lines = @{+shift};
if (multiline_break_enabled()) {
return merge_lines_multiline_break_enabled(@lines);
}
else {
return merge_lines_multiline_break_disabled(@lines);
}
}
sub extract_all_callees($$) {
my ($line, $re_func_call) = @_;
my @callees = ();
while ($line =~ /$re_func_call/g) {
push @callees, { call => $1, prefix => $2, name => $3 };
}
return @callees;
}
sub simple_name($) {
my $name = shift;
$name =~ s/ //g;
$name =~ /(~?\w+\b)$/ ? $1 : $name;
}
sub scope($) {
$_[0] =~ /\b(\w+)\b::\s*(~?\w+\b)$/;
$1
}
sub filename($) {
$_[0] =~ m{/([^/]+)\.\w+:\d+};
$1;
}
sub script_basename() {
get_path_of_script() =~ m{/([^/]+?)(?:\.\w+)?$};
$1
}
sub is_pure_name($) {
all {'a' le $_ && $_ le 'z'} split //, +shift
}
sub extract_all_funcs(\%$$) {
my ($ignored, $trivial_threshold, $length_threshold) = @_;
my $multiline_break = "";
if (multiline_break_enabled()) {
$multiline_break = "--multiline-break";
}
print qq(ag -U $multiline_break -G $java_filename_pattern $ignore_pattern '$RE_FUNC_DEFINITION'), "\n";
my @matches = map {
chomp;
$_ . " "
} qx(ag -U $multiline_break -G $java_filename_pattern $ignore_pattern '$RE_FUNC_DEFINITION');
printf "extract lines: %d\n", scalar(@matches);
die "Current directory seems not a Java project" if scalar(@matches) == 0;
my @func_file_line_def = merge_lines @matches;
printf "function definition after merge: %d\n", scalar(@func_file_line_def);
my $re_func_def_name = qr!$RE_FUNC_DEFINITION_NAME!;
my @func_def = map {$_->[3]} @func_file_line_def;
my @func_name = map {$_ =~ $re_func_def_name;
$1} @func_def;
my $re_func_call = qr!$RE_FUNC_CALL!;
printf "re_function_call=$RE_FUNC_CALL\n";
printf "process callees: begin\n";
my @func_callees = map {
my (undef, @rest) = extract_all_callees($_, $re_func_call);
[ @rest ]
} @func_def;
printf "process callees: end\n";
# remove trivial functions;
my %func_count = ();
foreach my $callees (@func_callees) {
foreach my $callee (@$callees) {
$func_count{$callee->{name}}++;
}
}
my %trivial = map {$_ => 1} grep {
is_pure_name($_) && ($func_count{$_} > $trivial_threshold || length($_) < $length_threshold)
} (keys %func_count);
my %ignored = (%$ignored, %trivial);
my %reserved = map {$_ => simple_name($_)} grep {!exists $ignored{$_}} (keys %func_count);
my @func_file_line = map {$_->[0] . ":" . $_->[1]} @func_file_line_def;
my @func_simple_name = map {simple_name($_)} @func_name;
my %calling = ();
my %called = ();
# When a function have no callees, we construct a dummy callee [NO_CALLEES] and add it to the
# called, and link this dummy node to the function. It is useful when search matched lines because
# the candidates nodes are picked from map{@$_}values %called.
my $no_callees = "[NO_CALLEES]";
$called{$no_callees} = [];
for (my $i = 0; $i < scalar(@func_name); ++$i) {
my $file_info = $func_file_line[$i];
my $caller_name = $func_name[$i];
my $caller_simple_name = $func_simple_name[$i];
my $scope = scope($caller_name);
my $filename = filename($file_info);
my ($file, $start_lineno, $end_lineno) = @{$func_file_line_def[$i]}[0 .. 2];
my @callees = @{$func_callees[$i]};
foreach my $seq (0 .. $#callees) {$callees[$seq]{seq} = $seq}
my %callees = map {
if (defined($_->{prefix})) {
$_->{prefix} . "/" . $_->{name} => $_
}
else {
$_->{name} => $_
}
} grep {exists $reserved{$_->{name}}} @callees;
@callees = values %callees;
@callees = sort {$a->{seq} <=> $b->{seq}} @callees;
my %callee_name2simple = map {$_->{name} => simple_name($_->{name})} @callees;
my $caller_node = {
name => $caller_name,
simple_name => $caller_simple_name,
scope => $scope,
file_info => $file_info,
file => $file,
start_lineno => $start_lineno,
end_lineno => $end_lineno,
filename => $filename,
callees => [ @callees ],
};
if (!exists $calling{$caller_name}) {
$calling{$caller_name} = [];
}
push @{$calling{$caller_name}}, $caller_node;
if ($caller_name ne $caller_simple_name) {
if (!exists $calling{$caller_simple_name}) {
$calling{$caller_simple_name} = [];
}
push @{$calling{$caller_simple_name}}, $caller_node;
}
my %processed_callee_names = ();
for my $callee (@callees) {
my $callee_name = $callee->{name};
my $callee_simple_name = $callee_name2simple{$callee_name};
if (!exists $called{$callee_name}) {
$called{$callee_name} = [];
}
push @{$called{$callee_name}}, $caller_node;
$processed_callee_names{$callee_name} = 1;
if (($callee_name ne $callee_simple_name) && !exists $processed_callee_names{$callee_simple_name}) {
if (!exists $called{$callee_simple_name}) {
$called{$callee_simple_name} = [];
}
push @{$called{$callee_simple_name}}, $caller_node;
$processed_callee_names{$callee_simple_name} = 1;
}
}
if (scalar(@callees) == 0) {
push @{$called{$no_callees}}, $caller_node;
}
}
my $calling_names = [ sort {$a cmp $b} keys %calling ];
my $called_names = [ sort {$a cmp $b} keys %called ];
return (\%calling, \%called, $calling_names, $called_names);
}
sub get_cached_or_extract_all_funcs(\%$$) {
my ($ignored, $trivial_threshold, $length_threshold) = @_;
restore_saved_files();
$trivial_threshold = int($trivial_threshold);
$length_threshold = int($length_threshold);
my $suffix = "$trivial_threshold.$length_threshold";
my $script_basename = script_basename();
my $file = ".$script_basename.summary.$suffix.dat";
my @key = ((sort {$a cmp $b} keys %$ignored), $trivial_threshold, $length_threshold);
my $do_summary = sub() {
print "preprocess_all_java_files\n";
preprocess_all_java_files();
print "register_abnormal_shutdown_hook\n";
register_abnormal_shutdown_hook();
print "extract_all_funcs: begin\n";
my @result =
extract_all_funcs(%$ignored, $trivial_threshold, $length_threshold);
print "extract_all_funcs: end\n";
@SIG{keys %SIG} = qw/DEFAULT/ x (keys %SIG);
restore_saved_files();
return @result;
};
my @result = get_cache_or_run_keyed(@key, $file, $do_summary);
return @result;
}
my @ignored = (
qw(for if while switch catch),
qw(VLOG LOG log warn log trace debug defined warn error fatal),
qw(static_cast reinterpret_cast const_cast dynamic_cast),
qw(return assert sizeof alignas),
qw(constexpr),
qw(set get),
qw(printf assert ASSERT),
qw(CHECK DCHECK_LT DCHECK DCHECK_EQ DCHECK_GT DCHECK_NE),
qw(UNLIKELY LIKELY unlikely likely)
);
sub get_env_or_default(&$$) {
my ($chk, $key, $default) = @_;
if (exists $ENV{$key}) {
my $value = $ENV{$key};
map {$chk->($_)} ($value);
return $value;
}
else {
return $default;
}
}
my $env_trivial_threshold = get_env_or_default {
die "Invariant 'java_calltree_trivial_threshold($_) > 0' is violated" unless int($_) > 0;
} qw/java_calltree_trivial_threshold 50/;
my $env_length_threshold = get_env_or_default {
die "Invalid 'java_calltree_length_threshold($_) > 1' is violated" unless int($_) > 1;
} qw/java_calltree_length_threshold 3/;
my %ignored = map {$_ => 1} @ignored;
my ($Global_calling, $Global_called, $Global_calling_names, $Global_called_names) = (undef, undef, undef, undef);
my $Global_pruned_cache = {};
my $Global_pruned_subtrees = {};
my $Global_common_quiet = 0;
my $Global_common_height = 0;
my $Global_common_count = 0;
sub should_prune_subtree($$) {
my ($node, $enable_prune) = @_;
if ($enable_prune && exists($node->{cache_key}) && exists($Global_pruned_cache->{$node->{cache_key}})) {
my $cache_key = $node->{cache_key};
my $cached_node = $Global_pruned_cache->{$cache_key};
if ($cached_node->{height} >= $Global_common_height && $cached_node->{count} >= $Global_common_count) {
if (!exists($Global_pruned_subtrees->{$cache_key})) {
$Global_pruned_subtrees->{$cache_key} = $cached_node;
my $idx = scalar(keys %$Global_pruned_subtrees) - 1;
$cached_node->{common_idx} = $idx;
}
return ($cached_node->{common_idx});
}
}
return ();
}
sub sub_tree($$$$$$$$) {
my ($graph, $node, $level, $depth, $path, $get_id_and_child, $install_child, $pruned) = @_;
my ($matched, $node_id, @child) = $get_id_and_child->($graph, $node);
# Assume the subtree is height of 1
$node->{height} = 1;
return undef unless defined($node_id);
$node->{leaf} = "internal";
if (scalar(@child) == 0 || ($level + 1) >= $depth || exists $path->{$node_id}) {
if (scalar(@child) == 0) {
$node->{leaf} = "outermost";
}
elsif (($level + 1) >= $depth) {
$node->{leaf} = "deep";
}
elsif (exists $path->{$node_id}) {
$node->{leaf} = "recursive";
}
else {
# never reach here;
}
return $matched ? $node : undef;
}
my $ref = sub() {
$level++;
# add node_id to path;
$path->{$node_id} = 1;
};
my $unref = sub() {
$level--;
# delete node_id from path;
delete $path->{$node_id};
};
my $raii = RAII->new($ref, $unref);
my @child_nodes = ();
my $unique_name = $node->{file_info} . "::" . $node->{name};
if (defined($pruned) && exists($pruned->{$unique_name})) {
my $cached_node = $pruned->{$unique_name};
# return undef if the current node is pruned
if (!defined($cached_node)) {
return undef;
}
else {
$cached_node->{count} += 1;
$node->{cache_key} = $unique_name;
$node->{cache_seqno} = $cached_node->{count};
$node->{height} = $cached_node->{height};
return $node;
}
}
else {
foreach my $chd (@child) {
push @child_nodes, &sub_tree($graph, $chd, $level, $depth, $path, $get_id_and_child, $install_child, $pruned);
}
}
@child_nodes = grep {defined($_)} @child_nodes;
if (@child_nodes) {
$install_child->($node, [ @child_nodes ]);
$node->{height} = max(map {$_->{height}} @child_nodes) + 1;
$node->{count} = 1;
if (defined($pruned)) {
$node->{cache_key} = $unique_name;
$pruned->{$unique_name} = $node;
}
return $node;
}
else {
$install_child->($node, []);
$node->{height} = 1;
$node->{count} = 1;
$node->{cache_key} = $unique_name if defined($pruned);
my $opt_node = ($matched || $level == 1) ? $node : undef;
if ($node->{leaf} eq "internal") {
$pruned->{$unique_name} = $opt_node if defined($pruned);
}
return $opt_node;
}
}
sub eliminate_empty_children($) {
my ($root) = @_;
unless (defined($root) && exists($root->{child})) {
return $root;
}
$root->{child} = [ grep {defined($_) && (!exists($_->{child}) || scalar(@{$_->{child}}) > 0)} @{$root->{child}} ];
if (scalar(@{$root->{child}}) > 0) {
return $root;
}
else {
return undef;
}
}
sub remove_loop($$$) {
my ($cache, $cache_key, $visited) = @_;
my $remove_child = sub($$) {
my ($n, $k) = @_;
$n->{child} = [ grep {!exists($_->{cache_key}) || $_->{cache_key} ne $k} @{$n->{child}} ];
};
my $ref = sub() {
$visited->{$cache_key} = 1;
};
my $unref = sub() {
delete($visited->{$cache_key});
};
my $raii = RAII->new($ref, $unref);
my $node = $cache->{$cache_key};
my @cache_keys = map {$_->{cache_key}} grep {exists($_->{cache_key})} @{$node->{child}};
foreach my $chd_cache_key (@cache_keys) {
if (exists($visited->{$chd_cache_key})) {
$remove_child->($node, $chd_cache_key);
}
else {
&remove_loop($cache, $chd_cache_key, $visited);
}
}
}
sub remove_all_loops($) {
my ($cache) = @_;
my $visited = {};
foreach my $cache_key (keys %$cache) {
remove_loop($cache, $cache_key, $visited);
}
}
use List::Util qw/min max/;
sub lev_dist($$) {
my ($a, $b) = @_;
my ($a_len, $b_len) = (0, 0);
$a_len = length($a) if defined($a);
$b_len = length($b) if defined($b);
return $b_len if $a_len == 0;
return $a_len if $b_len == 0;
my @a = split //, lc $a;
my @b = split //, lc $b;
my ($ii, $jj) = ($a_len + 1, $b_len + 1);
my @d = map {[ (0) x $jj ]} 1 .. $ii;
for (my $i = 0; $i < $ii; ++$i) {
$d[$i][0] = $i;
}
for (my $j = 0; $j < $jj; ++$j) {
$d[0][$j] = $j;
}
for (my $i = 1; $i < $ii; ++$i) {
for (my $j = 1; $j < $jj; ++$j) {
my ($ci, $cj) = ($a[$i - 1], $b[$j - 1]);
if ($ci eq $cj) {
$d[$i][$j] = $d[$i - 1][$j - 1];
}
else {
$d[$i][$j] = 1 + min($d[$i - 1][$j], $d[$i][$j - 1], $d[$i - 1][$j - 1]);
}
}
}
return $d[-1][-1];
}