chiark / gitweb /
i18n: i18n-diff-auditor: fix here doc regexp
[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     # entries contain
126     #   T     type
127     #   E     exact input text (does not contain here doc contents)
128     #   P     something to print in messages
129     #   V     value, only for: heredoc string
130     #   Q     quote characcter, only for: heredoc string
131     for (;;) {
132         s{^\s+}{};
133         if (s{^[\$\@\%]?[_0-9a-zA-Z]+}{}) {
134             push @o, { T => 'ident', E => $&, P => $& };
135         } elsif (s{^\<\<(['"]?)([A-Z_]+)\1}{}) {
136             my ($q,$d) = ($1,$2);
137             $q ||= '"';
138             push @o, { T => 'heredoc', Q => $q, Delim => $d,
139                        E => $&, P => "<<$q$d$q" };
140             s{^
141                 (                 .* \n     )
142                 ( (?: (?! $d \n ) .* \n )*? )
143                           $d         \n
144               }{ $1 }xe or die "missing end of here doc $d\n";
145             $o[$#o]{V} = $2;
146         } elsif (s{^ (["'])( (?: [^\\'"]
147                                | \\ [^"']
148                                | (?! \1 ) [^"]
149                               )*
150                        ) \1 }{}x) {
151             my ($q,$v) = ($1,$2);
152             push @o, { T => 'string', E => $&, P => "$q$q",
153                        Q => $q, V => $v};
154         } elsif (s{^$perlop_re|^\;}{}) {
155             push @o, { T => 'op', E => $&, P => $& };
156         } elsif (s/^[[{(]//) {
157             push @o, { T => 'bra', E => $&, P => $& };
158         } elsif (s/^[]})]//) {
159             push @o, { T => 'ket', E => $&, P => $& };
160         } elsif (s/^( [\$\@\%] )( \{ )//x) {
161             push @o, { T => 'deref', E => $1, P => $1 },
162                      { T => 'bra',   E => $2, P => $2 };
163         } elsif (s/^ [\$\@\%] [^[^{] //x) {
164             push @o, { T => 'specvar', E => $&, P => $& };
165         } elsif (!length) {
166             last;
167         } else {
168             m{^.{0,10}};
169             die "cannot tokenise \`$&'";
170         }
171     }
172     for (my $i=0; $i+2 < @o; $i++) {
173         next unless $o[$i+1]{E} eq '.';
174         my @inputs = @o[$i, $i+2];
175         #print STDERR Dumper(\@inputs);
176         next if grep { !is_string($_) } @inputs;
177         my $q = $inputs[0]{Q};
178         next if grep { $_->{Q} ne $q } @inputs;
179         my $new = { T => 'joinedstrings',
180                     E => (join '.', map { $_->{E} } @inputs),
181                     P => (join '.', map { $_->{P} } @inputs),
182                     V => (join '',  map { $_->{V} } @inputs),
183                     Q => $q,
184                   };
185         @o = (@o[0..$i-1], $new, @o[$i+3..$#o]);
186         $i--; # counteracts $i++
187     }
188     debug $ichunkstart, "semiparsed: ".join ' ', map { $_->{P} } @o;
189     # debug $ichunkstart, "semiparsed V: ".join ' ', map { defined $_->{V} ? ">$_->{V}<" : '-' } @o;
190     return @o;
191 }           
192
193 our @analysed_x;
194 our @analysed_y;
195
196 sub analyse_chunk_core () {
197     die "plain deletion\n" unless defined $after;
198     die "plain insertion\n" unless defined $before;
199     my @xs = semiparse $before;
200     my @ys = semiparse $after;
201     @analysed_x = @analysed_y = ();
202     my $next_something = sub {
203         my ($ary,$anal,$var,$what) = @_;
204         die "ran out of $what\n" unless @$ary;
205         my $r = shift @$ary;
206         push @$anal, $r->{P};
207         $$var = $r;
208     };
209     my ($x,$y);
210     my $next_x = sub { $next_something->(\@xs, \@analysed_x, \$x, 'before'); };
211     my $next_y = sub { $next_something->(\@ys, \@analysed_y, \$y, 'after' ); };
212     our @y_expect_suffix = ();
213     for (;;) {
214         while (my $e = shift @y_expect_suffix) {
215             $next_y->();
216             $y->{E} eq $e
217                 or die "suffix mismatch, expected $e got $y->{E}\n";
218         }
219         last unless @xs or @ys;
220         $next_x->();
221         $next_y->();
222         next if $x->{E} eq $y->{E};
223         next if $x->{E} eq 'sprintf' and $y->{E} eq 'f_';
224         next if $x->{E} eq 'die'     and $y->{E} eq 'confess';
225         if ($y->{E} eq '+'
226             and @ys >= 3
227             and $ys[0]{E} eq '('
228             and is_trans($ys[1])) {
229             $next_y->(); # (
230             $next_y->(); # __ f_ i_
231             @y_expect_suffix = ')';
232         } elsif ($y->{E} eq '('
233             and @ys > 2
234             and is_trans($ys[0])
235             and @analysed_y
236             and (grep { $_ eq $analysed_y[-1] } (qw( => [ { ? : . ),
237                                                  '(', ',') )) {
238             $next_y->(); # __ f_ i_
239             @y_expect_suffix = ')';
240         }
241         my $string_changed;
242         my $ye = $y->{E};
243         if (is_trans($y)) {
244             $next_y->();
245             die "__ on non-string $y->{P}\n"     unless is_string($y);
246             die "__ on was non-string $x->{P}\n" unless is_string($x);
247             if ($y->{Q} ne "'") {
248                 die "var subst in new string\n"
249                     if $y->{V} =~ m{(?<!\\) [\$\@]};
250             }
251             eval {
252                 die "__ string changed\n"       unless $y->{V} eq $x->{V};
253                 die "__ string quote changed\n" unless $y->{Q} eq $x->{Q};
254             };
255             $string_changed = $@;
256         }
257         if ($ye eq '__') {
258             $_ = $y->{V};
259             die "percent $& in __ ' string\n" if m{\%};
260             die $string_changed if length $string_changed;
261             next;
262         }
263         if ($ye eq 'i_') {
264             die $string_changed if length $string_changed;
265             next;
266         }
267         if ($ye eq 'f_') {
268             my $fmt = $y->{V};
269             die "no percent in _f string\n" unless $fmt =~ m{\%};
270             next unless $string_changed;
271             die "f_ old string '-quoted\n" if $x->{Q} ne '"';
272             my $xs = $x->{V};
273             my $exactly = sub {
274                 my ($lit, $what) = @_;
275                 my $xl = substr($xs, 0, length($lit));
276                 if ($xl ne $lit) {
277                     debug $ichunkstart, "not exactly x: ..".qp($xs);
278                     debug $ichunkstart, "not exactly y:   ".qp($lit);
279                     my $next = @ys ? $ys[0]{P} : '(end)';
280                     die "string contents mismatch near $what before $next\n";
281                 }
282                 $xs = substr($xs, length($lit));
283             };
284             for (;;) {
285                 if ($fmt !~ m{\%[^\%]}) {
286                     $exactly->($fmt, '(tail)');
287                     $fmt = '';
288                     die "text deleted from end of string: ".qp($xs)."\n"
289                         if length $xs;
290                     last;
291                 }
292                 $exactly->($`, '(literal)');
293                 $fmt = $';
294                 if ($& eq '%%') { $exactly->('%', '%%'); next; }
295                 elsif ($& ne '%s') { die "unhandled %-subst $&\n"; }
296                 $next_y->();
297                 die "expected comma, got $y->{P}\n" unless $y->{E} eq ',';
298                 if (!length $fmt and
299                     !length $xs and
300                     @xs and
301                     $xs[0]{E} eq '.') {
302                     # X has   "<earlier>" .                <something>
303                     # Y has   "<earlier>%s" [other args] , <something>
304                     $next_x->(); # eat the '.'
305                     next;
306                 }
307                 if ($xs =~ m{^\@}) {
308                     $next_y->();
309                     die "\@... => not string" unless is_string($y);
310                     die "\@... => $y->{P}" if $y->{Q} ne '"';
311                     $exactly->($y->{V}, $y->{P});
312                     next;
313                 }
314                 my $bras = 0;
315                 for (;;) {
316                     if (!$bras and !@ys) {
317                         last;
318                     }
319                     $next_y->();
320                     if (!$bras and
321                         (grep { $y->{E} eq $_ } qw( or xor and not ; :
322                                                     if unless while when )
323                          or $y->{E} eq ','
324                          or $y->{T} eq 'ket'
325                         )) {
326                         # lookahead shows close of containing scope
327                         # or lower precedence operator
328                         unshift @ys, $y;
329                         pop @analysed_y;
330                         last;
331                     }
332                     $xs =~ s{^\s+}{} if $bras;
333                     if (is_string($y) and $y->{Q} eq '"') {
334                         $exactly->($y->{V}, $y->{P});
335                         next;
336                     }
337                     $exactly->($y->{E}, $y->{P});
338                     if ($y->{T} eq 'bra' or $y->{E} eq '?') {
339                         $bras++;
340                     } elsif ($y->{T} eq 'ket' or $y->{E} eq ':') {
341                         die "too many kets at $y->{E}\n" unless $bras;
342                         $bras--;
343                     }
344                 }
345             }
346             next;
347         }
348         die "mismatch $x->{P} => $y->{P}\n";
349     }
350 }
351
352 sub analyse_chunk () {
353     for (;;) {
354         eval { analyse_chunk_core(); };
355         return unless length $@;
356         if ($@ =~ m{^missing end of here doc (\S+)\n}) {
357             # fudge this
358             $before .= "\n$1\n";
359             $after .= "\n$1\n";
360             next;
361         } else {
362             die $@;
363         }
364     }
365 }
366
367 our @report;
368 our $last_filehead = -1;
369
370 sub report_on_hunk () {
371     return unless @report;
372     if ($last_filehead != $ifilehead) {
373         foreach (my $i=$ifilehead; $i<$ifirsthunkhead; $i++) {
374             print $d[$i];
375         }
376         $last_filehead = $ifilehead;
377     }
378     my $dummy_r = { S => (scalar @d)+1, E => (scalar @d)+1 };
379     my $r;
380     for (my $i=$ihunkhead; ; $i++) {
381         for (;;) {
382             $r //= shift @report;
383             $r //= $dummy_r;
384             last if $i < $r->{E};
385             confess unless $r->{Done} == 03;
386             $r = undef;
387         }
388
389         last unless $i<$ihunkend;
390
391         foreach my $ds (@{ $debug[$i] }) {
392             print "# $ds\n";
393         }
394
395         if ($i == $r->{S}) {
396             print "!! $r->{M}";
397             $r->{Done} |= 01;
398         }
399         if ($i >= $r->{S}) {
400             print "!";
401             $r->{Done} |= 02;
402         } else {
403             print " ";
404         }
405         print $d[$i];
406     }
407     confess unless $r = $dummy_r;
408 }
409
410 for ($ifilehead = 0; l_ok $ifilehead; $ifilehead++) {
411     m{^diff} or next;
412     $ifirsthunkhead = $ifilehead;
413     while (l_ok $ifirsthunkhead and
414            m{^diff|^index|^---|^\Q+++\E}) {
415         $ifirsthunkhead++
416     }
417     $ihunkhead = $ifirsthunkhead;
418     while (l_ok $ihunkhead) {
419         m{^\@\@} or confess "$ihunkhead $_ ?";
420         my $i = $ihunkhead + 1;
421         for (; ; $i++) {
422             if (!l_ok $i or m{^ } or m{^\@\@}) {
423                 if (defined $ichunkstart) {
424                     $ichunkend = $i;
425                     eval { analyse_chunk(); 1; };
426                     if (length $@) {
427                         debug $ichunkstart, "done x: @analysed_x";
428                         debug $ichunkstart, "done y: @analysed_y";
429                         push @report, { M => $@,
430                                         S => $ichunkstart,
431                                         E => $ichunkend };
432                     }
433                     $ichunkstart = $ichunkend = $before = $after = undef;
434                 }
435                 l_ok $i or last;
436                 m{^\@\@} and last;
437             } elsif (m{^[-+]}) {
438                 my $which = $& eq '-' ? \$before : \$after;
439                 $ichunkstart //= $i;
440                 $$which //= '';
441                 $$which .= $';
442             } else {
443                 confess "$i $_ ?";
444             }
445         }
446         $ihunkend = $i;
447         report_on_hunk();
448         $ichunkend = $i;
449         $ihunkhead = $i;
450     }
451 }