chiark / gitweb /
tests/filter/check: Capture generate's stderr
[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 ($dir_prefix, $dir_suffix, $dir_name,
156      $var_prefix, $var_prefix_name);
157
158 sub dir_prefix ($) {
159     my ($path) = @_;
160     join '', map { "$_/" } @$path;
161 }
162
163 sub set_dir_vars ($) {
164     my ($path) = @_;
165     $dir_prefix = dir_prefix($path);
166     $dir_suffix = join '', map { "/$_" } @$path;
167     $dir_name = join '/', @$path ? @$path : '.';
168     $var_prefix_name = join '_', @$path ? @$path : qw(TOP);
169     $var_prefix = "${var_prefix_name}_";
170 }
171
172 our $err_file;
173
174 sub err ($) {
175     my ($m) = @_;
176     die "subdirmk: ${err_file}:$.: $m\n";
177 }
178
179 sub ddbl_only ($) {
180     my ($e) = @_;
181     return if $ddbl;
182     err "escape &$e is valid only during \$-doubling";
183 }
184
185 sub process_input_mk ($$$$);
186 sub process_input_mk ($$$$) {
187     my ($targets, $f, $esclitr, $enoent_ok) = @_;
188
189     my $caps_re = qr{[A-Z]};
190     my $lc_re = qr{[a-z]};
191
192     my $esc;
193     my $set_esc = sub {
194         $esc = $$esclitr;
195         $esc =~ s/\W/\\$&/g;
196     };
197     $set_esc->();
198
199     my $input = new IO::File $f, '<';
200     if (!$input) {
201         err "open $f: $!" unless $!==ENOENT && $enoent_ok;
202         return;
203     }
204     $input_files{$f}++;
205
206     local $err_file=$f;
207
208     my %srcdirmap = (
209                   '^' => "\$(top_srcdir)${dir_suffix}",
210                   '~' => "\$(top_srcdir)",
211                     );
212     my %pfxmap = (
213                   ''  => $dir_prefix,
214                  );
215     $pfxmap{$_} = $srcdirmap{$_}.'/' foreach keys %srcdirmap;
216
217     local $ddbl;
218     my @nest = (['']);
219     my $evalcall_brackets;
220
221     my $push_nest = sub {
222         my ($nk, $nndbl, $what) = @_;
223         unshift @nest, [ $nk, $ddbl, $what, $. ];
224         $ddbl = $nndbl;
225     };
226     my $pop_nest = sub {
227         my ($nk) = @_;
228         err "unexpectedly closed $nk in middle of $nest[0][0] ($nest[0][2])"
229             unless $nest[0][0] eq $nk;
230         $ddbl = (shift @nest)[1];
231     };
232
233     while (<$input>) {
234         if (s#^\s*$esc\:changequote\s+(\S+)\s+$##) {
235             $$esclitr = $1;
236             $set_esc->();
237             next;
238         } elsif (s#^\s*$esc\:endm\s+$##) {
239             $pop_nest->('macro');
240             od "endef\n";
241             next;
242         } elsif (s#^\s*$esc\:(?=(-?)include|macro)##) {
243             $buffering_output='';
244         } elsif (m#^\s*$esc\:([a-z][-0-9a-z_]*)#) {
245             err "unknown directive &:$1 or bad argumnt syntax";
246         } elsif (s{^\s*${esc}TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
247             my $t = $1 // 'all';
248             od target_varname($var_prefix, $t);
249             $targets->{$t} //= [ ];
250         }
251         for (;;) {
252             err 'cannot $-double &-processed RHS of directive'
253                 if $ddbl && defined $buffering_output;
254             unless ($nest[0][0] eq 'eval'
255                     ? s{^(.*?)($esc|[{}])}{}
256                     : s{^(.*?)($esc)}{}) { od $_; last; }
257             od $1;
258             if ($2 eq '{') {
259                 od $2;
260                 $evalcall_brackets++;
261                 next;
262             } elsif ($2 eq '}') {
263                 od $2;
264                 next if --$evalcall_brackets;
265                 $pop_nest->('eval');
266                 od '}';
267                 next;
268             }
269             if (s{^\\$esc}{}) { od "$$esclitr" }
270             elsif (s{^\\\$}{}) { oud '$' }
271             elsif (s{^\\\s+$}{}) { }
272             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
273             elsif (m{^(?=$caps_re)}) { od $var_prefix }
274             elsif (s{^\$([A-Za-z]\w+)}{}) { od "\$(${var_prefix}$1)" }
275             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
276             elsif (s{^_}{}) { od $var_prefix }
277             elsif (s{^=}{}) { od $var_prefix_name }
278             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
279             elsif (s{^\.}{}) { od $dir_name }
280             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
281             elsif (s{^\$\-}{}) { $ddbl=undef; }
282             elsif (s{^\$\+}{}) { $ddbl=1; }
283             elsif (s{^\$\(}{}) { ddbl_only($&); oud "\$("; }
284             elsif (s{^\$(\d+)}{}) { ddbl_only($&); oud "\$($1)"; }
285             elsif (s{^\$\{}{}) {
286                 err 'macro invocation cannot be re-$-doubled' if $ddbl;
287                 od '${eval ${call ';
288                 $evalcall_brackets = 1;
289                 $push_nest->('eval',1, '&${...}');
290             } elsif (s{^([~^]?)(?=[ \t])}{}) {
291                 my $prefix = $pfxmap{$1} // die "internal error ($1?)";
292                 my $after='';
293                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
294                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
295                 od $_;
296                 $_ = $after;
297             } elsif (s{^\#}{}) {
298                 $_ = '';
299             } elsif (s{^![ \t]+}{}) {
300                 od $_;
301                 $_ = '';
302             } else {
303                 m{^.{0,5}};
304                 err "bad &-escape \`$$esclitr$&'";
305             }
306         }
307         if (defined $buffering_output) {
308             $_=$buffering_output;
309             $buffering_output=undef;
310             if (m#^(-?)include\s+(\S+)\s+$#) {
311                 my $subf = "$srcdir/$2";
312                 process_input_mk($targets, $subf, $esclitr, $1);
313                 od "\n";
314             } elsif (m#^macro\s+(\S+)\s+$#) {
315                 od "define $1\n";
316                 $push_nest->('macro', 1, '&:macro');
317             } else {
318                 err "bad directive argument syntax";
319             }
320         }
321     }
322     die "subdirmk: $f:$nest[0][3]: unclosed $nest[0][0] ($nest[0][2])\n"
323         if $nest[0][0];
324     $input->error and die "read $f: $!\n";
325     close $input or die "close $f: $!\n";
326 }
327
328 sub filter_subdir_mk ($) {
329     my ($targets) = @_;
330
331     #use Data::Dumper;
332     #print STDERR "filter @_\n";
333
334     my $esclit = '&';
335
336     my $pi = sub {
337         my ($f, $enoentok) = @_;
338         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
339     };
340     $pi->("Prefix.sd.mk",           1);
341     $pi->("${dir_prefix}Dir.sd.mk", 0);
342     $pi->("Suffix.sd.mk",           1);
343 }
344
345 sub process_subtree ($$);
346 sub process_subtree ($$) {
347     # => list of targets (in form SUBDIR/)
348     # recursive, children first
349     my ($node, $path) = @_;
350
351     #use Data::Dumper;
352     #print STDERR Dumper(\@_);
353
354     my $dir_prefix = dir_prefix($path);
355     # ^ this is the only var which we need before we come back from
356     #   the recursion.
357
358     push @output_makefiles, "${dir_prefix}Dir.mk";
359     write_makefile($dir_prefix, scalar @$path);
360
361     my %targets = (all => []);
362     foreach my $child (@{ $node->[1] }) {
363         my @childpath = (@$path, $child->[0]);
364         my $child_subdir = join '/', @childpath;
365         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!\n";
366         push @{ $targets{$_} }, $child_subdir foreach
367             process_subtree($child, \@childpath);
368     }
369
370     set_dir_vars($path);
371     start_output_file("${dir_prefix}Dir.mk.tmp");
372
373     if ($node->[2]) {
374         filter_subdir_mk(\%targets);
375     } else {
376         my $sdmk = "${dir_prefix}Dir.sd.mk";
377         if (stat $sdmk) {
378             die
379  "subdirmk: $sdmk unexpectedly exists (${dir_prefix} not mentioned on subdirmk/generate command line, maybe directory is missing from SUBDIRMK_SUBDIRS)";
380         } elsif ($!==ENOENT) {
381         } else {
382             die "stat $sdmk: $!\n";
383         }
384     }
385
386     oraw "\n";
387
388     my @targets = sort keys %targets;
389     foreach my $target (@targets) {
390         my $target_varname = target_varname($var_prefix, $target);
391         oraw "${dir_prefix}${target}:: \$($target_varname)";
392         foreach my $child_subdir (@{ $targets{$target} }) {
393             oraw " $child_subdir/$target";
394         }
395         oraw "\n";
396     }
397     if (@targets) {
398         oraw ".PHONY:";
399         oraw " ${dir_prefix}${_}" foreach @targets;
400         oraw "\n";
401     }
402
403     return @targets;
404 }
405
406 sub process_final ($) {
407     my ($otargets) = @_;
408     set_dir_vars([]);
409     push @output_makefiles, "Final.mk";
410     start_output_file("Final.mk.tmp");
411     my %ntargets;
412     my $esclit='&';
413     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
414     delete $ntargets{$_} foreach @$otargets;
415     my @ntargets = sort keys %ntargets;
416     die "subdirmk: Final.sd.mk may not introduce new top-level targets".
417         " (@ntargets)\n" if @ntargets;
418 }
419
420 sub process_tree() {
421     my @targets = process_subtree($root, [ ]);
422     process_final(\@targets);
423     start_output_file("main.mk.tmp");
424     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
425         oraw "$v=\@$v@\n";
426     }
427     oraw "SUBDIRMK_MAKEFILES :=\n";
428     oraw "MAKEFILE_TEMPLATES :=\n";
429     foreach my $mf (@output_makefiles) {
430         oraw "SUBDIRMK_MAKEFILES += $mf\n";
431     }
432     foreach my $input (sort keys %input_files) {
433         oraw "MAKEFILE_TEMPLATES += $input\n";
434     }
435     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
436 }
437
438 build_tree();
439 process_tree();
440 install_output_files();