chiark / gitweb /
tests/filter: Print all the diffs, not just the first
[subdirmk.git] / generate
1 #!/usr/bin/perl -w
2 #
3 # subdirmk - &-filter (makefile generation program)
4 #  Copyright 2019 Ian Jackson
5 # SPDX-License-Identifier: LGPL-2.0-or-later
6 #
7 # $(srcdir)/subdirmk/generate [--srcdir=SRCDIR] [--] SUBDIR...
8 #
9 # generates in each subdirectory
10 #     Dir.mk.tmp
11 #     Makefile
12 # and in toplevel
13 #     main.mk.tmp
14
15 use strict;
16 use POSIX;
17
18 print "$0 @ARGV\n" or die $!;
19
20 our $srcdir='.';
21
22 # error handling methods:
23 #
24 # Error in input file, while $err_file and $. set, eg in most of
25 # process_input_mk:
26 #         err "message";
27 #
28 # Other input or usage errors:
29 #         die "subdirmk: $file:$lno: problem\n";
30 #         die "subdirmk: some problem not locatable in that way\n";
31 #
32 # Usage error:
33 #         die "subdirmk $0: explanation of problem\n";
34 #
35 # System call error (not ENOENT) accessing input/output files:
36 #         die "description of problem eg maybe erbing noun: $!\n";
37 #
38 # Bug detedcted in `generate':
39 #         die "internal error (some information)?"; # or similar
40
41 while (@ARGV && $ARGV[0] =~ m/^-/) {
42     $_ = shift @ARGV;
43     last if $_ eq '--';
44     if (s/^--srcdir=//) {
45         $srcdir=$';
46     } else {
47         die "subdirmk $0: unknown option \`$_'\n";
48     }
49 }
50 our @subdirs = @ARGV;
51
52 s{/+$}{} foreach @subdirs;
53
54 our $root = [ '.', [ ], 1 ];
55 # each node is [ 'relative subdir name', \@children, $mentioned ]
56
57 sub build_tree () {
58     foreach my $subdir (@subdirs) {
59         my @path = $subdir eq '.' ? () : split m{/+}, $subdir;
60         my $node = $root;
61         foreach my $d (@path) {
62             my ($c,) = grep { $_->[0] eq $d } @{ $node->[1] };
63             if (!$c) {
64                 $c = [ $d, [ ] ];
65                 push @{ $node->[1] }, $c;
66             }
67             $node = $c;
68         }
69         $node->[2] = 1;
70     }
71 }
72
73 sub target_varname ($$) {
74     my ($var_prefix, $target) = @_;
75     return $var_prefix.'TARGETS'.($target eq 'all' ? '' : "_$target");
76 }
77
78 our $writing_output;
79 our $buffering_output;
80 our %output_files;
81 our %input_files;
82 our @output_makefiles;
83
84 sub close_any_output_file() {
85     return unless defined $writing_output;
86     O->error and die "error writing $writing_output.tmp: $! (?)\n";
87     close O or die "error closing $writing_output.tmp: $!\n";
88     $writing_output = undef;
89 }
90
91 sub oraw {
92     die 'internal error' unless defined $writing_output;
93     print O @_ or die "error writing $writing_output.tmp: $!\n";
94 }
95
96 sub oud { # undoubled
97     if (defined $buffering_output) {
98         $buffering_output .= $_ foreach @_;
99         return;
100     }
101     oraw @_;
102 }
103
104 our $ddbl;
105
106 sub od { # maybe $-doubled
107     if (!$ddbl) {
108         oud @_;
109         return;
110     }
111     foreach (@_) {
112         my $e = $_;
113         $e =~ s{\$}{\$\$}g;
114         oud $e;
115     }
116 }
117
118 sub start_output_file ($) {
119     close_any_output_file();
120     ($writing_output) = @_;
121     die "internal error ($writing_output?)"
122         if $output_files{$writing_output}++;
123     my $tmp = "$writing_output.tmp";
124     open O, ">", $tmp or die "create $tmp: $!\n";
125     oraw "# autogenerated - do not edit\n";
126 }
127
128 sub install_output_files () {
129     close_any_output_file();
130     foreach my $f (sort keys %output_files) {
131         rename "$f.tmp", $f or die "install new $f: $!\n";
132     }
133 }
134
135 sub write_makefile ($$) {
136     my ($dir_prefix,$depth) = @_;
137     #print STDERR "write_makefile @_\n";
138     start_output_file("${dir_prefix}Makefile");
139     my $cd = $depth ? join('/', ('..',) x $depth) : '.';
140     my $suppress_templates=
141         '$(if $(filter-out clean real-clean, $(subdirmk_targets)),,'.
142         ' MAKEFILE_TEMPLATES=)';
143     oraw <<END;
144 default: all
145 \$(filter-out all,\$(MAKECMDGOALS)) all: run-main.mk
146         \@:
147 subdirmk_targets:=\$(or \$(MAKECMDGOALS),all)
148 Makefile run-main.mk:
149         \$(MAKE) -C $cd -f main.mk \$(addprefix ${dir_prefix},\$(subdirmk_targets))$suppress_templates
150 .SUFFIXES:
151 .PHONY: run-main.mk
152 END
153 }
154
155 our %varref;
156
157 our ($dir_prefix, $dir_suffix, $dir_name,
158      $var_prefix, $var_prefix_name);
159
160 sub dir_prefix ($) {
161     my ($path) = @_;
162     join '', map { "$_/" } @$path;
163 }
164
165 sub set_dir_vars ($) {
166     my ($path) = @_;
167     $dir_prefix = dir_prefix($path);
168     $dir_suffix = join '', map { "/$_" } @$path;
169     $dir_name = join '/', @$path ? @$path : '.';
170     $var_prefix_name = join '_', @$path ? @$path : qw(TOP);
171     $var_prefix = "${var_prefix_name}_";
172 }
173
174 our $err_file;
175
176 our @warn_ena_dfl = map { $_ => 1 } qw(
177     local+global
178     single-char-var
179     unknown-warning
180 );
181 our %warn_ena = @warn_ena_dfl;
182
183 our $warned;
184 our %warn_unk;
185
186 sub err ($) {
187     my ($m) = @_;
188     die "subdirmk: ${err_file}:$.: $m\n";
189 }
190
191 sub wrncore ($$) {
192     my ($wk,$m) = @_;
193     return 0 unless $warn_ena{$wk} // warn "internal error $wk ?";
194     $warned++;
195     print STDERR "subdirmk: warning ($wk): $m\n";
196     return 1;
197 }
198
199 sub wrn ($$) {
200     my ($wk,$m) = @_;
201     our %warn_dedupe;
202     return 0 if $warn_dedupe{$err_file,$.,$wk,$m}++;
203     wrncore($wk, "${err_file}:$.: $m");
204 }
205
206 sub ddbl_only ($) {
207     my ($e) = @_;
208     return if $ddbl;
209     err "escape &$e is valid only during \$-doubling";
210 }
211
212 sub process_input_mk ($$$$);
213 sub process_input_mk ($$$$) {
214     my ($targets, $f, $esclitr, $enoent_ok) = @_;
215
216     my $caps_re = qr{[A-Z]};
217     my $lc_re = qr{[a-z]};
218
219     my $esc;
220     my $set_esc = sub {
221         $esc = $$esclitr;
222         $esc =~ s/\W/\\$&/g;
223     };
224     $set_esc->();
225
226     my $input = new IO::File $f, '<';
227     if (!$input) {
228         err "open $f: $!" unless $!==ENOENT && $enoent_ok;
229         return;
230     }
231     $input_files{$f}++;
232
233     local $err_file=$f;
234
235     my %srcdirmap = (
236                   '^' => "\$(top_srcdir)${dir_suffix}",
237                   '~' => "\$(top_srcdir)",
238                     );
239     my %pfxmap = (
240                   ''  => $dir_prefix,
241                  );
242     $pfxmap{$_} = $srcdirmap{$_}.'/' foreach keys %srcdirmap;
243
244     local $ddbl;
245     my @nest = (['']);
246     my $evalcall_brackets;
247
248     my $push_nest = sub {
249         my ($nk, $nndbl, $what) = @_;
250         unshift @nest, [ $nk, $ddbl, $what, $. ];
251         $ddbl = $nndbl;
252     };
253     my $pop_nest = sub {
254         my ($nk) = @_;
255         err "unexpectedly closed $nk in middle of $nest[0][0] ($nest[0][2])"
256             unless $nest[0][0] eq $nk;
257         $ddbl = (shift @nest)[1];
258     };
259
260     # Our detection of variable settings does not have to be completely
261     # accurate, since it is only going to be used for advice to the user.
262     my $note_varref = sub {
263         my ($vn,$amp) = @_;
264         $varref{$vn}{$amp}{"$f:$."} = 1;
265     };
266
267     while (<$input>) {
268         if (m#^\s*($esc)?(\w+)\s*(?:=|\+=|\?=|:=)# ||
269             m#^\s*(?:$esc\:macro|define)\s+($esc)?(\S+)\s#) {
270             $note_varref->($2,!!$1);
271         }
272         if (s#^\s*$esc\:changequote\s+(\S+)\s+$##) {
273             $$esclitr = $1;
274             $set_esc->();
275             next;
276         } elsif (s#^\s*$esc\:endm\s+$##) {
277             $pop_nest->('macro');
278             od "endef\n";
279             next;
280         } elsif (s#^\s*$esc\:warn\s+(\S.*)$##) {
281             foreach my $wk (split /\s+/, $1) {
282                 my $yes = $wk !~ s{^!}{};
283                 if (defined $warn_ena{$wk}) {
284                     $warn_ena{$wk} = $yes;
285                     next;
286                 } elsif ($yes) {
287                     wrn 'unknown-warning',
288                         "unknown warning $wk requested";
289                 } else {
290                     $warn_unk{$wk} //= "$f:$.";
291                 }
292             }
293             next;
294         } elsif (s#^\s*$esc\:local\+global\s+(\S.*)$##) {
295             foreach my $vn (split /\s+/, $1) {
296                 $vn =~ s{^$esc}{};
297                 $varref{$vn}{NoWarn} = 1;
298             }
299             next;
300         } elsif (s#^\s*$esc\:(?=(-?)include|macro)##) {
301             $buffering_output='';
302         } elsif (m#^\s*$esc\:([a-z][-+0-9a-z_]*)#) {
303             err "unknown directive &:$1 or bad argumnt syntax";
304         } elsif (s{^\s*${esc}TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
305             my $t = $1 // 'all';
306             my $vn = target_varname($var_prefix, $t);
307             $note_varref->($vn,1);
308             od $vn;
309             $targets->{$t} //= [ ];
310         }
311         for (;;) {
312             err 'cannot $-double &-processed RHS of directive'
313                 if $ddbl && defined $buffering_output;
314             unless ($nest[0][0] eq 'eval'
315                     ? s{^(.*?)($esc|\$|[{}])}{}
316                     : s{^(.*?)($esc|\$)}{}) { od $_; last; }
317             od $1;
318             if ($2 eq '{') {
319                 od $2;
320                 $evalcall_brackets++;
321                 next;
322             } elsif ($2 eq '}') {
323                 od $2;
324                 next if --$evalcall_brackets;
325                 $pop_nest->('eval');
326                 od '}';
327                 next;
328             } elsif ($2 eq '$') {
329                 od $2;
330                 if (s{^\$}{}) { od $&; }
331                 elsif (m{^[a-zA-Z]\w}) {
332                     wrn 'single-char-var',
333                     'possibly confusing unbracketed single-char $-expansion';
334                 }
335                 elsif (m{^\(($esc)?([^()\$]+)\)} ||
336                        m{^\{($esc)?([^{}\$]+)\}}) {
337                     $note_varref->($2,!!$1);
338                 }
339                 next;
340             }
341             if (s{^\\$esc}{}) { od "$$esclitr" }
342             elsif (s{^\\\$}{}) { oud '$' }
343             elsif (s{^\\\s+$}{}) { }
344             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
345             elsif (m{^(?=$caps_re)}) { od $var_prefix }
346             elsif (s{^\$([A-Za-z]\w+)}{}) {
347                 $note_varref->($1,1);
348                 od "\$(${var_prefix}$1)";
349             }
350             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
351             elsif (s{^_}{}) { od $var_prefix }
352             elsif (s{^=}{}) { od $var_prefix_name }
353             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
354             elsif (s{^\.}{}) { od $dir_name }
355             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
356             elsif (s{^\$\-}{}) { $ddbl=undef; }
357             elsif (s{^\$\+}{}) { $ddbl=1; }
358             elsif (s{^\$\(}{}) {
359                 ddbl_only($&); oud "\$(";
360                 $note_varref->($2,!!$1) if m{^($esc)?([^()\$]+\))};
361             }
362             elsif (s{^\$(\d+)}{}) { ddbl_only($&); oud "\$($1)"; }
363             elsif (s{^\$\{}{}) {
364                 err 'macro invocation cannot be re-$-doubled' if $ddbl;
365                 od '${eval ${call ';
366                 $evalcall_brackets = 1;
367                 $push_nest->('eval',1, '&${...}');
368                 $note_varref->($2,!!$1) if m{^\s*($esc)?([^,{}\$]+)};
369             } elsif (s{^([~^]?)(?=[ \t])}{}) {
370                 my $prefix = $pfxmap{$1} // die "internal error ($1?)";
371                 my $after='';
372                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
373                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
374                 od $_;
375                 $_ = $after;
376             } elsif (s{^\#}{}) {
377                 $_ = '';
378             } elsif (s{^![ \t]+}{}) {
379                 od $_;
380                 $_ = '';
381             } else {
382                 m{^.{0,5}};
383                 err "bad &-escape \`$$esclitr$&'";
384             }
385         }
386         if (defined $buffering_output) {
387             $_=$buffering_output;
388             $buffering_output=undef;
389             if (m#^(-?)include\s+(\S+)\s+$#) {
390                 my $subf = "$srcdir/$2";
391                 process_input_mk($targets, $subf, $esclitr, $1);
392                 od "\n";
393             } elsif (m#^macro\s+(\S+)\s+$#) {
394                 od "define $1\n";
395                 $push_nest->('macro', 1, '&:macro');
396             } else {
397                 err "bad directive argument syntax";
398             }
399         }
400     }
401     die "subdirmk: $f:$nest[0][3]: unclosed $nest[0][0] ($nest[0][2])\n"
402         if $nest[0][0];
403     $input->error and die "read $f: $!\n";
404     close $input or die "close $f: $!\n";
405 }
406
407 sub filter_subdir_mk ($) {
408     my ($targets) = @_;
409
410     #use Data::Dumper;
411     #print STDERR "filter @_\n";
412
413     my $esclit = '&';
414
415     my $pi = sub {
416         my ($f, $enoentok) = @_;
417         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
418     };
419     $pi->("Prefix.sd.mk",           1);
420     $pi->("${dir_prefix}Dir.sd.mk", 0);
421     $pi->("Suffix.sd.mk",           1);
422 }
423
424 sub process_subtree ($$);
425 sub process_subtree ($$) {
426     # => list of targets (in form SUBDIR/)
427     # recursive, children first
428     my ($node, $path) = @_;
429
430     #use Data::Dumper;
431     #print STDERR Dumper(\@_);
432
433     my $dir_prefix = dir_prefix($path);
434     # ^ this is the only var which we need before we come back from
435     #   the recursion.
436
437     push @output_makefiles, "${dir_prefix}Dir.mk";
438     write_makefile($dir_prefix, scalar @$path);
439
440     my %targets = (all => []);
441     foreach my $child (@{ $node->[1] }) {
442         my @childpath = (@$path, $child->[0]);
443         my $child_subdir = join '/', @childpath;
444         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!\n";
445         local %warn_ena = @warn_ena_dfl;
446         push @{ $targets{$_} }, $child_subdir foreach
447             process_subtree($child, \@childpath);
448     }
449
450     set_dir_vars($path);
451     start_output_file("${dir_prefix}Dir.mk.tmp");
452
453     if ($node->[2]) {
454         filter_subdir_mk(\%targets);
455     } else {
456         my $sdmk = "${dir_prefix}Dir.sd.mk";
457         if (stat $sdmk) {
458             die
459  "subdirmk: $sdmk unexpectedly exists (${dir_prefix} not mentioned on subdirmk/generate command line, maybe directory is missing from SUBDIRMK_SUBDIRS)";
460         } elsif ($!==ENOENT) {
461         } else {
462             die "stat $sdmk: $!\n";
463         }
464     }
465
466     oraw "\n";
467
468     my @targets = sort keys %targets;
469     foreach my $target (@targets) {
470         my $target_varname = target_varname($var_prefix, $target);
471         oraw "${dir_prefix}${target}:: \$($target_varname)";
472         foreach my $child_subdir (@{ $targets{$target} }) {
473             oraw " $child_subdir/$target";
474         }
475         oraw "\n";
476     }
477     if (@targets) {
478         oraw ".PHONY:";
479         oraw " ${dir_prefix}${_}" foreach @targets;
480         oraw "\n";
481     }
482
483     return @targets;
484 }
485
486 sub process_final ($) {
487     my ($otargets) = @_;
488     set_dir_vars([]);
489     push @output_makefiles, "Final.mk";
490     start_output_file("Final.mk.tmp");
491     my %ntargets;
492     my $esclit='&';
493     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
494     delete $ntargets{$_} foreach @$otargets;
495     my @ntargets = sort keys %ntargets;
496     die "subdirmk: Final.sd.mk may not introduce new top-level targets".
497         " (@ntargets)\n" if @ntargets;
498 }
499
500 sub process_tree() {
501     my @targets = process_subtree($root, [ ]);
502     process_final(\@targets);
503     start_output_file("main.mk.tmp");
504     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
505         oraw "$v=\@$v@\n";
506     }
507     oraw "SUBDIRMK_MAKEFILES :=\n";
508     oraw "MAKEFILE_TEMPLATES :=\n";
509     foreach my $mf (@output_makefiles) {
510         oraw "SUBDIRMK_MAKEFILES += $mf\n";
511     }
512     foreach my $input (sort keys %input_files) {
513         oraw "MAKEFILE_TEMPLATES += $input\n";
514     }
515     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
516 }
517
518 sub flmap ($) { local ($_) = @_; s{:(\d+)$}{ sprintf ":%10d", $1 }e; $_; }
519
520 sub print_varref_warnings () {
521     foreach my $vn (sort keys %varref) {
522         my $vv = $varref{$vn};
523         next unless $vv->{''} && $vv->{1};
524         next if $vv->{NoWarn};
525         wrncore 'local+global', "saw both $vn and &$vn" or return;
526         foreach my $amp ('', 1) {
527             printf STDERR " saw %s%s at %s\n",
528                 ($amp ? '&' : ''), $vn, $_
529                 foreach
530                 sort { flmap($a) cmp flmap($b) }
531                 keys %{ $vv->{$amp} };
532         }
533     }
534 }
535
536 sub print_warning_warnings () {
537     return unless $warned;
538     foreach my $wk (sort keys %warn_unk) {
539         wrncore 'unknown-warning',
540             "$warn_unk{$wk}: attempt to suppress unknown warning(s) \`$wk'";
541     }
542 }
543
544 build_tree();
545 process_tree();
546 print_varref_warnings();
547 print_warning_warnings();
548 install_output_files();