chiark / gitweb /
13454197c7a4be61f62dddce2f2a57bbe3f29435
[dgit.git] / i18n-diff-auditor
1 #!/usr/bin/perl -w
2 use strict;
3 use Carp;
4 use Data::Dumper;
5 use Getopt::Long;
6
7 our $debug = 0;
8 GetOptions("debug|D+" => \$debug
9            );
10
11 our @debug;
12 sub debug ($$) {
13     my ($i,$s) = @_;
14     push @{ $debug[$i] }, $s if $debug;
15 }
16
17 my @d = <>;
18 unshift @d, "# dummy line to make line 1 index 1 in \@d\n";
19
20 our $i_last_l_ok = -1;
21 our $count_i_last_l_ok;
22
23 sub l_ok ($) {
24     my ($i) = @_;
25
26     if ($i == $i_last_l_ok) {
27         confess $i if $count_i_last_l_ok++ > 50;
28     } else {
29         $count_i_last_l_ok = 0;
30         $i_last_l_ok = $i;
31     }
32
33     return unless $i < @d;
34     $_ = $d[$i];
35     #print STDERR "L $i\n";
36     1;
37 }
38
39 sub l ($) {
40     my ($i) = @_;
41     confess $i unless l_ok $i;
42 };
43
44 our $perlop_text = <<'END'; # c&p from man perlop
45            left        terms and list operators (leftward)
46            left        ->
47            nonassoc    ++ --
48            right       **
49            right       ! ~ \ and unary + and -
50            left        =~ !~
51            left        * / % x
52            left        + - .
53            left        << >>
54            nonassoc    named unary operators
55            nonassoc    < > <= >= lt gt le ge
56            nonassoc    == != <=> eq ne cmp ~~
57            left        &
58            left        | ^
59            left        &&
60            left        || //
61            nonassoc    ..  ...
62            right       ?:
63            right       = += -= *= etc. goto last next redo dump
64            left        , =>
65            nonassoc    list operators (rightward)
66            right       not
67            left        and
68            left        or xor
69
70            **=    +=    *=    &=    &.=    <<=    &&=
71                   -=    /=    |=    |.=    >>=    ||=
72                   .=    %=    ^=    ^.=           //=
73                         x=
74 END
75
76 our $perlop_re;
77
78 sub prep_perlop () {
79     my @ops;
80     foreach (split /\n/, $perlop_text) {
81         next unless m{\S};
82         s{\s+$}{};
83         s{^\s+}{};
84         s{^(?: left | right | nonassoc ) \s+}{}x;
85         next if m{^terms and list operators};
86         next if m{^named unary};
87         next if m{^list operators};
88         s{ and unary.*}{};
89         s{ etc\. }{ };
90         s{\?\:}{ ? : };
91         foreach my $op (split /\s+/) {
92             next unless length $op;
93             next if $op =~ m{^\w+$};
94             $op =~ s/\W/\\$&/g;
95             push @ops, $op;
96         }
97     }
98     $perlop_re = '(?: '.(join ' | ', @ops).' )';
99     $perlop_re = qr{$perlop_re}x;
100     #print STDERR "$perlop_re\n";
101 }
102
103 prep_perlop();
104
105 our ($ifilehead, $ifirsthunkhead);
106 our ($ihunkhead, $ihunkend);
107 our ($ichunkstart, $ichunkend);
108 our ($before, $after);
109
110 sub is_string ($) { $_[0]{T} =~ m/heredoc|string/; }
111 sub is_trans ($) { grep { $_[0]{E} eq $_ } qw(__ f_ i_); }
112
113 sub qp ($) {
114     my ($p) = @_;
115     $p =~ s{\\}{\\\\}g;
116     $p =~ s{\'}{\\'}g;
117     $p =~ s{\n}{\\n}g;
118     $p =~ s{\t}{\\t}g;
119     return "'$p'";
120 };
121
122 sub semiparse ($) {
123     ($_) = @_;
124     my @o;
125     #my $in = $_;
126     # entries contain
127     #   T     type
128     #   E     exact input text (does not contain here doc contents)
129     #   P     something to print in messages
130     #   V     value, only for: heredoc string
131     #   Q     quote characcter, only for: heredoc string
132     for (;;) {
133         s{^\s+}{};
134         if (s{^[\$\@\%]?[_0-9a-zA-Z]+}{}) {
135             push @o, { T => 'ident', E => $&, P => $& };
136         } elsif (s{^\<\<(['"]?)([A-Z_]+)\1}{}) {
137             my ($q,$d) = ($1,$2);
138             $q ||= '"';
139             push @o, { T => 'heredoc', Q => $q, Delim => $d,
140                        E => $&, P => "<<$q$d$q" };
141             if (s{^
142                     (                 .* \n     )
143                     ( (?: (?! $d \n ) .* \n )*? )
144                               $d         \n
145                  }{ $1 }xe) {
146                 $o[$#o]{V} = $2;
147             } else {
148                 s{ \n (.*) }{ \n }s;
149                 $o[$#o]{V} = $1;
150                 $o[$#o]{Invented} = 1;
151             }
152         } elsif (s{^ (["'])( (?: [^\\'"]
153                                | \\ [^"']
154                                | (?! \1 ) [^"]
155                               )*
156                        ) \1 }{}x) {
157             my ($q,$v) = ($1,$2);
158             push @o, { T => 'string', E => $&, P => "$q$q",
159                        Q => $q, V => $v};
160         } elsif (s{^$perlop_re|^\;}{}) {
161             push @o, { T => 'op', E => $&, P => $& };
162         } elsif (s/^[[{(]//) {
163             push @o, { T => 'bra', E => $&, P => $& };
164         } elsif (s/^[]})]//) {
165             push @o, { T => 'ket', E => $&, P => $& };
166         } elsif (s/^( [\$\@\%] )( \{ )//x) {
167             push @o, { T => 'deref', E => $1, P => $1 },
168                      { T => 'bra',   E => $2, P => $2 };
169         } elsif (s/^ [\$\@\%] [^[^{] //x) {
170             push @o, { T => 'specvar', E => $&, P => $& };
171         } elsif (!length) {
172             last;
173         } else {
174             m{^.{0,10}};
175             die "cannot tokenise \`$&'";
176         }
177     }
178     for (my $i=0; $i+2 < @o; $i++) {
179         next unless $o[$i+1]{E} eq '.';
180         my @inputs = @o[$i, $i+2];
181         #print STDERR Dumper(\@inputs);
182         next if grep { !is_string($_) } @inputs;
183         my $q = $inputs[0]{Q};
184         next if grep { $_->{Q} ne $q } @inputs;
185         next if grep { $_->{Invented} } @inputs;
186         my $new = { T => 'joinedstrings',
187                     E => (join '.', map { $_->{E} } @inputs),
188                     P => (join '.', map { $_->{P} } @inputs),
189                     V => (join '',  map { $_->{V} } @inputs),
190                     Q => $q,
191                   };
192         @o = (@o[0..$i-1], $new, @o[$i+3..$#o]);
193         $i--; # counteracts $i++
194     }
195     debug $ichunkstart, "semiparsed: ".join ' ', map { $_->{P} } @o;
196     # debug $ichunkstart, "semiparsed V: ".join ' ', map { defined $_->{V} ? ">$_->{V}<" : '-' } @o;
197     return @o;
198 }           
199
200 our @analysed_x;
201 our @analysed_y;
202
203 sub analyse_chunk_core () {
204     die "plain deletion\n" unless defined $after;
205     die "plain insertion\n" unless defined $before;
206     my @xs = semiparse $before;
207     my @ys = semiparse $after;
208     @analysed_x = @analysed_y = ();
209     my $next_something = sub {
210         my ($ary,$anal,$var,$what) = @_;
211         die "ran out of $what\n" unless @$ary;
212         my $r = shift @$ary;
213         push @$anal, $r->{P};
214         $$var = $r;
215     };
216     my ($x,$y);
217     my $next_x = sub { $next_something->(\@xs, \@analysed_x, \$x, 'before'); };
218     my $next_y = sub { $next_something->(\@ys, \@analysed_y, \$y, 'after' ); };
219     our @y_expect_suffix = ();
220     for (;;) {
221         while (my $e = shift @y_expect_suffix) {
222             $next_y->();
223             $y->{E} eq $e
224                 or die "suffix mismatch, expected $e got $y->{E}\n";
225         }
226         last unless @xs or @ys;
227         $next_x->();
228         $next_y->();
229         next if $x->{E} eq $y->{E};
230         next if $x->{E} eq 'sprintf' and $y->{E} eq 'f_';
231         next if $x->{E} eq 'die'     and $y->{E} eq 'confess';
232         if ($y->{E} eq '+'
233             and @ys >= 3
234             and $ys[0]{E} eq '('
235             and is_trans($ys[1])) {
236             $next_y->(); # (
237             $next_y->(); # __ f_ i_
238             @y_expect_suffix = ')';
239         } elsif ($y->{E} eq '('
240             and @ys > 2
241             and is_trans($ys[0])
242             and @analysed_y
243             and (grep { $_ eq $analysed_y[-1] } (qw( => [ { ? : . ),
244                                                  '(', ',') )) {
245             $next_y->(); # __ f_ i_
246             @y_expect_suffix = ')';
247         }
248         my $string_changed;
249         my $ye = $y->{E};
250         if (is_trans($y)) {
251             $next_y->();
252             die "__ on non-string $y->{P}\n"     unless is_string($y);
253             die "__ on was non-string $x->{P}\n" unless is_string($x);
254             if ($y->{Q} ne "'") {
255                 die "var subst in new string\n"
256                     if $y->{V} =~ m{(?<!\\) [\$\@]};
257             }
258             eval {
259                 die "__ string changed\n"       unless $y->{V} eq $x->{V};
260                 die "__ string quote changed\n" unless $y->{Q} eq $x->{Q};
261             };
262             $string_changed = $@;
263         }
264         if ($ye eq '__') {
265             $_ = $y->{V};
266             die "percent $& in __ ' string\n" if m{\%};
267             die $string_changed if length $string_changed;
268             next;
269         }
270         if ($ye eq 'i_') {
271             die $string_changed if length $string_changed;
272             next;
273         }
274         if ($ye eq 'f_') {
275             my $fmt = $y->{V};
276             die "no percent in _f string\n" unless $fmt =~ m{\%};
277             next unless $string_changed;
278             die "f_ old string '-quoted\n" if $x->{Q} ne '"';
279             my $xs = $x->{V};
280             my $exactly = sub {
281                 my ($lit, $what) = @_;
282                 my $xl = substr($xs, 0, length($lit));
283                 if ($xl ne $lit) {
284                     debug $ichunkstart, "not exactly x: ..".qp($xs);
285                     debug $ichunkstart, "not exactly y:   ".qp($lit);
286                     my $next = @ys ? $ys[0]{P} : '(end)';
287                     die "string contents mismatch near $what before $next\n";
288                 }
289                 $xs = substr($xs, length($lit));
290             };
291             for (;;) {
292                 #print STDERR Dumper($fmt, $xs, \@xs, @ys);
293                 if ($fmt !~ m{\%[^\%]}) {
294                     $exactly->($fmt, '(tail)');
295                     $fmt = '';
296                     die "text deleted from end of string: ".qp($xs)."\n"
297                         if length $xs;
298                     last;
299                 }
300                 $exactly->($`, '(literal)');
301                 $fmt = $';
302                 if ($& eq '%%') { $exactly->('%', '%%'); next; }
303                 elsif ($& ne '%s') { die "unhandled %-subst $&\n"; }
304                 $next_y->();
305                 die "expected comma, got $y->{P}\n" unless $y->{E} eq ',';
306                 if (!length $fmt and
307                     !length $xs and
308                     @xs and
309                     $xs[0]{E} eq '.') {
310                     # X has   "<earlier>" .                <something>
311                     # Y has   "<earlier>%s" [other args] , <something>
312                     $next_x->(); # eat the '.'
313                     next;
314                 }
315                 if ($xs =~ m{^\@}) {
316                     $next_y->();
317                     die "\@... => not string" unless is_string($y);
318                     die "\@... => $y->{P}" if $y->{Q} ne '"';
319                     $exactly->($y->{V}, $y->{P});
320                     next;
321                 }
322                 my $bras = 0;
323                 for (;;) {
324                     if (!$bras and !@ys) {
325                         last;
326                     }
327                     $next_y->();
328                     if (!$bras and
329                         (grep { $y->{E} eq $_ } qw( or xor and not ; :
330                                                     if unless while when )
331                          or $y->{E} eq ','
332                          or $y->{T} eq 'ket'
333                         )) {
334                         # lookahead shows close of containing scope
335                         # or lower precedence operator
336                         unshift @ys, $y;
337                         pop @analysed_y;
338                         last;
339                     }
340                     $xs =~ s{^\s+}{} if $bras;
341                     if (is_string($y) and $y->{Q} eq '"') {
342                         $exactly->($y->{V}, $y->{P});
343                         next;
344                     }
345                     $exactly->($y->{E}, $y->{P});
346                     if ($y->{T} eq 'bra' or $y->{E} eq '?') {
347                         $bras++;
348                     } elsif ($y->{T} eq 'ket' or $y->{E} eq ':') {
349                         die "too many kets at $y->{E}\n" unless $bras;
350                         $bras--;
351                     }
352                 }
353             }
354             next;
355         }
356         die "mismatch $x->{P} => $y->{P}\n";
357     }
358 }
359
360 sub analyse_chunk () {
361     for (;;) {
362         eval { analyse_chunk_core(); };
363         return unless length $@;
364         if ($@ =~ m{^missing end of here doc (\S+)\n}) {
365             # fudge this
366             # (this never happens now, but in the future we might
367             # want this code again eg to try adding to the chunk)
368             $before .= "\n$1\n";
369             $after .= "\n$1\n";
370             next;
371         } else {
372             die $@;
373         }
374     }
375 }
376
377 our @report;
378 our $last_filehead = -1;
379
380 sub report_on_hunk () {
381     return unless @report;
382     if ($last_filehead != $ifilehead) {
383         foreach (my $i=$ifilehead; $i<$ifirsthunkhead; $i++) {
384             print $d[$i];
385         }
386         $last_filehead = $ifilehead;
387     }
388     my $dummy_r = { S => (scalar @d)+1, E => (scalar @d)+1 };
389     my $r;
390     for (my $i=$ihunkhead; ; $i++) {
391         for (;;) {
392             $r //= shift @report;
393             $r //= $dummy_r;
394             last if $i < $r->{E};
395             confess unless $r->{Done} == 03;
396             $r = undef;
397         }
398
399         last unless $i<$ihunkend;
400
401         foreach my $ds (@{ $debug[$i] }) {
402             print "# $ds\n";
403         }
404
405         if ($i == $r->{S}) {
406             print "!! $r->{M}";
407             $r->{Done} |= 01;
408         }
409         if ($i >= $r->{S}) {
410             print "!";
411             $r->{Done} |= 02;
412         } else {
413             print " ";
414         }
415         print $d[$i];
416     }
417     confess unless $r = $dummy_r;
418 }
419
420 for ($ifilehead = 0; l_ok $ifilehead; $ifilehead++) {
421     m{^diff} or next;
422     $ifirsthunkhead = $ifilehead;
423     while (l_ok $ifirsthunkhead and
424            m{^diff|^index|^---|^\Q+++\E}) {
425         $ifirsthunkhead++
426     }
427     $ihunkhead = $ifirsthunkhead;
428     while (l_ok $ihunkhead) {
429         m{^\@\@} or confess "$ihunkhead $_ ?";
430         my $i = $ihunkhead + 1;
431         for (; ; $i++) {
432             if (!l_ok $i or m{^ } or m{^\@\@}) {
433                 if (defined $ichunkstart) {
434                     $ichunkend = $i;
435                     eval { analyse_chunk(); 1; };
436                     if (length $@) {
437                         debug $ichunkstart, "done x: @analysed_x";
438                         debug $ichunkstart, "done y: @analysed_y";
439                         push @report, { M => $@,
440                                         S => $ichunkstart,
441                                         E => $ichunkend };
442                     }
443                     $ichunkstart = $ichunkend = $before = $after = undef;
444                 }
445                 l_ok $i or last;
446                 m{^\@\@} and last;
447             } elsif (m{^[-+]}) {
448                 my $which = $& eq '-' ? \$before : \$after;
449                 $ichunkstart //= $i;
450                 $$which //= '';
451                 $$which .= $';
452             } else {
453                 confess "$i $_ ?";
454             }
455         }
456         $ihunkend = $i;
457         report_on_hunk();
458         $ichunkend = $i;
459         $ihunkhead = $i;
460     }
461 }