chiark / gitweb /
i18n: i18n-diff-auditor: Handle comments
[dgit.git] / i18n-diff-auditor
1 #!/usr/bin/perl -w
2 #
3 # i18n-diff-auditor
4 # Copyright (C)2018 Ian Jackson
5 # GPLv3+, NO WARRANTY, see below.
6 #
7 #
8 # Usage:
9 #  something like this
10 #  git-log -n1 -p | ./i18n-diff-auditor -D 2>&1 |less -j10 +/'^!.*'
11 #
12 # -D is for debug.  Currently only one level.
13 #
14 # Output is the relevant diff hunks, with each line prepended with
15 # space for ok lines and ! for questionable ones, and with relevant
16 # diff lines prepended with lines starting !! (and lines starting #
17 # for debug output), so ovrall:
18 #
19 #   !! <message>   reasoning for subsequent questionable diff line(s)
20 #   !+             diff line found to be questionable
21 #   !-             diff line found to be questionable
22 #    @@@ etc.      diff furniture
23 #    +             diff line checked and ok
24 #    -             diff line checked and ok
25 #   # <stuff>      debug output (normally precedes relevant output)
26 #
27 # Changes are generally marked as ok if they correspond to a known
28 # intended code change pattern.  (That includes changing error calls
29 # to different error calls.)  If they don't correspond to any known
30 # pattern, they are "questionable" and the first thing that doesn't
31 # match the most common pattern is reported.
32 #
33 # Might be useful for projects other than dgit, provided it uses
34 # the same gettext aliases (__ f_ i_) and similar error calls
35 # (die, confess, fail).
36 #
37 #
38 # This program is free software: you can redistribute it and/or modify
39 # it under the terms of the GNU General Public License as published by
40 # the Free Software Foundation, either version 3 of the License, or
41 # (at your option) any later version.
42 #
43 # This program is distributed in the hope that it will be useful,
44 # but WITHOUT ANY WARRANTY; without even the implied warranty of
45 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
46 # GNU General Public License for more details.
47 #
48 # You should have received a copy of the GNU General Public License
49 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
50
51 use strict;
52 use Carp;
53 use Data::Dumper;
54 use Getopt::Long;
55
56 our $debug = 0;
57 GetOptions("debug|D+" => \$debug
58            );
59
60 our @debug;
61 sub debug ($$) {
62     my ($i,$s) = @_;
63     push @{ $debug[$i] }, $s if $debug;
64 }
65
66 my @d = <>;
67 unshift @d, "# dummy line to make line 1 index 1 in \@d\n";
68
69 our $i_last_l_ok = -1;
70 our $count_i_last_l_ok;
71
72 sub l_ok ($) {
73     my ($i) = @_;
74
75     if ($i == $i_last_l_ok) {
76         confess $i if $count_i_last_l_ok++ > 50;
77     } else {
78         $count_i_last_l_ok = 0;
79         $i_last_l_ok = $i;
80     }
81
82     return unless $i < @d;
83     $_ = $d[$i];
84     #print STDERR "L $i\n";
85     1;
86 }
87
88 sub l ($) {
89     my ($i) = @_;
90     confess $i unless l_ok $i;
91 };
92
93 our $perlop_text = <<'END'; # c&p from man perlop
94            left        terms and list operators (leftward)
95            left        ->
96            nonassoc    ++ --
97            right       **
98            right       ! ~ \ and unary + and -
99            left        =~ !~
100            left        * / % x
101            left        + - .
102            left        << >>
103            nonassoc    named unary operators
104            nonassoc    < > <= >= lt gt le ge
105            nonassoc    == != <=> eq ne cmp ~~
106            left        &
107            left        | ^
108            left        &&
109            left        || //
110            nonassoc    ..  ...
111            right       ?:
112            right       = += -= *= etc. goto last next redo dump
113            left        , =>
114            nonassoc    list operators (rightward)
115            right       not
116            left        and
117            left        or xor
118
119            **=    +=    *=    &=    &.=    <<=    &&=
120                   -=    /=    |=    |.=    >>=    ||=
121                   .=    %=    ^=    ^.=           //=
122                         x=
123 END
124
125 our $perlop_re;
126
127 sub prep_perlop () {
128     my @ops;
129     foreach (split /\n/, $perlop_text) {
130         next unless m{\S};
131         s{\s+$}{};
132         s{^\s+}{};
133         s{^(?: left | right | nonassoc ) \s+}{}x;
134         next if m{^terms and list operators};
135         next if m{^named unary};
136         next if m{^list operators};
137         s{ and unary.*}{};
138         s{ etc\. }{ };
139         s{\?\:}{ ? : };
140         foreach my $op (split /\s+/) {
141             next unless length $op;
142             next if $op =~ m{^\w+$};
143             $op =~ s/\W/\\$&/g;
144             push @ops, $op;
145         }
146     }
147     $perlop_re = '(?: '.(join ' | ', @ops).' )';
148     $perlop_re = qr{$perlop_re}x;
149     #print STDERR "$perlop_re\n";
150 }
151
152 prep_perlop();
153
154 our ($ifilehead, $ifirsthunkhead);
155 our ($ihunkhead, $ihunkend);
156 our ($ichunkstart, $ichunkend);
157 our ($before, $after);
158
159 sub is_string ($) { $_[0]{T} =~ m/heredoc|string/; }
160 sub is_trans ($) { grep { $_[0]{E} eq $_ } qw(__ f_ i_); }
161
162 sub qp ($) {
163     my ($p) = @_;
164     $p =~ s{\\}{\\\\}g;
165     $p =~ s{\'}{\\'}g;
166     $p =~ s{\n}{\\n}g;
167     $p =~ s{\t}{\\t}g;
168     return "'$p'";
169 };
170
171 sub semiparse ($) {
172     ($_) = @_;
173     my @o;
174     #my $in = $_;
175     # entries contain
176     #   T     type
177     #   E     exact input text (does not contain here doc contents)
178     #   P     something to print in messages
179     #   V     value, only for: heredoc string
180     #   Q     quote characcter, only for: heredoc string
181     for (;;) {
182         s{^\s+}{};
183         if (s{^[\$\@\%]?[_0-9a-zA-Z]+}{}) {
184             push @o, { T => 'ident', E => $&, P => $& };
185         } elsif (s{^\<\<(['"]?)([A-Z_]+)\1}{}) {
186             my ($q,$d) = ($1,$2);
187             $q ||= '"';
188             push @o, { T => 'heredoc', Q => $q, Delim => $d,
189                        E => $&, P => "<<$q$d$q" };
190             if (s{^
191                     (                 .* \n     )
192                     ( (?: (?! $d \n ) .* \n )*? )
193                               $d         \n
194                  }{ $1 }xe) {
195                 $o[$#o]{V} = $2;
196             } else {
197                 m{^.*\n} or confess;
198                 $_ = $&;
199                 $o[$#o]{V} = $';
200                 $o[$#o]{Invented} = 1;
201             }
202         } elsif (s{^ (["'])( (?: [^\\'"]
203                                | \\ [^"']
204                                | (?! \1 ) [^"]
205                               )*
206                        ) \1 }{}x) {
207             my ($q,$v) = ($1,$2);
208             push @o, { T => 'string', E => $&, P => "$q$q",
209                        Q => $q, V => $v};
210         } elsif (s{^$perlop_re|^\;}{}) {
211             push @o, { T => 'op', E => $&, P => $& };
212         } elsif (s/^[[{(]//) {
213             push @o, { T => 'bra', E => $&, P => $& };
214         } elsif (s/^[]})]//) {
215             push @o, { T => 'ket', E => $&, P => $& };
216         } elsif (s/^( [\$\@\%] )( \{ )//x) {
217             push @o, { T => 'deref', E => $1, P => $1 },
218                      { T => 'bra',   E => $2, P => $2 };
219         } elsif (s/^ [\$\@\%] [^[^{] //x) {
220             push @o, { T => 'specvar', E => $&, P => $& };
221         } elsif (!length) {
222             last;
223         } elsif (s{^\#.*\n}{}) {
224         } else {
225             m{^.{0,10}};
226             die "cannot tokenise \`$&'";
227         }
228     }
229     for (my $i=0; $i+2 < @o; $i++) {
230         next unless $o[$i+1]{E} eq '.';
231         my @inputs = @o[$i, $i+2];
232         #print STDERR Dumper(\@inputs);
233         next if grep { !is_string($_) } @inputs;
234         my $q = $inputs[0]{Q};
235         next if grep { $_->{Q} ne $q } @inputs;
236         next if grep { $_->{Invented} } @inputs;
237         my $new = { T => 'joinedstrings',
238                     E => (join '.', map { $_->{E} } @inputs),
239                     P => (join '.', map { $_->{P} } @inputs),
240                     V => (join '',  map { $_->{V} } @inputs),
241                     Q => $q,
242                   };
243         @o = (@o[0..$i-1], $new, @o[$i+3..$#o]);
244         $i--; # counteracts $i++
245     }
246     debug $ichunkstart, "semiparsed: ".join ' ', map { $_->{P} } @o;
247     # debug $ichunkstart, "semiparsed V: ".join ' ', map { defined $_->{V} ? ">$_->{V}<" : '-' } @o;
248     return @o;
249 }           
250
251 our @analysed_x;
252 our @analysed_y;
253
254 sub analyse_chunk_core () {
255     $before //= '';
256     die "plain deletion\n" unless defined $after;
257     my @xs = semiparse $before;
258     my @ys = semiparse $after;
259     @analysed_x = @analysed_y = ();
260     my $next_something = sub {
261         my ($ary,$anal,$var,$what) = @_;
262         die "ran out of $what\n" unless @$ary;
263         my $r = shift @$ary;
264         push @$anal, $r->{P};
265         $$var = $r;
266     };
267     my ($x,$y);
268     my $next_x = sub { $next_something->(\@xs, \@analysed_x, \$x, 'before'); };
269     my $next_y = sub { $next_something->(\@ys, \@analysed_y, \$y, 'after' ); };
270     our @y_expect_suffix = ();
271     for (;;) {
272         while (my $e = shift @y_expect_suffix) {
273             $next_y->();
274             $y->{E} eq $e
275                 or die "suffix mismatch, expected $e got $y->{E}\n";
276         }
277         last unless @xs or @ys;
278         $next_x->();
279         $next_y->();
280         next if $x->{E} eq $y->{E};
281         next if $x->{E} eq 'sprintf' and $y->{E} eq 'f_';
282         next if $x->{E} eq 'die'     and $y->{E} eq 'confess';
283         next if $x->{E} eq 'die'     and $y->{E} eq 'fail';
284         if ($y->{E} eq '+'
285             and @ys >= 3
286             and $ys[0]{E} eq '('
287             and is_trans($ys[1])) {
288             $next_y->(); # (
289             $next_y->(); # __ f_ i_
290             @y_expect_suffix = ')';
291         } elsif ($y->{E} eq '('
292             and @ys > 2
293             and is_trans($ys[0])
294             and @analysed_y
295             and (grep { $_ eq $analysed_y[-1] } (qw( => [ { ? : . ),
296                                                  '(', ',') )) {
297             $next_y->(); # __ f_ i_
298             @y_expect_suffix = ')';
299         }
300         my $string_changed;
301         my $ye = $y->{E};
302         if (is_trans($y)) {
303             $next_y->();
304             die "__ on non-string $y->{P}\n"     unless is_string($y);
305             die "__ on was non-string $x->{P}\n" unless is_string($x);
306             if ($y->{Q} ne "'") {
307                 die "var subst in new string\n"
308                     if $y->{V} =~ m{(?<!\\) [\$\@]};
309             }
310             eval {
311                 die "__ string changed\n"       unless $y->{V} eq $x->{V};
312                 die "__ string quote changed\n" unless $y->{Q} eq $x->{Q};
313             };
314             $string_changed = $@;
315         }
316         if ($ye eq '__') {
317             $_ = $y->{V};
318             die "percent $& in __ ' string\n" if m{\%};
319             die $string_changed if length $string_changed;
320             next;
321         }
322         if ($ye eq 'i_') {
323             die $string_changed if length $string_changed;
324             next;
325         }
326         if ($ye eq 'f_') {
327             my $fmt = $y->{V};
328             die "no percent in f_ string\n" unless $fmt =~ m{\%};
329             next unless $string_changed;
330             die "f_ old string '-quoted\n" if $x->{Q} ne '"';
331             my $xs = $x->{V};
332             my $exactly = sub {
333                 my ($lit, $what) = @_;
334                 my $xl = substr($xs, 0, length($lit));
335                 if ($xl ne $lit) {
336                     debug $ichunkstart, "not exactly x: ..".qp($xs);
337                     debug $ichunkstart, "not exactly y:   ".qp($lit);
338                     my $next = @ys ? $ys[0]{P} : '(end)';
339                     die "string contents mismatch near $what before $next\n";
340                 }
341                 $xs = substr($xs, length($lit));
342             };
343             for (;;) {
344                 #print STDERR Dumper($fmt, $xs, \@xs, @ys);
345                 if ($fmt !~ m{\%[^\%]}) {
346                     $exactly->($fmt, '(tail)');
347                     $fmt = '';
348                     die "text deleted from end of string: ".qp($xs)."\n"
349                         if length $xs;
350                     last;
351                 }
352                 $exactly->($`, '(literal)');
353                 $fmt = $';
354                 if ($& eq '%%') { $exactly->('%', '%%'); next; }
355                 elsif ($& ne '%s') { die "unhandled %-subst $&\n"; }
356                 $next_y->();
357                 die "expected comma, got $y->{P}\n" unless $y->{E} eq ',';
358                 if (!length $fmt and
359                     !length $xs and
360                     @xs and
361                     $xs[0]{E} eq '.') {
362                     # X has   "<earlier>" .                <something>
363                     # Y has   "<earlier>%s" [other args] , <something>
364                     $next_x->(); # eat the '.'
365                     next;
366                 }
367                 if ($xs =~ m{^\@}) {
368                     $next_y->();
369                     die "\@... => not string" unless is_string($y);
370                     die "\@... => $y->{P}" if $y->{Q} ne '"';
371                     $exactly->($y->{V}, $y->{P});
372                     next;
373                 }
374                 my $bras = 0;
375                 for (;;) {
376                     if (!$bras and !@ys) {
377                         last;
378                     }
379                     $next_y->();
380                     if (!$bras and
381                         (grep { $y->{E} eq $_ } qw( or xor and not ; :
382                                                     if unless while when )
383                          or $y->{E} eq ','
384                          or $y->{T} eq 'ket'
385                         )) {
386                         # lookahead shows close of containing scope
387                         # or lower precedence operator
388                         unshift @ys, $y;
389                         pop @analysed_y;
390                         last;
391                     }
392                     $xs =~ s{^\s+}{} if $bras;
393                     if (is_string($y) and $y->{Q} eq '"') {
394                         $exactly->($y->{V}, $y->{P});
395                         next;
396                     }
397                     $exactly->($y->{E}, $y->{P});
398                     if ($y->{T} eq 'bra' or $y->{E} eq '?') {
399                         $bras++;
400                     } elsif ($y->{T} eq 'ket' or $y->{E} eq ':') {
401                         die "too many kets at $y->{E}\n" unless $bras;
402                         $bras--;
403                     }
404                 }
405             }
406             next;
407         }
408         die "mismatch $x->{P} => $y->{P}\n";
409     }
410 }
411
412 sub analyse_chunk () {
413     for (;;) {
414         eval { analyse_chunk_core(); };
415         return unless length $@;
416         if ($@ =~ m{^missing end of here doc (\S+)\n}) {
417             # fudge this
418             # (this never happens now, but in the future we might
419             # want this code again eg to try adding to the chunk)
420             $before .= "\n$1\n";
421             $after .= "\n$1\n";
422             next;
423         } else {
424             die $@;
425         }
426     }
427 }
428
429 our @report;
430 our $last_filehead = -1;
431
432 sub report_on_hunk () {
433     return unless @report;
434     if ($last_filehead != $ifilehead) {
435         foreach (my $i=$ifilehead; $i<$ifirsthunkhead; $i++) {
436             print $d[$i];
437         }
438         $last_filehead = $ifilehead;
439     }
440     my $dummy_r = { S => (scalar @d)+1, E => (scalar @d)+1 };
441     my $r;
442     for (my $i=$ihunkhead; ; $i++) {
443         for (;;) {
444             $r //= shift @report;
445             $r //= $dummy_r;
446             last if $i < $r->{E};
447             confess unless $r->{Done} == 03;
448             $r = undef;
449         }
450
451         last unless $i<$ihunkend;
452
453         foreach my $ds (@{ $debug[$i] }) {
454             print "# $ds\n";
455         }
456
457         if ($i == $r->{S}) {
458             print "!! $r->{M}";
459             $r->{Done} |= 01;
460         }
461         if ($i >= $r->{S}) {
462             print "!";
463             $r->{Done} |= 02;
464         } else {
465             print " ";
466         }
467         print $d[$i];
468     }
469     confess unless $r = $dummy_r;
470 }
471
472 for ($ifilehead = 0; l_ok $ifilehead; $ifilehead++) {
473     m{^diff} or next;
474     $ifirsthunkhead = $ifilehead;
475     while (l_ok $ifirsthunkhead and
476            m{^diff|^index|^---|^\Q+++\E}) {
477         $ifirsthunkhead++
478     }
479     $ihunkhead = $ifirsthunkhead;
480     while (l_ok $ihunkhead) {
481         m{^\@\@} or confess "$ihunkhead $_ ?";
482         my $i = $ihunkhead + 1;
483         for (; ; $i++) {
484             if (!l_ok $i or m{^ } or m{^\@\@}) {
485                 if (defined $ichunkstart) {
486                     $ichunkend = $i;
487                     eval { analyse_chunk(); 1; };
488                     if (length $@) {
489                         debug $ichunkstart, "done x: @analysed_x";
490                         debug $ichunkstart, "done y: @analysed_y";
491                         push @report, { M => $@,
492                                         S => $ichunkstart,
493                                         E => $ichunkend };
494                     }
495                     $ichunkstart = $ichunkend = $before = $after = undef;
496                 }
497                 l_ok $i or last;
498                 m{^\@\@} and last;
499             } elsif (m{^[-+]}) {
500                 my $which = $& eq '-' ? \$before : \$after;
501                 $ichunkstart //= $i;
502                 $$which //= '';
503                 $$which .= $';
504             } else {
505                 confess "$i $_ ?";
506             }
507         }
508         $ihunkend = $i;
509         report_on_hunk();
510         $ichunkend = $i;
511         $ihunkhead = $i;
512     }
513 }