/
Diff.pm
1620 lines (1278 loc) · 49.1 KB
/
Diff.pm
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
class Algorithm::Diff {
# # McIlroy-Hunt diff algorithm
# # Adapted from the Smalltalk code of Mario I. Wolczko, <mario@wolczko.com>
# # by Ned Konz, perl@bike-nomad.com
# # Updates by Tye McQueen, http://perlmonks.org/?node=tye
#
# Perl 6 port by Philip Mabon aka: takadonet.
# Additional porting by Stephen Schulze, aka: thundergnat.
# default key generator to use in the most common case:
# comparison of two strings
my &default_keyGen = sub { @_[0] };
# Create a hash that maps each element of @aCollection to the set of
# positions it occupies in @aCollection, restricted to the elements
# within the range of indexes specified by $start and $end.
# The fourth parameter is a subroutine reference that will be called to
# generate a string to use as a key.
#
# my %hash = _withPositionsOfInInterval( @array, $start, $end, &keyGen );
sub _withPositionsOfInInterval( @aCollection, $start, $end, &keyGen )
{
my %d;
for ( $start .. $end ) -> $index
{
my $element = @aCollection[$index];
my $key = &keyGen($element);
if ( %d.exists($key) )
{
%d{$key}.unshift( $index );
}
else
{
%d{$key}[0]=$index;
}
}
return %d;
}
# Find the place at which aValue would normally be inserted into the
# array. If that place is already occupied by aValue, do nothing, and
# return undef. If the place does not exist (i.e., it is off the end of
# the array), add it to the end, otherwise replace the element at that
# point with aValue. It is assumed that the array's values are numeric.
# This is where the bulk (75%) of the time is spent in this module, so
# try to make it fast!
our sub _replaceNextLargerWith( @array is rw, $aValue, $high is copy )
{
$high ||= +@array-1;
# off the end?
if $high == -1 || $aValue > @array[*-1]
{
@array.push($aValue);
return $high + 1;
}
# binary search for insertion point...
my $low = 0;
my $index;
my $found;
while $low <= $high
{
$index = (( $high + $low ) / 2).Int;
$found = @array[$index];
if ( $aValue == $found )
{
return Mu;
}
elsif ( $aValue > $found )
{
$low = $index + 1;
}
else
{
$high = $index - 1;
}
}
# now insertion point is in $low.
@array[$low] = $aValue; # overwrite next larger
return $low;
}
# This method computes the longest common subsequence in @a and @b.
# Result is array whose contents is such that
# @a[ $i ] == @b[ @result[ $i ] ]
# foreach $i in ( 0 .. ^@result ) if @result[ $i ] is defined.
# An additional argument may be passed; this is a hash or key generating
# function that should return a string that uniquely identifies the given
# element. It should be the case that if the key is the same, the elements
# will compare the same. If this parameter is undef or missing, the key
# will be the element as a string.
# By default, comparisons will use "eq" and elements will be turned into keys
# using the default stringizing operator '""'.
# If passed two arrays, trim any leading or trailing common elements, then
# process (&prepare) the second array to a hash and redispatch
our proto sub _longestCommonSubsequence(@a,@b?,%bMatches?,$counting?,&fcn?,%args?) {*}
our multi sub _longestCommonSubsequence(
@a,
@b,
$counting = 0,
&keyGen = &default_keyGen
)
{
my &compare;
if (&keyGen eq &default_keyGen)
{
# most common case - string comparison
&compare = sub ( $a, $b ) { $a eq $b };
}
else
{
&compare = sub ( $a, $b ) { &keyGen( $a ) eq &keyGen( $b ) };
}
my ( $aStart, $aFinish ) = ( 0, +@a-1 );
my ( $bStart, $bFinish ) = ( 0, +@b-1 );
my @matchVector;
my ( $prunedCount, %bMatches ) = ( 0, {} );
# First we prune off any common elements at the beginning
while $aStart <= $aFinish
and $bStart <= $bFinish
and &compare( @a[$aStart], @b[$bStart])
{
@matchVector[ $aStart++ ] = $bStart++;
$prunedCount++;
}
# now the end
while $aStart <= $aFinish
and $bStart <= $bFinish
and &compare( @a[$aFinish], @b[$bFinish] )
{
@matchVector[ $aFinish-- ] = $bFinish--;
$prunedCount++;
}
# Now compute the equivalence classes of positions of elements
%bMatches = _withPositionsOfInInterval( @b, $bStart, $bFinish, &keyGen);
# and redispatch
return _longestCommonSubsequence(
@a,
%bMatches,
$counting,
&keyGen,
PRUNED => $prunedCount,
ASTART => $aStart,
AFINISH => $aFinish,
MATCHVEC => @matchVector
);
}
our multi sub _longestCommonSubsequence(
@a,
%bMatches,
$counting = 0,
&keyGen = &default_keyGen,
:PRUNED( $prunedCount ),
:ASTART( $aStart ) = 0,
:AFINISH( $aFinish ) = +@a-1,
:MATCHVEC( @matchVector ) = []
)
{
my ( @thresh, @links, $ai );
for ( $aStart .. ^$aFinish ) -> $i
{
$ai = &keyGen( @a[$i] );
if ( %bMatches.exists($ai) )
{
my $k;
for @( %bMatches{$ai} ) -> $j
{
# optimization: most of the time this will be true
if ( $k and @thresh[$k] > $j and @thresh[ $k - 1 ] < $j )
{
@thresh[$k] = $j;
}
else
{
$k = _replaceNextLargerWith( @thresh, $j, $k );
}
# oddly, it's faster to always test this (CPU cache?).
# ( still true for perl6? need to test. )
if ( $k.defined )
{
if $k
{
@links[$k] = [ @links[ $k - 1 ] , $i, $j ];
}
else
{
@links[$k] = [ Mu, $i, $j ];
}
}
}
}
}
if ( @thresh )
{
return $prunedCount + @thresh if $counting;
loop ( my $link = @links[+@thresh-1] ; $link ; $link = $link[0] )
{
@matchVector[ $link[1] ] = $link[2];
}
}
elsif ( $counting )
{
return $prunedCount;
}
return @matchVector;
}
sub traverse_sequences(
@a,
@b,
&keyGen = &default_keyGen,
:MATCH( &match ),
:DISCARD_A( &discard_a ),
:DISCARD_B( &discard_b ),
:A_FINISHED( &finished_a ) is copy,
:B_FINISHED( &finished_b ) is copy
) is export
{
my @matchVector = _longestCommonSubsequence( @a, @b, 0, &keyGen );
# Process all the lines in @matchVector
my ( $lastA, $lastB, $bi ) = ( +@a-1, +@b-1, 0 );
my $ai;
loop ( $ai = 0 ; $ai < +@matchVector ; $ai++ )
{
my $bLine = @matchVector[$ai];
if $bLine.defined # matched
{
&discard_b( $ai, $bi++ ) while $bi < $bLine;
&match( $ai, $bi++ );
}
else
{
&discard_a( $ai, $bi);
}
}
# The last entry (if any) processed was a match.
# $ai and $bi point just past the last matching lines in their sequences.
while $ai <= $lastA or $bi <= $lastB
{
# last A?
if $ai == $lastA + 1 and $bi <= $lastB
{
if ( &finished_a.defined )
{
&finished_a( $lastA );
&finished_a = sub {};
}
else
{
&discard_b( $ai, $bi++ ) while $bi <= $lastB;
}
}
# last B?
if ( $bi == $lastB + 1 and $ai <= $lastA )
{
if ( &finished_b.defined )
{
&finished_b( $lastB );
&finished_b = sub {};
}
else
{
&discard_a( $ai++, $bi ) while $ai <= $lastA;
}
}
&discard_a( $ai++, $bi ) if $ai <= $lastA;
&discard_b( $ai, $bi++ ) if $bi <= $lastB;
}
return 1;
}
sub traverse_balanced(
@a,
@b,
&keyGen = &default_keyGen,
:MATCH( &match ),
:DISCARD_A( &discard_a ),
:DISCARD_B( &discard_b ),
:CHANGE( &change )
) is export
{
my @matchVector = _longestCommonSubsequence( @a, @b, 0, &keyGen );
# Process all the lines in match vector
my ( $lastA, $lastB ) = ( +@a-1, +@b-1);
my ( $bi, $ai, $ma ) = ( 0, 0, -1 );
my $mb;
while ( 1 )
{
# Find next match indices $ma and $mb
repeat {
$ma++;
} while
$ma < +@matchVector
&& !(@matchVector[$ma].defined);
last if $ma >= +@matchVector; # end of matchVector?
$mb = @matchVector[$ma];
# Proceed with discard a/b or change events until
# next match
while $ai < $ma || $bi < $mb
{
if $ai < $ma && $bi < $mb
{
# Change
if ( &change.defined )
{
&change( $ai++, $bi++);
}
else
{
&discard_a( $ai++, $bi);
&discard_b( $ai, $bi++);
}
}
elsif $ai < $ma
{
&discard_a( $ai++, $bi);
}
else
{
# $bi < $mb
&discard_b( $ai, $bi++);
}
}
# Match
&match( $ai++, $bi++ );
}
while $ai <= $lastA || $bi <= $lastB
{
if $ai <= $lastA && $bi <= $lastB
{
# Change
if &change.defined
{
&change( $ai++, $bi++);
}
else
{
&discard_a( $ai++, $bi);
&discard_b( $ai, $bi++);
}
}
elsif $ai <= $lastA
{
&discard_a( $ai++, $bi);
}
else
{
# $bi <= $lastB
&discard_b( $ai, $bi++);
}
}
return 1;
}
sub prepare ( @a, &keyGen = &default_keyGen ) is export
{
return _withPositionsOfInInterval( @a, 0, +@a-1, &keyGen );
}
multi sub LCS( %b, @a, &keyGen = &default_keyGen ) is export
{ # rearrange args and re-dispatch
return LCS( @a, %b, &keyGen )
}
multi sub LCS( @a, @b, &keyGen = &default_keyGen ) is export
{
my @matchVector = _longestCommonSubsequence( @a, @b, 0, &keyGen);
return @a[(^@matchVector).grep: { @matchVector[$^a].defined }];
}
multi sub LCS( @a, %b, &keyGen = &default_keyGen ) is export
{
my @matchVector = _longestCommonSubsequence( @a, %b, 0, &keyGen);
return @a[(^@matchVector).grep: { @matchVector[$^a].defined }];
}
sub LCS_length( @a, @b, &keyGen = &default_keyGen ) is export
{
return _longestCommonSubsequence( @a, @b, 1, &keyGen );
}
sub LCSidx( @a, @b, &keyGen = &default_keyGen ) is export
{
my @match = _longestCommonSubsequence( @a, @b, 0, &keyGen );
my $amatch_indices = (^@match).grep: { @match[$^a].defined };
my $bmatch_indices = @match[$amatch_indices];
# return list references, @arrays will flatten
return ($amatch_indices, $bmatch_indices);
}
sub compact_diff( @a, @b, &keyGen = &default_keyGen ) is export
{
my ( $am, $bm ) = LCSidx( @a, @b, &keyGen );
my @cdiff;
my ( $ai, $bi ) = ( 0, 0 );
push @cdiff, $ai, $bi;
while ( 1 )
{
while ( $am && $ai == $am.[0] && $bi == $bm.[0] )
{
shift $am;
shift $bm;
++$ai, ++$bi;
}
push @cdiff, $ai, $bi;
last if !$am;
$ai = $am.[0];
$bi = $bm.[0];
push @cdiff, $ai, $bi;
}
push @cdiff, +@a, +@b
if $ai < @a || $bi < @b;
return @cdiff;
}
sub diff( @a, @b ) is export
{
my ( @retval, @hunk );
traverse_sequences(
@a, @b,
MATCH => sub ($x,$y) { @retval.push( @hunk ); @hunk = () },
DISCARD_A => sub ($x,$y) { @hunk.push( [ '-', $x, @a[ $x ] ] ) },
DISCARD_B => sub ($x,$y) { @hunk.push( [ '+', $y, @b[ $y ] ] ) }
);
return @retval, @hunk;
}
sub sdiff( @a, @b ) is export
{
my @retval;
traverse_balanced(
@a, @b,
MATCH => sub ($x,$y) { @retval.push( [ 'u', @a[ $x ], @b[ $y ] ] ) },
DISCARD_A => sub ($x,$y) { @retval.push( [ '-', @a[ $x ], '' ] ) },
DISCARD_B => sub ($x,$y) { @retval.push( [ '+', '' , @b[ $y ] ] ) },
CHANGE => sub ($x,$y) { @retval.push( [ 'c', @a[ $x ], @b[ $y ] ] ) }
);
return @retval;
}
#############################################################################
# Object Interface
#
has @_Idx is rw; # Array of hunk indices
has @_Seq is rw; # First , Second sequence
has $_End is rw; # Diff between forward and reverse pos
has $_Same is rw; # 1 if pos 1 contains unchanged items
has $_Base is rw; # Added to range's min and max
has $_Pos is rw; # Which hunk is currently selected
has $_Off is rw; # Offset into _Idx for current position
has $_Min = -2; # Added to _Off to get min instead of max+1
method new ( @seq1, @seq2, &keyGen = &default_keyGen ) {
my @cdif = &compact_diff( @seq1, @seq2, &keyGen );
my $same = 1;
if ( 0 == @cdif[2] && 0 == @cdif[3] ) {
$same = 0;
@cdif.splice( 0, 2 );
}
my $object = Algorithm::Diff.bless(*,
:_Idx( @cdif ),
:_Seq( '', [@seq1], [@seq2] ),
:_End( ((1 + @cdif ) / 2).Int ),
:_Same( $same ),
:_Base( 0 ),
:_Pos( 0 ),
:_Off( 0 ),
);
return $object;
}
# sanity check to make sure Pos index is a defined & non-zero.
method _ChkPos {
return if $_Pos;
die( "Method illegal on a \"Reset\" Diff object" );
}
# increment Pos index pointer; default: +1, or passed parameter.
method Next ($steps? is copy ) {
$steps = 1 if !$steps.defined;
if $steps {
my $pos = $_Pos;
my $new = $pos + $steps;
$new = 0 if ($pos and $new) < 0;
self.Reset( $new );
}
return $_Pos;
}
# inverse of Next.
method Prev ( $steps? is copy ) {
$steps = 1 if !$steps.defined;
my $pos = self.Next( -$steps );
$pos -= $_End if $pos;
return $pos;
}
# set the Pos pointer to passed index or 0 if none passed.
method Reset ( $pos? is copy ) {
$pos = 0 if !$pos.defined;
$pos += $_End if $pos < 0;
$pos = 0 if $pos < 0 || $_End <= $pos;
$_Pos = $pos // 0;
$_Off = 2 * $pos - 1;
return self;
}
# make sure a valid hunk is at the sequence/offset.
method _ChkSeq ( $seq ) {
return $seq + $_Off if 1 == $seq || 2 == $seq;
die( "Invalid sequence number ($seq); must be 1 or 2" );
}
# Change indexing base to the passed parameter (0 or 1 typically).
method Base ( $base? ) {
my $oldBase = $_Base;
$_Base = 0 + $base if $base.defined ;
return $oldBase;
}
# Generate a new Diff object bassed on an existing one.
method Copy ( $pos?, $base? ) {
my $you = self.clone;
$you.Reset( $pos ) if $pos.defined ;
$you.Base( $base );
return $you;
}
# returns the index of the first item in a given hunk.
method Min ( $seq, $base? is copy ) {
self._ChkPos;
my $off = self._ChkSeq( $seq );
$base = $_Base if !$base.defined;
return $base + @_Idx[ $off + $_Min ];
}
# returns the index of the last item in a given hunk.
method Max ( $seq, $base? is copy ) {
self._ChkPos;
my $off = self._ChkSeq( $seq );
$base = $_Base if !$base.defined;
return $base + @_Idx[ $off ] - 1;
}
# returns the indicies of the items in a given hunk.
method Range ( $seq, $base? is copy ) {
self._ChkPos;
my $off = self._ChkSeq( $seq );
$base = $_Base if !$base.defined;
return ( $base + @_Idx[ $off + $_Min ] )
.. ( $base + @_Idx[ $off ] - 1 );
}
# returns the items in a given hunk.
method Items ( $seq ) {
self._ChkPos;
my $off = self._ChkSeq( $seq );
return @_Seq[$seq][@_Idx[ $off + $_Min ] .. @_Idx[ $off ] - 1 ];
}
# returns a bit mask representing the operations to change the current
# hunk from seq2 to seq1.
# 0 - no change
# 1 - delete items from sequence 1
# 2 - insert items from sequence 2
# 3 - replace items from sequence 1 with those from sequence 2
method Diff {
self._ChkPos;
return 0 if $_Same == ( 1 +& $_Pos );
my $ret = 0;
my $off = $_Off;
for ( 1, 2 ) -> $seq {
$ret +|= $seq
if @_Idx[ $off + $seq + $_Min ]
< @_Idx[ $off + $seq ];
}
return $ret;
}
# returns the items in the current hunk if they are equivalent
# or an empty list if not.
method Same {
self._ChkPos;
return () if $_Same != ( 1 +& $_Pos );
return self.Items(1);
}
} # end Algorithm::Diff
# ############################################################################
# Unported perl 5 object methods. Everything below except Die is to support Get
# with its extensive symbol table mangling. It's not worth the aggravation.
# sub Die
# {
# require Carp;
# Carp::confess( @_ );
# }
# sub getObjPkg
# {
# my( $us )= @_;
# return ref $us if ref $us;
# return $us . "::_obj";
# }
# my %getName;
# BEGIN {
# %getName= (
# same => \&Same,
# diff => \&Diff,
# base => \&Base,
# min => \&Min,
# max => \&Max,
# range=> \&Range,
# items=> \&Items, # same thing
# );
# }
# sub Get
# {
# my $me= shift @_;
# $me->_ChkPos();
# my @value;
# for my $arg ( @_ ) {
# for my $word ( split ' ', $arg ) {
# my $meth;
# if( $word !~ /^(-?\d+)?([a-zA-Z]+)([12])?$/
# || not $meth= $getName{ lc $2 }
# ) {
# Die( $Root, ", Get: Invalid request ($word)" );
# }
# my( $base, $name, $seq )= ( $1, $2, $3 );
# push @value, scalar(
# 4 == length($name)
# ? $meth->( $me )
# : $meth->( $me, $seq, $base )
# );
# }
# }
# if( wantarray ) {
# return @value;
# } elsif( 1 == @value ) {
# return $value[0];
# }
# Die( 0+@value, " values requested from ",
# $Root, "'s Get in scalar context" );
# }
# my $Obj= getObjPkg($Root);
# no strict 'refs';
# for my $meth ( qw( new getObjPkg ) ) {
# *{$Root."::".$meth} = \&{$meth};
# *{$Obj ."::".$meth} = \&{$meth};
# }
# for my $meth ( qw(
# Next Prev Reset Copy Base Diff
# Same Items Range Min Max Get
# _ChkPos _ChkSeq
# ) ) {
# *{$Obj."::".$meth} = \&{$meth};
# }
#############################################################
=begin pod
=head1 NAME
Algorithm::Diff - Compute `intelligent' differences between two files / lists
=head1 SYNOPSIS
require Algorithm::Diff;
# This example produces traditional 'diff' output:
my $diff = Algorithm::Diff.new( @seq1, @seq2 );
$diff.Base( 1 ); # Return line numbers, not indices
while( $diff.Next() ) {
next if $diff.Same();
my $sep = '';
if( ! $diff.Items(2) ) {
printf "%d,%dd%d\n",
$diff.Min(1), $diff.Max(1), $diff.Max(2);
} elsif( ! $diff.Items(1) ) {
printf "%da%d,%d\n",
$diff.Min(1), $diff.Max(1), $diff.Max(2);
} else {
$sep = "---\n";
printf "%d,%dc%d,%d\n",
$diff.Min(1), $diff.Max(1), $diff.Min(2), $diff.Max(2);
}
print "< $_" for $diff.Items(1);
print $sep;
print "> $_" for $diff.Items(2);
}
# Alternate interfaces:
use Algorithm::Diff;
@lcs = LCS( @seq1, @seq2 );
$count = LCS_length( @seq1, @seq2 );
( $seq1idxlist, $seq2idxlist ) = LCSidx( @seq1, @seq2 );
# Complicated interfaces:
@diffs = diff( @seq1, @seq2 );
@sdiffs = sdiff( @seq1, @seq2 );
@cdiffs = compact_diff( @seq1, @seq2 );
traverse_sequences(
@seq1,
@seq2,
MATCH => &callback1,
DISCARD_A => &callback2,
DISCARD_B => &callback3,
&key_generator,
);
traverse_balanced(
@seq1,
@seq2,
MATCH => &callback1,
DISCARD_A => &callback2,
DISCARD_B => &callback3,
CHANGE => &callback4,
&key_generator,
);
=head1 INTRODUCTION
(by Mark-Jason Dominus)
I once read an article written by the authors of C<diff>; they said
that they worked very hard on the algorithm until they found the
right one.
I think what they ended up using (and I hope someone will correct me,
because I am not very confident about this) was the `longest common
subsequence' method. In the LCS problem, you have two sequences of
items:
a b c d f g h j q z
a b c d e f g i j k r x y z
and you want to find the longest sequence of items that is present in
both original sequences in the same order. That is, you want to find
a new sequence I<S> which can be obtained from the first sequence by
deleting some items, and from the secend sequence by deleting other
items. You also want I<S> to be as long as possible. In this case I<S>
is
a b c d f g j z
From there it's only a small step to get diff-like output:
e h i k q r x y
+ - + + - + + +
This module solves the LCS problem. It also includes a canned function
to generate C<diff>-like output.
It might seem from the example above that the LCS of two sequences is
always pretty obvious, but that's not always the case, especially when
the two sequences have many repeated elements. For example, consider
a x b y c z p d q
a b c a x b y c z
A naive approach might start by matching up the C<a> and C<b> that
appear at the beginning of each sequence, like this:
a x b y c z p d q
a b c a b y c z
This finds the common subsequence C<a b c z>. But actually, the LCS
is C<a x b y c z>:
a x b y c z p d q
a b c a x b y c z
or
a x b y c z p d q
a b c a x b y c z
=head1 USAGE
(See also the README file and several example
scripts include with this module.)
This module now provides an object-oriented interface that uses less
memory and is easier to use than most of the previous procedural
interfaces. It also still provides several exportable functions. We'll
deal with these in ascending order of difficulty: C<LCS>,
C<LCS_length>, C<LCSidx>, OO interface, C<prepare>, C<diff>, C<sdiff>,
C<traverse_sequences>, and C<traverse_balanced>.
=head2 C<LCS>
Given two lists of items, LCS returns an array containing
their longest common subsequence.
@lcs = LCS( @seq1, @seq2 );
C<LCS> may be passed an optional third parameter; this is a CODE
reference to a key generation function. See L</KEY GENERATION
FUNCTIONS>.
@lcs = LCS( @seq1, @seq2, $keyGen );
=head2 C<LCS_length>
This is just like C<LCS> except it only returns the length of the
longest common subsequence. This provides a performance gain of about
9% compared to C<LCS>.
=head2 C<LCSidx>
Like C<LCS> except it returns references to two lists. The first list
contains the indices into @seq1 where the LCS items are located. The
second list contains the indices into @seq2 where the LCS items are located.
Therefore, the following three lists will contain the same values:
my( $idx1, $idx2 ) = LCSidx( @seq1, @seq2 );
my @list1 = @seq1[ $idx1 ];
my @list2 = @seq2[ $idx2 ];
my @list3 = LCS( @seq1, @seq2 );
head2 C<new>
$diff = Algorithm::Diffs.new( @seq1, @seq2 );
$diff = Algorithm::Diffs.new( @seq1, @seq2, &keyGen );
C<new> computes the smallest set of additions and deletions necessary
to turn the first sequence into the second and compactly records them
in the object.
You use the object to iterate over I<hunks>, where each hunk represents
a contiguous section of items which should be added, deleted, replaced,
or left unchanged.
=over 4
The following summary of all of the methods looks a lot like Perl code
but some of the symbols have different meanings:
[ ] Encloses optional arguments
: Is followed by the default value for an optional argument
| Separates alternate return results
Method summary:
$obj = Algorithm::Diff.new( @seq1, @seq2, [ &keyGen ] );
$pos = $obj.Next( [ $count : 1 ] );
$revPos = $obj.Prev( [ $count : 1 ] );
$obj = $obj.Reset( [ $pos : 0 ] );
$copy = $obj.Copy( [ $pos, [ $newBase ] ] );
$oldBase = $obj.Base( [ $newBase ] );
Note that all of the following methods C<die> if used on an object that
is "reset" (not currently pointing at any hunk).
$bits = $obj.Diff( );
@items = $obj.Same( );
@items = $obj.Items( $seqNum );
@idxs = $obj.Range( $seqNum, [ $base ] );
$minIdx = $obj.Min( $seqNum, [ $base ] );
$maxIdx = $obj.Max( $seqNum, [ $base ] );
@values = $obj.Get( @names );
Passing in an undefined value for an optional argument is always treated the
same as if no argument were passed in.
=item C<Next>
$pos = $diff.Next(); # Move forward 1 hunk
$pos = $diff.Next( 2 ); # Move forward 2 hunks
$pos = $diff.Next(-5); # Move backward 5 hunks
C<Next> moves the object to point at the next hunk. The object starts
out "reset", which means it isn't pointing at any hunk. If the object
is reset, then C<Next()> moves to the first hunk.
C<Next> returns a true value iff the move didn't go past the last hunk.
So C<Next(0)> will return true iff the object is not reset.
Actually, C<Next> returns the object's new position, which is a number
between 1 and the number of hunks (inclusive), or returns a false value.
=item C<Prev>
C<Prev($N)> is almost identical to C<Next(-$N)>; it moves to the $Nth
previous hunk. On a 'reset' object, C<Prev()> [and C<Next(-1)>] move
to the last hunk.
The position returned by C<Prev> is relative to the I<end> of the
hunks; -1 for the last hunk, -2 for the second-to-last, etc.
=item C<Reset>
$diff.Reset(); # Reset the object's position
$diff.Reset($pos); # Move to the specified hunk
$diff.Reset(1); # Move to the first hunk
$diff.Reset(-1); # Move to the last hunk
C<Reset> returns the object, so, for example, you could use
C<< $diff.Reset().Next(-1) >> to get the number of hunks.
=item C<Copy>
$copy = $diff.Copy( $newPos, $newBase );
C<Copy> returns a copy of the object. The copy and the orignal object
share most of their data, so making copies takes very little memory.
The copy maintains its own position (separate from the original), which
is the main purpose of copies. It also maintains its own base.
By default, the copy's position starts out the same as the original
object's position. But C<Copy> takes an optional first argument to set the
new position, so the following three snippets are equivalent:
$copy = $diff.Copy($pos);
$copy = $diff.Copy();
$copy.Reset($pos);
$copy = $diff.Copy().Reset($pos);
C<Copy> takes an optional second argument to set the base for
the copy. If you wish to change the base of the copy but leave
the position the same as in the original, here are two
equivalent ways:
$copy = $diff.Copy();
$copy.Base( 0 );