chiark / gitweb /
Error handling: Replace or update many calls to `die'
[secnet.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 #     Subdir.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 "$0: $file:$lno: problem\n";
30 #         die "$0: some problem not locatable in that way\n";
31 #
32 # System call error (not ENOENT) accessing input/output files:
33 #         die "description of problem eg maybe erbing noun: $!\n";
34 #
35 # Bug detedcted in `generate':
36 #         die "internal error (some information)?"; # or similar
37
38 while (@ARGV && $ARGV[0] =~ m/^-/) {
39     $_ = shift @ARGV;
40     last if $_ eq '--';
41     if (s/^--srcdir=//) {
42         $srcdir=$';
43     } else {
44         die "$0: unknown option \`$_'\n";
45     }
46 }
47 our @subdirs = @ARGV;
48
49 s{/+$}{} foreach @subdirs;
50
51 our $root = [ '.', [ ], 1 ];
52 # each node is [ 'relative subdir name', \@children, $mentioned ]
53
54 sub build_tree () {
55     foreach my $subdir (@subdirs) {
56         my @path = $subdir eq '.' ? () : split m{/+}, $subdir;
57         my $node = $root;
58         foreach my $d (@path) {
59             my ($c,) = grep { $_->[0] eq $d } @{ $node->[1] };
60             if (!$c) {
61                 $c = [ $d, [ ] ];
62                 push @{ $node->[1] }, $c;
63             }
64             $node = $c;
65         }
66         $node->[2] = 1;
67     }
68 }
69
70 sub target_varname ($$) {
71     my ($var_prefix, $target) = @_;
72     return $var_prefix.'TARGETS'.($target eq 'all' ? '' : "_$target");
73 }
74
75 our $writing_output;
76 our $buffering_output;
77 our %output_files;
78 our %input_files;
79 our @output_makefiles;
80
81 sub close_any_output_file() {
82     return unless defined $writing_output;
83     O->error and die "error writing $writing_output.tmp: $! (?)\n";
84     close O or die "error closing $writing_output.tmp: $!\n";
85     $writing_output = undef;
86 }
87
88 sub oraw {
89     die 'internal error' unless defined $writing_output;
90     print O @_ or die "error writing $writing_output.tmp: $!\n";
91 }
92
93 sub oud { # undoubled
94     if (defined $buffering_output) {
95         $buffering_output .= $_ foreach @_;
96         return;
97     }
98     oraw @_;
99 }
100
101 our $ddbl;
102
103 sub od { # maybe $-doubled
104     if (!$ddbl) {
105         oud @_;
106         return;
107     }
108     foreach (@_) {
109         my $e = $_;
110         $e =~ s{\$}{\$\$}g;
111         oud $e;
112     }
113 }
114
115 sub start_output_file ($) {
116     close_any_output_file();
117     ($writing_output) = @_;
118     die "internal error ($writing_output?)"
119         if $output_files{$writing_output}++;
120     my $tmp = "$writing_output.tmp";
121     open O, ">", $tmp or die "create $tmp: $!\n";
122     oraw "# autogenerated - do not edit\n";
123 }
124
125 sub install_output_files () {
126     close_any_output_file();
127     foreach my $f (sort keys %output_files) {
128         rename "$f.tmp", $f or die "install new $f: $!\n";
129     }
130 }
131
132 sub write_makefile ($$) {
133     my ($dir_prefix,$depth) = @_;
134     #print STDERR "write_makefile @_\n";
135     start_output_file("${dir_prefix}Makefile");
136     my $cd = $depth ? join('/', ('..',) x $depth) : '.';
137     my $suppress_templates=
138         '$(if $(filter-out clean real-clean, $(subdirmk_targets)),,'.
139         ' MAKEFILE_TEMPLATES=)';
140     oraw <<END;
141 default: all
142 \$(filter-out all,\$(MAKECMDGOALS)) all: run-main.mk
143         \@:
144 subdirmk_targets:=\$(or \$(MAKECMDGOALS),all)
145 Makefile run-main.mk:
146         \$(MAKE) -C $cd -f main.mk \$(addprefix ${dir_prefix},\$(subdirmk_targets))$suppress_templates
147 .SUFFIXES:
148 .PHONY: run-main.mk
149 END
150 }
151
152 our ($dir_prefix, $dir_suffix, $dir_name,
153      $var_prefix, $var_prefix_name);
154
155 sub dir_prefix ($) {
156     my ($path) = @_;
157     join '', map { "$_/" } @$path;
158 }
159
160 sub set_dir_vars ($) {
161     my ($path) = @_;
162     $dir_prefix = dir_prefix($path);
163     $dir_suffix = join '', map { "/$_" } @$path;
164     $dir_name = join '/', @$path ? @$path : '.';
165     $var_prefix_name = join '_', @$path ? @$path : qw(TOP);
166     $var_prefix = "${var_prefix_name}_";
167 }
168
169 our $err_file;
170
171 sub err ($) {
172     my ($m) = @_;
173     die "$0: ${err_file}:$.: $m\n";
174 }
175
176 sub ddbl_only ($) {
177     my ($e) = @_;
178     return if $ddbl;
179     err "escape &$e is valid only during \$-doubling";
180 }
181
182 sub process_input_mk ($$$$);
183 sub process_input_mk ($$$$) {
184     my ($targets, $f, $esclitr, $enoent_ok) = @_;
185
186     my $caps_re = qr{[A-Z]};
187     my $lc_re = qr{[a-z]};
188
189     my $esc;
190     my $set_esc = sub {
191         $esc = $$esclitr;
192         $esc =~ s/\W/\\$&/g;
193     };
194     $set_esc->();
195
196     my $input = new IO::File $f, '<';
197     if (!$input) {
198         err "open $f: $!" unless $!==ENOENT && $enoent_ok;
199         return;
200     }
201     $input_files{$f}++;
202
203     local $err_file=$f;
204
205     my %srcdirmap = (
206                   '^' => "\$(top_srcdir)${dir_suffix}",
207                   '~' => "\$(top_srcdir)",
208                     );
209     my %pfxmap = (
210                   ''  => $dir_prefix,
211                  );
212     $pfxmap{$_} = $srcdirmap{$_}.'/' foreach keys %srcdirmap;
213
214     local $ddbl;
215     my @nest = (['']);
216
217     my $push_nest = sub {
218         my ($nk, $nndbl) = @_;
219         unshift @nest, [ $nk, $ddbl ];
220         $ddbl = $nndbl;
221     };
222     my $pop_nest = sub {
223         my ($nk) = @_;
224         die unless $nest[0][0] eq $nk;
225         # ^ xxx need better message
226         $ddbl = (shift @nest)[1];
227     };
228
229     while (<$input>) {
230         if (s#^\s*$esc\:changequote\s+(\S+)\s+$##) {
231             $$esclitr = $1;
232             $set_esc->();
233             next;
234         } elsif (s#^\s*$esc\:endm\s+$##) {
235             $pop_nest->('Macro');
236             od "endef\n";
237             next;
238         } elsif (s#^\s*$esc\:(?=(-?)include|macro)##) {
239             $buffering_output='';
240         } elsif (m#^\s*$esc\:([a-z][-0-9a-z_]*)#) {
241             err "unknown directive &:$1";
242         } elsif (s{^\s*${esc}TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
243             my $t = $1 // 'all';
244             od target_varname($var_prefix, $t);
245             $targets->{$t} //= [ ];
246         }
247         for (;;) {
248             err 'cannot $-double &-processed RHS of directive'
249                 if $ddbl && defined $buffering_output;
250             unless ($nest[0][0] eq 'Eval'
251                     ? s{^(.*?)($esc|[{}])}{}
252                     : s{^(.*?)($esc)}{}) { od $_; last; }
253             od $1;
254             if ($2 eq '{') {
255                 $ddbl++;
256                 next;
257             } elsif ($2 eq '}') {
258                 next if --$ddbl;
259                 $pop_nest->('Eval');
260                 od '}}';
261                 next;
262             }
263             if (s{^\\$esc}{}) { od "$$esclitr" }
264             elsif (s{^\\\$}{}) { oud '$' }
265             elsif (s{^\\\s+$}{}) { }
266             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
267             elsif (m{^(?=$caps_re)}) { od $var_prefix }
268             elsif (s{^\$([A-Za-z]\w+)}{}) { od "\$(${var_prefix}$1)" }
269             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
270             elsif (s{^_}{}) { od $var_prefix }
271             elsif (s{^=}{}) { od $var_prefix_name }
272             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
273             elsif (s{^\.}{}) { od $dir_name }
274             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
275             elsif (s{^\$\-}{}) { $ddbl=undef; }
276             elsif (s{^\$\+}{}) { $ddbl=1; }
277             elsif (s{^\$\(}{}) { ddbl_only($&); oud "\$("; }
278             elsif (s{^\$(\d+)}{}) { ddbl_only($&); oud "\$($1)"; }
279             elsif (s{^\$\{}{}) {
280                 err 'macro invocation cannot be re-$-doubled' if $ddbl;
281                 od '${eval ${call ';
282                 $push_nest->('Eval',1);
283             } elsif (s{^([~^]?)(?=[ \t])}{}) {
284                 my $prefix = $pfxmap{$1} // die "internal error ($1?)";
285                 my $after='';
286                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
287                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
288                 od $_;
289                 $_ = $after;
290             } elsif (s{^\#}{}) {
291                 $_ = '';
292             } elsif (s{^![ \t]+}{}) {
293                 od $_;
294                 $_ = '';
295             } else {
296                 err "bad &-escape \`$$esclitr$_'";
297             }
298         }
299         if (defined $buffering_output) {
300             $_=$buffering_output;
301             $buffering_output=undef;
302             if (m#^(-?)include\s+(\S+)\s+$#) {
303                 my $subf = "$srcdir/$2";
304                 process_input_mk($targets, $subf, $esclitr, $1);
305                 od "\n";
306             } elsif (m#^macro\s+(\S+)\s+$#) {
307                 od "define $1\n";
308                 $push_nest->('Macro', 1);
309             } else {
310                 die "internal error ($_?)";
311             }
312         }
313     }
314     die "unclosed $nest[0][0]" if $nest[0][0];
315     $input->error and die "read $f: $!\n";
316     close $input or die "close $f: $!\n";
317 }
318
319 sub filter_subdir_mk ($) {
320     my ($targets) = @_;
321
322     #use Data::Dumper;
323     #print STDERR "filter @_\n";
324
325     my $esclit = '&';
326
327     my $pi = sub {
328         my ($f, $enoentok) = @_;
329         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
330     };
331     $pi->("Prefix.sd.mk",              1);
332     $pi->("${dir_prefix}Subdir.sd.mk", 0);
333     $pi->("Suffix.sd.mk",              1);
334 }
335
336 sub process_subtree ($$);
337 sub process_subtree ($$) {
338     # => list of targets (in form SUBDIR/)
339     # recursive, children first
340     my ($node, $path) = @_;
341
342     #use Data::Dumper;
343     #print STDERR Dumper(\@_);
344
345     my $dir_prefix = dir_prefix($path);
346     # ^ this is the only var which we need before we come back from
347     #   the recursion.
348
349     push @output_makefiles, "${dir_prefix}Subdir.mk";
350     write_makefile($dir_prefix, scalar @$path);
351
352     my %targets = (all => []);
353     foreach my $child (@{ $node->[1] }) {
354         my @childpath = (@$path, $child->[0]);
355         my $child_subdir = join '/', @childpath;
356         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!\n";
357         push @{ $targets{$_} }, $child_subdir foreach
358             process_subtree($child, \@childpath);
359     }
360
361     set_dir_vars($path);
362     start_output_file("${dir_prefix}Subdir.mk.tmp");
363
364     if ($node->[2]) {
365         filter_subdir_mk(\%targets);
366     } else {
367         my $sdmk = "${dir_prefix}Subdir.sd.mk";
368         if (stat $sdmk) {
369             die
370  "$0: $sdmk unexpectedly exists (${dir_prefix} not mentioned on subdirmk/generate command line, maybe directory is missing from SUBDIRMK_SUBDIRS)";
371         } elsif ($!==ENOENT) {
372         } else {
373             die "stat $sdmk: $!\n";
374         }
375     }
376
377     oraw "\n";
378
379     my @targets = sort keys %targets;
380     foreach my $target (@targets) {
381         my $target_varname = target_varname($var_prefix, $target);
382         print O "${dir_prefix}${target}:: \$($target_varname)";
383         foreach my $child_subdir (@{ $targets{$target} }) {
384             print O " $child_subdir/$target";
385         }
386         print O "\n";
387     }
388     if (@targets) {
389         print O ".PHONY:";
390         print O " ${dir_prefix}${_}" foreach @targets;
391         print O "\n";
392     }
393
394     return @targets;
395 }
396
397 sub process_final ($) {
398     my ($otargets) = @_;
399     set_dir_vars([]);
400     push @output_makefiles, "Final.mk";
401     start_output_file("Final.mk.tmp");
402     my %ntargets;
403     my $esclit='&';
404     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
405     delete $ntargets{$_} foreach @$otargets;
406     my @ntargets = sort keys %ntargets;
407     die "$0: Final.sd.mk may not introduce new top-level targets".
408         " (@ntargets)\n" if @ntargets;
409 }
410
411 sub process_tree() {
412     my @targets = process_subtree($root, [ ]);
413     process_final(\@targets);
414     start_output_file("main.mk.tmp");
415     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
416         oraw "$v=\@$v@\n";
417     }
418     oraw "SUBDIRMK_MAKEFILES :=\n";
419     oraw "MAKEFILE_TEMPLATES :=\n";
420     foreach my $mf (@output_makefiles) {
421         oraw "SUBDIRMK_MAKEFILES += $mf\n";
422     }
423     foreach my $input (sort keys %input_files) {
424         oraw "MAKEFILE_TEMPLATES += $input\n";
425     }
426     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
427 }
428
429 build_tree();
430 process_tree();
431 install_output_files();