forked from huiqing/percept2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sim_code.erl
executable file
·1384 lines (1219 loc) · 50.7 KB
/
sim_code.erl
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
%% Copyright (c) 2011, Huiqing Li, Simon Thompson
%% All rights reserved.
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions are met:
%% %% Redistributions of source code must retain the above copyright
%% notice, this list of conditions and the following disclaimer.
%% %% Redistributions in binary form must reproduce the above copyright
%% notice, this list of conditions and the following disclaimer in the
%% documentation and/or other materials provided with the distribution.
%% %% Neither the name of the copyright holders nor the
%% names of its contributors may be used to endorse or promote products
%% derived from this software without specific prior written permission.
%%
%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS''
%% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS
%% BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
%% BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
%% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
%% OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
%% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%% ===========================================================================================
%% Incremental similar code detection for Erlang programs.
%%
%% Author contact: hl@kent.ac.uk, sjt@kent.ac.uk
%%
%% @private
-module(sim_code).
-export([sim_code_detection/8,sim_code_detection/4]).
-export([ sim_code_detection_1/6,
gen_initial_clone_candidates/3,
generalise_and_hash_ast/6,
check_clone_candidates/4]).
-export([ hash_loop/1, pforeach_0/3, clone_check_loop/3, pmap_1/3, pforeach_1/3]).
-include_lib("wrangler/include/wrangler_internal.hrl").
-define(INC, false). %% incremental or not.
%% default threshold values.
-define(DefaultSimiScore, 0.8).
-define(DEFAULT_LEN, 5).
-define(DEFAULT_TOKS, 40).
-define(DEFAULT_FREQ, 2).
-define(DEFAULT_SIMI_SCORE, 0.8).
-define(DEFAULT_NEW_VARS, 4).
-define(MIN_TOKS, 10).
%% record for threshold values.
-record(threshold,
{min_len = ?DEFAULT_LEN,
min_freq= ?DEFAULT_FREQ,
min_toks= ?DEFAULT_TOKS,
max_new_vars =?DEFAULT_NEW_VARS,
simi_score=?DEFAULT_SIMI_SCORE}).
%% record for ets/dets table names.
-record(tabs,
{ast_tab,
var_tab,
exp_hash_tab,
clone_tab
}).
-define(PARALLEL, false).
-spec(sim_code_detection/8::(DirFileList::[filename()|dir()], MinLen::integer(), MinToks::integer(),
MinFreq::integer(), MaxVars::integer(),SimiScore::float(),
SearchPaths::[dir()], TabWidth::integer()) -> {ok, string()}).
sim_code_detection(DirFileList,MinLen1,MinToks1,MinFreq1,MaxVars1,SimiScore1,SearchPaths,TabWidth) ->
{MinLen,MinToks,MinFreq,MaxVars,SimiScore} = check_parameters(MinLen1,MinToks1,MinFreq1,MaxVars1,SimiScore1),
Files = wrangler_misc:expand_files(DirFileList,".erl"),
case Files of
[] ->
?wrangler_io("Warning: No files found in the searchpaths specified.",[]);
_ -> Cs = sim_code_detection(Files, {MinLen, MinToks, MinFreq, MaxVars, SimiScore},
SearchPaths, TabWidth),
%% wrangler_io:format("\nStart displaying results...\n"),
wrangler_code_search_utils:display_clone_result(Cs, "Similar")
%% wrangler_io:format("\nTime spent on displaying results: ~p\n", [to_seconds(T)])
end,
{ok, "Similar code detection finished."}.
sim_code_detection(Files, {MinLen, MinToks, MinFreq, MaxVars, SimiScore},
SearchPaths, TabWidth) ->
%% dets tables used to cache information.
Tabs = #tabs{ast_tab = create_ets(ast_tab),
var_tab = create_ets(var_tab),
exp_hash_tab = create_ets(expr_hash_tab),
clone_tab = create_ets(expr_clone_tab)},
%% Threshold parameters.
Threshold = #threshold{min_len = MinLen,
min_freq = MinFreq,
min_toks = MinToks,
max_new_vars = MaxVars,
simi_score = SimiScore},
HashPid = start_hash_process(),
%% Clone detection.
Cs = sim_code_detection_1(Files,Threshold,Tabs, HashPid,SearchPaths,TabWidth),
%% ?wrangler_io("\nTime spent on generalisarion and hashing: ~w seconds\n",[to_seconds(T1)]),
%% ?wrangler_io("\nTime spent on generating initial clone candidates: ~w seconds\n",[to_seconds(T2)]),
%% ?wrangler_io("\nTime spent on examination of clone candidates: ~w seconds\n",[to_seconds(T3)]),
%% ?wrangler_io("\nTotal Time spent:\n~p\n", [to_seconds(T0)]),
stop_hash_process(HashPid),
Cs.
%% incremental clone detection.
sim_code_detection_1(Files, Thresholds, Tabs, HashPid, SearchPaths, TabWidth) ->
?wrangler_io("\nGeneralise and hash ASTs ...\n", []),
generalise_and_hash_ast(Files, Thresholds, Tabs, HashPid, SearchPaths, TabWidth),
?wrangler_io("\nCollecting initial clone candidates ...\n",[]),
Cs= gen_initial_clone_candidates(Files, Thresholds,HashPid),
?wrangler_io("\nNumber of initial clone candidates: ~p\n", [length(Cs)]),
?wrangler_io("\nChecking clone candidates ... \n", []),
Cs4 = check_clone_candidates(Thresholds, Tabs, HashPid, Cs),
%%?wrangler_io("\nChecking clone candidates finshed; time used: ~w seconds \n", [to_seconds(T3)]),
Cs4.
gen_initial_clone_candidates(Files, Thresholds, HashPid) ->
%% Generate clone candidates using suffix tree based clone detection techniques.
Dir = filename:dirname(hd(Files)),
{ok, OutFileName} = get_clone_candidates(HashPid, Thresholds, Dir),
{ok, Res} = file:consult(OutFileName),
file:delete(OutFileName),
Cs0 = case Res of
[] -> [];
[R] -> R
end,
process_initial_clones(Cs0).
process_initial_clones(Cs) ->
lists:map(fun({Rs, Len, _Freq}) ->
Rs1 =sets:to_list(sets:from_list(Rs)),
{Rs1, Len, length(Rs1)}
end, Cs).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%
%% Generalise and hash ASTs %%
%% %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Serialise, in breath-first order, generalise each expression in the AST and insert them into
%% the AST table. Each object in the AST table has the following format:
%% {{FileName, FunName, Arity, Index}, ExprAST}, where Index is used to identify a specific
%% expression in the function.
generalise_and_hash_ast(Files, Threshold, Tabs, HashPid, SearchPaths, TabWidth) ->
%% change 1.
pforeach(fun(File) ->
generalise_and_hash_file_ast_1(
File, Threshold, Tabs, HashPid, true, SearchPaths, TabWidth)
end, Files).
%% Generalise and hash the AST for an single Erlang file.
generalise_and_hash_file_ast_1(FName, Threshold, Tabs, HashPid, IsNewFile, SearchPaths, TabWidth) ->
Forms = try wrangler_ast_server:quick_parse_annotate_file(FName, SearchPaths, TabWidth) of
{ok, {AnnAST, _Info}} ->
wrangler_syntax:form_list_elements(AnnAST)
catch
_E1:_E2 -> []
end,
F = fun (Form) ->
case wrangler_syntax:type(Form) of
function ->
generalise_and_hash_function_ast(Form, FName, IsNewFile, Threshold, Tabs, HashPid);
_ -> ok
end
end,
%% change 2.
pforeach(fun (Form) -> F(Form) end, Forms).
%% generalise and hash the AST of a single function.
generalise_and_hash_function_ast(Form, FName, true, Threshold, Tabs, HashPid) ->
FunName = wrangler_syntax:atom_value(wrangler_syntax:function_name(Form)),
Arity = wrangler_syntax:function_arity(Form),
HashVal = erlang:md5(format(Form)),
generalise_and_hash_function_ast_1(FName, Form, FunName, Arity, HashVal, Threshold, Tabs, HashPid).
%% generalise and hash a function that is either new or has been changed since last run of clone detection.
generalise_and_hash_function_ast_1(File, Form, FunName, Arity, HashVal, Threshold, Tabs, HashPid) ->
{StartLine, _} = wrangler_syntax:get_pos(Form),
%% Turn absolute locations to relative locations, so
%% so that the result can be reused.
NewForm = absolute_to_relative_loc(Form, StartLine),
%% all locations are relative locations.
%% variable binding information is needed by the anti-unification process.
AllVars = wrangler_misc:collect_var_source_def_pos_info(NewForm),
%% I also put the Hashvalue of a function in var_tab.
ets:insert(Tabs#tabs.var_tab, {{File, FunName, Arity}, HashVal, AllVars}),
ASTTab = Tabs#tabs.ast_tab,
Fun = fun(Node, Index) ->
case wrangler_syntax:type(Node) of
clause ->
Body = wrangler_syntax:clause_body(Node),
generalise_and_hash_body(ASTTab, HashPid, Body, StartLine,
{File, FunName, Arity}, Threshold, Index);
block_expr ->
Body = wrangler_syntax:block_expr_body(Node),
generalise_and_hash_body(ASTTab, HashPid, Body, StartLine,
{File, FunName, Arity}, Threshold, Index);
try_expr ->
Body = wrangler_syntax:try_expr_body(Node),
generalise_and_hash_body(ASTTab, HashPid, Body, StartLine,
{File, FunName, Arity}, Threshold, Index);
_ -> Index
end
end,
api_ast_traverse:fold(Fun, 1, NewForm).
generalise_and_hash_body(ASTTab, HashPid, Body, StartLine, FFA,
Threshold, Index) ->
Len = length(Body),
case Len>= Threshold#threshold.min_len of
true ->
ExprASTsWithIndex = lists:zip(Body, lists:seq(0, Len - 1)),
HashValExprPairs=[generalise_and_hash_expr(ASTTab, FFA, StartLine,
Index, {E, I})
||{E, I}<-ExprASTsWithIndex],
insert_hash(HashPid, {FFA, HashValExprPairs}),
Index + Len;
false ->
Index
end.
generalise_and_hash_expr(ASTTab, {M, F, A}, StartLine,
StartIndex, {Expr, RelativeIndex}) ->
%% Num of tokens is used to chech the size of a clone candidate.
NoOfToks = no_of_tokens(Expr),
%% insert the AST of an expression into the ast table.
ets:insert(ASTTab, {{M, F, A, StartIndex + RelativeIndex}, Expr}),
E1 = do_generalise(Expr),
%% get the hash values of the generalised expression.
HashVal = erlang:md5(format(E1)),
%% the location here is relative location.
StartEndLoc = wrangler_misc:start_end_loc(Expr),
{HashVal, {StartIndex + RelativeIndex,
NoOfToks, StartEndLoc, StartLine}}.
%% replace an AST node if the node can be generalised.
do_generalise(Node) ->
F0 = fun (T, _Others) ->
case wrangler_code_search_utils:generalisable(T) of
true ->
{wrangler_syntax:variable('Var'), true};
false -> {T, false}
end
end,
element(1, api_ast_traverse:stop_tdTP(F0, Node, [])).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%
%% Hash the AST representation of generalised expressions using MD5, %%
%% and map sequences of expressions into sequences of indexes. %%
%% %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
start_hash_process() ->
ExpHashTab=ets:new(expr_hash_tab, [set, public]),
%% spawn_link(fun () -> hash_loop({1, ExpHashTab, []}) end).
spawn_link(?MODULE, hash_loop, [{1, ExpHashTab, []}]).
%% Get initial clone candidates.
get_clone_candidates(Pid, Thresholds, Dir) ->
Pid ! {get_clone_candidates, self(), Thresholds, Dir},
receive
{Pid, {ok, OutFileName}}->
{ok, OutFileName}
end.
get_clone_in_range(Pid, C) ->
Pid! {get_clone_in_range, self(), C},
receive
{Pid, C1} ->
C1
end.
stop_hash_process(Pid) ->
Pid!stop.
insert_hash(Pid, {{M, F, A}, HashExprPairs}) ->
Pid ! {add, {{M, F, A}, HashExprPairs}}.
get_index(ExpHashTab, Key) ->
case ets:lookup(ExpHashTab, Key) of
[{Key, I}]->
I;
[] ->
NewIndex = ets:info(ExpHashTab, size)+1,
ets:insert(ExpHashTab, {Key, NewIndex}),
NewIndex
end.
hash_loop({NextSeqNo, ExpHashTab, NewData}) ->
receive
%% add a new entry.
{add, {{M, F, A}, KeyExprPairs}} ->
KeyExprPairs1 =
[{{Index1, NumOfToks, StartEndLoc, StartLine, true}, HashIndex}
|| {Key, {Index1, NumOfToks, StartEndLoc, StartLine}} <- KeyExprPairs,
HashIndex <- [get_index(ExpHashTab, Key)]],
hash_loop({NextSeqNo+1, ExpHashTab, [{NextSeqNo, {M,F,A}, KeyExprPairs1}| NewData]});
{get_clone_candidates, From, Thresholds, Dir} ->
{ok, OutFileName} = search_for_clones(Dir, lists:reverse(NewData), Thresholds),
From ! {self(), {ok, OutFileName}},
hash_loop({NextSeqNo, ExpHashTab, lists:reverse(NewData)});%%!!!! Data Reorded!!!
{get_clone_in_range, From, {Ranges, Len, Freq}} ->
F0 = fun ({ExprSeqId, ExprIndex}, L) ->
{ExprSeqId, {M, F, A}, Exprs} = lists:nth(ExprSeqId, NewData),
Es = lists:sublist(Exprs, ExprIndex, L),
[{{M,F,A,Index}, Toks, {{StartLoc, EndLoc}, StartLine}, IsNew}
|| {{Index, Toks, {StartLoc, EndLoc}, StartLine, IsNew}, _HashIndex} <- Es]
end,
C1 = {[F0(R, Len) || R <- Ranges], {Len, Freq}},
From ! {self(), C1},
hash_loop({NextSeqNo, ExpHashTab, NewData});
stop ->
ok
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%
%% Hash the AST representation of expressions using MD5, and map %%
%% sequence of expression into sequences of indexes. %%
%% %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
check_clone_candidates(Thresholds, Tabs, HashPid, Cs) ->
CloneCheckerPid = start_clone_check_process(Tabs),
%% examine each clone candiate and filter false positives.
Cs2 = examine_clone_candidates(Cs, Thresholds, Tabs, CloneCheckerPid, HashPid),
Cs3 = combine_clones_by_au(Cs2),
%%wrangler_io:format("Time spent on combining clones by au:~p\n", [T]),
stop_clone_check_process(CloneCheckerPid),
[{R, L, F, C}||{R, L, F, C}<-Cs3, length(R)>=2].
start_clone_check_process(Tabs) ->
%% spawn_link(fun()->clone_check_loop([],[], Tabs) end).
spawn_link(?MODULE, clone_check_loop, [[],[], Tabs]).
stop_clone_check_process(Pid) ->
Pid ! stop.
add_new_clones(Pid, Clones) ->
Pid ! {add_clone, Clones}.
get_final_clone_classes(Pid) ->
Pid ! {get_clones, self()},
receive
{Pid, Cs} ->
Cs
end.
clone_check_loop(Cs, CandidateClassPairs, Tabs) ->
receive
{add_clone, {Candidate, Clones}} ->
%%wrangler_io:format("\nAdd a clone ...\n"),
Clones1=[get_clone_class_in_absolute_locs(Clone)
|| Clone <- Clones],
%%wrangler_io:format("\n get clone class in absoulte locs done\n"),
NewCandidateClassPairs = [{hash_a_clone_candidate(Candidate), Clones}
|CandidateClassPairs],
%%wrangler_io:format("\nFinished adding a clone ...\n"),
clone_check_loop(Clones1 ++ Cs, NewCandidateClassPairs, Tabs);
{get_clones, From} ->
%%wrangler_io:format("\n get processed clones ... \n"),
Cs0=remove_sub_clones(Cs),
%% wrangler_io:format("\nTime spent on removing sub clones:~p\n", [to_seconds(T)]),
Cs1=[{AbsRanges, Len, Freq, AntiUnifier}||
{_, {Len, Freq}, AntiUnifier,AbsRanges}<-Cs0],
From ! {self(), Cs1},
clone_check_loop(Cs, CandidateClassPairs, Tabs);
stop ->
%%ets:insert(Tabs#tabs.clone_tab, CandidateClassPairs),
ok;
_Msg ->
?wrangler_io("Unexpected message:\n~p\n",[_Msg]),
clone_check_loop(Cs, CandidateClassPairs, Tabs)
end.
%%=============================================================================
%% check each candidate clone, and drive real clone classes.
examine_clone_candidates(Cs, Thresholds, Tabs, CloneCheckerPid, HashPid) ->
NumberedCs = lists:zip(Cs, lists:seq(1, length(Cs))),
pforeach(fun({C, Nth}) ->
examine_a_clone_candidate({C,Nth},Thresholds, Tabs, CloneCheckerPid, HashPid)
end, NumberedCs),
get_final_clone_classes(CloneCheckerPid).
examine_a_clone_candidate({C, Nth},Thresholds,Tabs,CloneCheckerPid,HashPid) ->
output_progress_msg(Nth),
C1 = get_clone_in_range(HashPid,C),
MinToks = Thresholds#threshold.min_toks,
MinFreq = Thresholds#threshold.min_freq,
Num=case remove_short_clones(C1,MinToks,MinFreq) of
[] ->
0;
[C2] ->
case examine_a_clone_candidate(C2,Thresholds,Tabs) of
[] ->
0;
ClonesWithAU ->
add_new_clones(CloneCheckerPid,{C2, ClonesWithAU}),
length(ClonesWithAU)
end
end,
output_progress_msg_1(Nth, Num).
output_progress_msg(_Nth) ->
%% ?wrangler_io("\nChecking clone candidate no. ~p ...", [Nth]).
ok.
output_progress_msg_1(_Nth, _Num) ->
ok.
%% ?wrangler_io("\nChecking clone candidate no. ~p finished "
%% "with ~p clone classes derived..", [Nth, Num]).
hash_a_clone_candidate(_C={Ranges, {_Len, _Freq}}) ->
F = fun({MFAI, Toks, {Loc, _StartLine}, _IsNew}) ->
{MFAI, Toks, Loc}
end,
erlang:md5(lists:usort(
[erlang:md5(lists:flatten(
io_lib:format(
"~p", [[F(E)||E<-R]])))
||R<-Ranges])).
%% examine a clone candidate.
examine_a_clone_candidate(_C={Ranges, {_Len, _Freq}}, Thresholds, Tabs) ->
ASTTab = Tabs#tabs.ast_tab,
RangesWithExprAST=[attach_expr_ast_to_ranges(R, ASTTab)|| R<-Ranges],
Clones = examine_clone_class_members(RangesWithExprAST, Thresholds, Tabs,[]),
ClonesWithAU = [begin
FromSameFile=from_same_file(Rs),
AU= get_anti_unifier(Info, FromSameFile),
{Rs1, AU1} = attach_fun_call_to_range(Rs, AU, FromSameFile),
{Rs1, {Len, length(Rs1)}, AU1}
end
|| {Rs, {Len, _}, Info} <- Clones],
[{Rs1, {Len, F}, AU1}||{Rs1, {Len, F}, AU1}<-ClonesWithAU,
F>=Thresholds#threshold.min_freq].
attach_expr_ast_to_ranges(Rs, ASTTab) ->
[{R, ExpAST}||R={ExprKey, _Toks, _Loc, _IsNew}<-Rs,
{_Key, ExpAST}<-ets:lookup(ASTTab, ExprKey)].
%% check the clone members of a clone candidate using
%% anti-unification techniques.
examine_clone_class_members(RangesWithExprAST, Thresholds, _, Acc)
when length(RangesWithExprAST)< Thresholds#threshold.min_freq ->
%% The number of clone memebers left is less
%% than the min_freq threshold, so the examination
%% finishes, and sub-clones are removed.
remove_sub_clones(Acc);
examine_clone_class_members(RangesWithExprAST, Thresholds,Tabs, Acc) ->
%% Take the first clone member and try to anti_unify other
%% clone members with this member. If there is a real clone
%% class found, then the anti-unifier of the class is derrived
%% by generalisation of the first clone member.
[RangeWithExprAST1|Rs]=RangesWithExprAST,
%% try to anti_unify each of the remaining candidate clone members
%% with the first candidate clone member.
Res = [do_anti_unification(RangeWithExprAST1, RangeWithExprAST2)
|| RangeWithExprAST2<-Rs],
%% process the anti_unification result.
Clones = process_au_result(Res, Thresholds, Tabs),
%% get the maximal length of the clone clone members returned.
MaxCloneLength= case Clones ==[] of
true ->
0;
_->
%% make sure the clones returned are ordered!!!
element(1, element(2, hd(Clones)))
end,
InitialLength = length(RangeWithExprAST1),
case MaxCloneLength /= InitialLength of
true ->
%% the original expression sequences have been chopped into shorter ones.
examine_clone_class_members(Rs, Thresholds,Tabs, Clones ++ Acc);
false ->
%% the original expression still a class member of the clones returned.
Rs1 = element(1, hd(Clones)),
RemainedRanges = RangesWithExprAST -- Rs1,
examine_clone_class_members(RemainedRanges, Thresholds,Tabs, Clones ++ Acc)
end.
%% try to anti-unify two expression sequences.
do_anti_unification(RangeWithExpr1, RangeWithExpr2) ->
ZippedExprs=lists:zip(RangeWithExpr1, RangeWithExpr2),
[begin
{{Index1,E1}, {Index2, E2},
do_anti_unification_1(E1,E2)}
end|| {{Index1,E1}, {Index2, E2}}<-ZippedExprs].
%% try to anti_unift two expressions.
do_anti_unification_1(E1, E2) ->
SubSt=wrangler_anti_unification:anti_unification(E1,E2),
case SubSt of
none -> none;
_ -> case subst_sanity_check(E1, SubSt) of
true ->
SubSt;
false ->
none
end
end.
subst_sanity_check(Expr1, SubSt) ->
BVs = api_refac:bound_vars(Expr1),
F = fun ({E1, E2}) ->
case wrangler_syntax:type(E1) of
variable ->
case is_macro_name(E1) of
true ->
false;
_ -> has_same_subst(E1, E2, SubSt)
end;
_ ->
%% the expression to be replaced should not contain local variables.
BVs -- api_refac:free_vars(E1) == BVs
end
end,
lists:all(F, SubSt).
has_same_subst(E1, E2, SubSt) ->
E1Ann = wrangler_syntax:get_ann(E1),
{value, {def, DefPos}} = lists:keysearch(def, 1, E1Ann),
%% local vars should have the same substitute.
not lists:any(
fun ({E11, E21}) ->
wrangler_syntax:type(E11) == variable andalso
{value, {def, DefPos}} == lists:keysearch(
def, 1, wrangler_syntax:get_ann(E11))
andalso
wrangler_prettypr:format(wrangler_misc:reset_ann_and_pos(E2))
=/= wrangler_prettypr:format(wrangler_misc:reset_ann_and_pos(E21))
end, SubSt).
%% process anti-unification result.
process_au_result(AURes, Thresholds, Tabs) ->
Res = [process_one_au_result(OneAURes, Thresholds, Tabs)
|| OneAURes <- AURes],
ClonePairs = lists:append(Res),
get_clone_classes(ClonePairs, Thresholds, Tabs).
%% process one anti_unification pair. In case the whose
%% pair of expression sequences do not anti-unify, get those
%% pairs of sub sequences that do anti-unify.
process_one_au_result(OneAURes, Thresholds, _Tabs) ->
SubAULists=group_au_result(OneAURes, Thresholds),
ClonePairs =lists:append([get_clone_pairs(SubAUList, Thresholds)
||SubAUList<-SubAULists]),
ClonePairs1 =[lists:unzip3(CP)||CP<-ClonePairs],
remove_sub_clone_pairs(ClonePairs1).
%% examine the result of anti-unifying a pair of expression sequences and
%% get the sub expression sequences pairs that are anti-unifiable.
group_au_result([], _Thresholds)->
[];
group_au_result(AURes, Thresholds) ->
%% here 'none' means the two expressions E1 an E2 do not anti-unify.
{AUResList1,AUResList2} =
lists:splitwith(fun({_E1,_E2, S}) ->S/=none end, AURes),
AUResList3 = case AUResList2 of
[] -> [];
[_|T] -> T
end,
case clone_pair_above_min_size(AUResList1, Thresholds) of
true ->
[AUResList1]++group_au_result(AUResList3, Thresholds);
false ->
group_au_result(AUResList3, Thresholds)
end.
get_clone_pairs(AURes, Thresholds) ->
get_clone_pairs(AURes, Thresholds, {[],[]},[]).
get_clone_pairs([],Thresholds,{_VarSubAcc,ClonePairAcc},Acc) ->
case clone_pair_above_min_size(ClonePairAcc,Thresholds) of
true ->
ClonePairs = decompose_clone_pair(lists:reverse(ClonePairAcc),Thresholds),
ClonePairs++Acc;
false ->
Acc
end;
get_clone_pairs([CurPair = {_E1,_E2,SubSt}| AURes],Thresholds,
{VarSubAcc,ClonePairAcc},Acc) ->
%% check the subsitution of variables.
%% variables with the same defining location should
%% has the same substitution.
CurVarSubsts = get_var_subst(SubSt),
case var_sub_conflicts(CurVarSubsts,VarSubAcc) of
true ->
%% conflicting variable substitution.
case clone_pair_above_min_size(ClonePairAcc,Thresholds) of
true ->
NewClonePairs = decompose_clone_pair(lists:reverse(ClonePairAcc),Thresholds),
NewAcc = NewClonePairs++Acc,
get_clone_pairs(AURes,Thresholds,{[],[]},NewAcc);
false ->
%% the clone pairs is too short.
get_clone_pairs(AURes,Thresholds,{[],[]},Acc)
end;
false ->
get_clone_pairs(AURes,Thresholds,
{CurVarSubsts++VarSubAcc,[CurPair]++ClonePairAcc},Acc)
end.
get_var_subst(SubSt) ->
F = fun ({E1, E2}) ->
{value, {def, DefPos}} =
lists:keysearch(def, 1, wrangler_syntax:get_ann(E1)),
{DefPos, wrangler_prettypr:format(wrangler_misc:reset_ann_and_pos(E2))}
end,
[F({E1,E2})
|| {E1,E2} <- SubSt,
wrangler_syntax:type(E1) == variable,
not is_macro_name(E1)].
is_macro_name(Exp) ->
Ann = wrangler_syntax:get_ann(Exp),
{value, {syntax_path, macro_name}} ==
lists:keysearch(syntax_path, 1, Ann).
var_sub_conflicts(SubSts, ExistingVarSubsts) ->
lists:any(fun ({DefPos, E}) ->
case lists:keysearch(DefPos, 1, ExistingVarSubsts) of
{value, {DefPos, E1}} ->
E /= E1;
false ->
false
end
end, SubSts).
%% decompose a clone pairs so that each new clone pairs' simi score
%% is above the threshold specified.
decompose_clone_pair(ClonePair,Thresholds) ->
ListOfClonePairs=decompose_clone_pair_by_new_vars(ClonePair, Thresholds),
Res=[decompose_clone_pair_by_simi_score(CP, Thresholds)||CP<-ListOfClonePairs],
lists:append(Res).
decompose_clone_pair_by_simi_score(ClonePair, Thresholds) ->
case clone_pair_above_min_simi_score(ClonePair, Thresholds) of
true ->
[ClonePair];
false->
decompose_clone_pair_by_simi_score_1(ClonePair, Thresholds)
end.
decompose_clone_pair_by_simi_score_1(ClonePair,Thresholds) ->
ClonePairWithSimiScore =
[{R1, R2, Subst, {simi_score([R1], SubEs1), simi_score([R2], SubEs2)}}
||{R1, R2, Subst}<-ClonePair, {SubEs1, SubEs2}<-[lists:unzip(Subst)]],
decompose_clone_pair_by_simi_score_2(ClonePairWithSimiScore, Thresholds).
decompose_clone_pair_by_simi_score_2(ClonePairWithSimiScore, Thresholds) ->
Scores = [(Score1+Score2)/2||Pair<-ClonePairWithSimiScore,
{Score1,Score2}<-[element(4, Pair)]],
MinScore = lists:min(Scores),
%%spliting the clone pairs at the pair of expressions with the lowest
%% similarity score.
{ClonePair1, [_P|ClonePair2]} = lists:splitwith(
fun({_, _, _, {Score1, Score2}}) ->
(Score1+Score2)/2 /= MinScore
end, ClonePairWithSimiScore),
decompose_clone_pair_by_simi_score_3(ClonePair1, Thresholds)
++ decompose_clone_pair_by_simi_score_3(ClonePair2, Thresholds).
decompose_clone_pair_by_simi_score_3(ClonePair, Thresholds)->
case not clone_pair_above_min_size(ClonePair, Thresholds) of
true ->
[];
false ->
CP =[{R1, R2, Subst}||{R1,R2, Subst, _}<-ClonePair],
case clone_pair_above_min_simi_score(CP, Thresholds) of
true ->
[CP];
false ->
decompose_clone_pair_by_simi_score_2(ClonePair, Thresholds)
end
end.
decompose_clone_pair_by_new_vars(ClonePair, Thresholds)->
MinLen = Thresholds#threshold.min_len,
MaxNewVars = Thresholds#threshold.max_new_vars,
{{CurLen, _}, CurClonePair, ClonePairs}=
lists:foldl(fun({R1,R2, Subst}, {{Len, SubstAcc}, Acc1, Acc2})->
case Subst of
[] ->
{{Len+1, SubstAcc}, [{R1,R2,Subst}|Acc1], Acc2};
_ ->
NewVars=num_of_new_vars(Subst++SubstAcc),
case NewVars> MaxNewVars of
true ->
{NewAcc1, NewSubst} = get_sub_clone_pair(lists:reverse([{R1,R2,Subst}|Acc1]), MaxNewVars),
NewLen = length(NewAcc1),
case Len>=MinLen of
true ->
{{NewLen, NewSubst}, lists:reverse(NewAcc1), [lists:reverse(Acc1)|Acc2]};
false ->
{{NewLen, NewSubst}, lists:reverse(NewAcc1), Acc2}
end;
false ->
{{Len+1, Subst++SubstAcc}, [{R1,R2,Subst}|Acc1], Acc2}
end
end
end,
{{0, []}, [], []}, ClonePair),
case CurLen>=MinLen of
true ->
lists:reverse([lists:reverse(CurClonePair)|ClonePairs]);
false ->
lists:reverse(ClonePairs)
end.
get_sub_clone_pair([{_R1,_R2, Subst}|CPs], NumOfNewVars) ->
case Subst of
[] ->
get_sub_clone_pair(CPs, NumOfNewVars);
_ ->
{_,_, ListOfSubSt} = lists:unzip3(CPs),
NewSubst = lists:append(ListOfSubSt),
case num_of_new_vars(NewSubst) =< NumOfNewVars of
true ->
{CPs, NewSubst};
false ->
get_sub_clone_pair(CPs, NumOfNewVars)
end
end.
clone_pair_above_min_simi_score(ClonePair, Thresholds)->
SimiScoreThreshold = Thresholds#threshold.simi_score,
{Range1, Range2, Subst} = lists:unzip3(ClonePair),
{SubExprs1, SubExprs2} = lists:unzip(lists:append(Subst)),
Score1 = simi_score(Range1, SubExprs1),
Score2 = simi_score(Range2, SubExprs2),
Score1 >= SimiScoreThreshold andalso
Score2>= SimiScoreThreshold.
clone_pair_above_min_size(CP, Thresholds) ->
length(CP)>=Thresholds#threshold.min_len andalso
lists:sum([element(2, E1)||{{E1,_}, _E2, _S}<-CP])
>=Thresholds#threshold.min_toks.
simi_score(ExprRanges, SubExprs) ->
ExprToks = lists:sum([element(2, (element(1,R)))||R<-ExprRanges]),
case ExprToks of
0 ->
0;
_ ->
1-((num_of_tokens(SubExprs)-length(SubExprs))/ExprToks)
end.
num_of_tokens(Exprs) ->
lists:sum([num_of_tokens_in_string(format(E))
||E<-Exprs]).
num_of_tokens_in_string(Str) ->
case wrangler_scan:string(Str, {1,1}, 8, 'unix') of
{ok, Ts, _} ->
Ts1 = [T||T<-Ts],
length(Ts1);
_ ->
0
end.
remove_sub_clone_pairs([]) ->[];
remove_sub_clone_pairs(CPs) ->
SortedCPs = lists:sort(fun({Rs1,_,_}, {Rs2, _, _}) ->
length(Rs1)>length(Rs2)
end, CPs),
remove_sub_clone_pairs(SortedCPs, []).
remove_sub_clone_pairs([], Acc) ->
lists:reverse(Acc);
remove_sub_clone_pairs([CP={Rs, _,_}|CPs], Acc) ->
case lists:any(fun({Rs1, _,_}) ->
Rs--Rs1==[]
end, Acc) of
true ->
remove_sub_clone_pairs(CPs,Acc);
_ -> remove_sub_clone_pairs(CPs, [CP|Acc])
end.
%% derive clone classes from clone pairs.
get_clone_classes(ClonePairs,Thresholds, Tabs) ->
RangeGroups = lists:usort([Rs1 || {Rs1, _Rs2, _Subst} <- ClonePairs]),
CloneClasses = lists:append([get_one_clone_class(Range, ClonePairs, Thresholds, Tabs)
|| Range <- RangeGroups]),
lists:keysort(2, CloneClasses).
get_one_clone_class(RangeWithExprAST, ClonePairs, Thresholds, Tabs) ->
Res = lists:append([get_one_clone_class_1(RangeWithExprAST, ClonePair, Tabs)
|| ClonePair <- ClonePairs]),
CloneClasses =group_clone_pairs(Res, Thresholds),
[begin
{Range, Exprs} = lists:unzip(RangeWithExprAST),
[{{FName, FunName, Arity, _}, _, _,_}| _] = Range,
VarTab = Tabs#tabs.var_tab,
VarsToExport = get_vars_to_export(Exprs, {FName, FunName, Arity}, VarTab),
{Ranges, ExportVars, SubSt} = lists:unzip3(C),
%% VarstoExport format : [{name, pos}].
ExportVars1 = {element(1, lists:unzip(VarsToExport)),
lists:usort(lists:append(ExportVars))},
{[RangeWithExprAST| Ranges], {length(Exprs), length(Ranges) + 1},
{Exprs, SubSt, ExportVars1}}
end
|| C<-CloneClasses].
get_one_clone_class_1(RangeWithExprAST, _ClonePair = {Range1, Range2, Subst}, Tabs) ->
case RangeWithExprAST -- Range1 == [] of
true ->
%% Range is a sub list of Range1.
Len = length(RangeWithExprAST),
R = hd(RangeWithExprAST),
StartIndex=length(lists:takewhile(fun (R0) -> R0 /= R end, Range1))+1,
SubRange2 = lists:sublist(Range2, StartIndex, Len),
SubSubst = lists:append(lists:sublist(Subst, StartIndex, Len)),
{_, Exprs2} = lists:unzip(SubRange2),
[{{{FName, FunName, Arity, _}, _, _, _},_}| _] = SubRange2,
VarTab = Tabs#tabs.var_tab,
VarsToExport2 = get_vars_to_export(Exprs2, {FName, FunName, Arity}, VarTab),
%% Exprs from the first member of the clone pair which are going to
%% be replaced by new variables, and the new variables will be exported.
EVs = [E1 || {E1, E2} <- SubSubst, wrangler_syntax:type(E2) == variable,
lists:member({wrangler_syntax:variable_name(E2), get_var_define_pos(E2)},
VarsToExport2)],
%% EVs are variables from Exprs1 that need to be exported.
NumOfNewVars = num_of_new_vars(SubSubst),
[{{SubRange2, EVs, SubSubst},NumOfNewVars}];
false ->
[]
end.
group_clone_pairs(ClonePairs, Thresholds) ->
ClonePairs1=lists:keysort(2,ClonePairs),
group_clone_pairs(ClonePairs1, Thresholds, []).
group_clone_pairs([], _, Acc) ->
lists:reverse(Acc);
group_clone_pairs(ClonePairs, Thresholds, Acc) ->
MinFreq= Thresholds#threshold.min_freq -1,
{NewCs, LeftPairs}=group_clone_pairs(ClonePairs,Thresholds, sets:new(),[],[]),
NewAcc = case length(NewCs)>=MinFreq of
true->[NewCs|Acc];
false ->
Acc
end,
case length(LeftPairs)<MinFreq of
true ->
NewAcc;
false ->
group_clone_pairs(LeftPairs, Thresholds, NewAcc)
end.
group_clone_pairs([], _, _, Acc, LeftPairs) ->
{lists:reverse(Acc), lists:reverse(LeftPairs)};
group_clone_pairs([CP={C={_R, _EVs, Subst}, NumOfNewVars}|T], Thresholds, ExprsToBeGenAcc, Acc, LeftPairs) ->
MaxNewVars = Thresholds#threshold.max_new_vars,
ExprsToBeGen=exprs_to_be_generalised(Subst),
NewExprsToBeGenAcc =sets:union(ExprsToBeGen, ExprsToBeGenAcc),
case sets:size(NewExprsToBeGenAcc)=<MaxNewVars of
true ->
group_clone_pairs(T, Thresholds, NewExprsToBeGenAcc, [C|Acc], LeftPairs);
false ->
case NumOfNewVars>MaxNewVars of
true ->
group_clone_pairs([], Thresholds, ExprsToBeGenAcc, Acc, LeftPairs);
false ->
group_clone_pairs(T, Thresholds, ExprsToBeGenAcc, Acc, [CP|LeftPairs])
end
end.
%% This is not accurate, and will be improved!
exprs_to_be_generalised(SubSt) ->
sets:from_list([wrangler_prettypr:format(wrangler_misc:reset_ann_and_pos(E1))
|| {E1,_E2} <- SubSt, wrangler_syntax:type(E1) /= variable]).
num_of_new_vars(SubSt) ->
length(lists:usort([{wrangler_prettypr:format(wrangler_misc:reset_ann_and_pos(E1)),
wrangler_prettypr:format(wrangler_misc:reset_ann_and_pos(E2))}
|| {E1,E2} <- SubSt, wrangler_syntax:type(E1) /= variable])).
format(Node) ->
wrangler_prettypr:format(wrangler_misc:reset_ann_and_pos(Node)).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%
%% Attach function call to each class member %%
%% %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
attach_fun_call_to_range(RangesWithAST,{AU, Pars}, FromSameFile) ->
RangesWithFunCalls=[generate_fun_call_1(RangeWithAST, AU, FromSameFile)
|| RangeWithAST <- RangesWithAST],
{lists:append(RangesWithFunCalls),{simplify_anti_unifier(AU),Pars}}.
generate_fun_call_1(RangeWithAST, AUForm, FromSameFile) ->
{Range, Exprs} = lists:unzip(RangeWithAST),
AUFunClause=hd(wrangler_syntax:function_clauses(AUForm)),
Pats = wrangler_syntax:clause_patterns(AUFunClause),
AUBody = wrangler_syntax:clause_body(AUFunClause),
try
%% it would be a bug if this does not match.
{true, Subst} =
case length(AUBody) - length(Exprs) of
1 ->
SubAUBody = lists:reverse(tl(lists:reverse(AUBody))),
wrangler_unification:expr_unification_extended(SubAUBody, Exprs);
0 ->
wrangler_unification:expr_unification_extended(AUBody, Exprs)
end,
%% Need to check side-effect here. but it is a bit slow!!!
FunCall=make_fun_call(new_fun, Pats, Subst, FromSameFile),
[{Range, format(FunCall)}]
catch
_E1:_E2 ->
[] %%"wrangler-failed-to-generate-the-function-application."
end.
make_fun_call(FunName, Pats, Subst, FromSameFile) ->
Fun = fun (P) ->
case wrangler_syntax:type(P) of
variable ->
PName = wrangler_syntax:variable_name(P),
case lists:keysearch(PName, 1, Subst) of
{value, {PName, Par}} ->
case wrangler_syntax:type(Par) of
atom ->
case FromSameFile of
true -> Par;
false ->
As = wrangler_syntax:get_ann(Par),
case lists:keysearch(fun_def, 1, As) of
{value, {fun_def, {M, _F, A, _, _}}} ->
case M== erlang orelse M=='_' of
true ->
Par;
false ->
Mod = wrangler_syntax:atom(M),
ModQualifier = wrangler_syntax:module_qualifier(Mod, Par),
wrangler_syntax:implicit_fun(ModQualifier, wrangler_syntax:integer(A))
end;
_ -> Par
end
end;
module_qualifier ->
As = wrangler_syntax:get_ann(Par),
case lists:keysearch(fun_def, 1, As) of
{value, {fun_def, {_M, _F, A, _, _}}} ->
wrangler_syntax:implicit_fun(Par, wrangler_syntax:integer(A));
_ -> Par %% This should not happen!
end;
application ->
wrangler_syntax:fun_expr([wrangler_syntax:clause([], none, [Par])]);
_ -> Par
end;
_ ->
wrangler_syntax:atom(undefined)
end;
underscore ->
wrangler_syntax:atom(undefined);
_ -> P
end
end,
Pars = lists:map(Fun, Pats),
Op = wrangler_syntax:atom(FunName),
wrangler_misc:reset_attrs(wrangler_syntax:application(Op, [P || P <- Pars])).