chiark / gitweb /
generate: Avoid $err_file undefined warning during startup
[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 our %varref_exp;
157
158 our ($dir_prefix, $dir_suffix, $dir_name,
159      $var_prefix, $var_prefix_name);
160
161 sub dir_prefix ($) {
162     my ($path) = @_;
163     join '', map { "$_/" } @$path;
164 }
165
166 sub set_dir_vars ($) {
167     my ($path) = @_;
168     $dir_prefix = dir_prefix($path);
169     $dir_suffix = join '', map { "/$_" } @$path;
170     $dir_name = join '/', @$path ? @$path : '.';
171     $var_prefix_name = join '_', @$path ? @$path : qw(TOP);
172     $var_prefix = "${var_prefix_name}_";
173 }
174
175 our $err_file;
176
177 our @warn_ena_dfl = map { $_ => 1 } qw(
178     local+global
179     single-char-var
180     unknown-warning
181     broken-var-ref
182 );
183 our %warn_ena = @warn_ena_dfl;
184
185 our $warned;
186 our %warn_unk;
187
188 sub err ($) {
189     my ($m) = @_;
190     die defined $err_file
191         ? "subdirmk: ${err_file}:$.: $m\n"
192         : "subdirmk: $m\n";
193 }
194
195 sub wrncore ($$) {
196     my ($wk,$m) = @_;
197     return 0 unless $warn_ena{$wk} // warn "internal error $wk ?";
198     $warned++;
199     print STDERR "subdirmk: warning ($wk): $m\n";
200     return 1;
201 }
202
203 sub wrn ($$) {
204     my ($wk,$m) = @_;
205     our %warn_dedupe;
206     return 0 if $warn_dedupe{$err_file,$.,$wk,$m}++;
207     wrncore($wk, "${err_file}:$.: $m");
208 }
209
210 sub ddbl_only ($) {
211     my ($e) = @_;
212     return if $ddbl;
213     err "escape &$e is valid only during \$-doubling";
214 }
215
216 sub process_input_mk ($$$$);
217 sub process_input_mk ($$$$) {
218     my ($targets, $f, $esclitr, $enoent_ok) = @_;
219
220     my $caps_re = qr{[A-Z]};
221     my $lc_re = qr{[a-z]};
222
223     my $esc;
224     my $set_esc = sub {
225         $esc = $$esclitr;
226         $esc =~ s/\W/\\$&/g;
227     };
228     $set_esc->();
229
230     my $input = new IO::File $f, '<';
231     if (!$input) {
232         err "open $f: $!" unless $!==ENOENT && $enoent_ok;
233         return;
234     }
235     $input_files{$f}++;
236
237     local $err_file=$f;
238
239     my %srcdirmap = (
240                   '^' => "\${top_srcdir}${dir_suffix}",
241                   '~' => "\${top_srcdir}",
242                     );
243     my %pfxmap = (
244                   ''  => $dir_prefix,
245                  );
246     $pfxmap{$_} = $srcdirmap{$_}.'/' foreach keys %srcdirmap;
247
248     local $ddbl;
249     my @nest = (['']);
250     my $evalcall_brackets;
251
252     my $push_nest = sub {
253         my ($nk, $nndbl, $what) = @_;
254         unshift @nest, [ $nk, $ddbl, $what, $. ];
255         $ddbl = $nndbl;
256     };
257     my $pop_nest = sub {
258         my ($nk) = @_;
259         err "unexpectedly closed $nk in middle of $nest[0][0] ($nest[0][2])"
260             unless $nest[0][0] eq $nk;
261         $ddbl = (shift @nest)[1];
262     };
263
264     # Our detection of variable settings does not have to be completely
265     # accurate, since it is only going to be used for advice to the user.
266     my $note_varref = sub {
267         my ($vn,$amp) = @_;
268         my $exp = !!$varref_exp{$vn}{$amp};
269         $varref{$vn}{$exp}{$amp}{"$f:$."} = 1;
270     };
271
272     while (<$input>) {
273         if (m#^\s*($esc)?(\w+)\s*(?:=|\+=|\?=|:=)# ||
274             m#^\s*(?:$esc\:macro|define)\s+($esc)?(\S+)\s#) {
275             $note_varref->($2,!!$1);
276         }
277         if (s#^\s*$esc\:changequote\s+(\S+)\s+$##) {
278             $$esclitr = $1;
279             $set_esc->();
280             next;
281         } elsif (s#^\s*$esc\:endm\s+$##) {
282             $pop_nest->('macro');
283             od "endef\n";
284             next;
285         } elsif (s#^\s*$esc\:warn\s+(\S.*)$##) {
286             foreach my $wk (split /\s+/, $1) {
287                 my $yes = $wk !~ s{^!}{};
288                 if (defined $warn_ena{$wk}) {
289                     $warn_ena{$wk} = $yes;
290                     next;
291                 } elsif ($yes) {
292                     wrn 'unknown-warning',
293                         "unknown warning $wk requested";
294                 } else {
295                     $warn_unk{$wk} //= "$f:$.";
296                 }
297             }
298             next;
299         } elsif (s#^\s*$esc\:local\+global\s+(\S.*)$##) {
300             foreach my $vn (split /\s+/, $1) {
301                 my $pos = !($vn =~ s{^!}{});
302                 my $amp = $vn =~ s{^$esc}{};
303                 $varref_exp{$vn}{!!$amp} = $pos;
304             }
305             next;
306         } elsif (s#^\s*$esc\:(?=(-?)include|macro)##) {
307             $buffering_output='';
308         } elsif (m#^\s*$esc\:([a-z][-+0-9a-z_]*)#) {
309             err "unknown directive &:$1 or bad argumnt syntax";
310         } elsif (s{^\s*${esc}TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
311             my $t = $1 // 'all';
312             my $vn = target_varname($var_prefix, $t);
313             $note_varref->($vn,1);
314             od $vn;
315             $targets->{$t} //= [ ];
316         }
317         for (;;) {
318             err 'cannot $-double &-processed RHS of directive'
319                 if $ddbl && defined $buffering_output;
320             unless ($nest[0][0] eq 'eval'
321                     ? s{^(.*?)($esc|\$|[{}])}{}
322                     : s{^(.*?)($esc|\$)}{}) { od $_; last; }
323             od $1;
324             if ($2 eq '{') {
325                 od $2;
326                 $evalcall_brackets++;
327                 next;
328             } elsif ($2 eq '}') {
329                 od $2;
330                 next if --$evalcall_brackets;
331                 $pop_nest->('eval');
332                 od '}';
333                 next;
334             } elsif ($2 eq '$') {
335                 od $2;
336                 if (s{^\$}{}) { od $&; }
337                 elsif (m{^[a-zA-Z]\w}) {
338                     wrn 'single-char-var',
339                     'possibly confusing unbracketed single-char $-expansion';
340                 }
341                 elsif (m{^$esc}) {
342                     wrn 'broken-var-ref',
343                     'broken $&... expansion; you probably meant &$';
344                 }
345                 elsif (m{^\(($esc)?([^()\$]+)\)} ||
346                        m{^\{($esc)?([^{}\$]+)\}}) {
347                     $note_varref->($2,!!$1);
348                 }
349                 next;
350             }
351             if (s{^\\$esc}{}) { od "$$esclitr" }
352             elsif (s{^\\\$}{}) { oud '$' }
353             elsif (s{^\\\s+$}{}) { }
354             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
355             elsif (m{^(?=$caps_re)}) { od $var_prefix }
356             elsif (s{^\$([A-Za-z]\w+)}{}) {
357                 $note_varref->($1,1);
358                 od "\${${var_prefix}$1}";
359             }
360             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
361             elsif (s{^_}{}) { od $var_prefix }
362             elsif (s{^=}{}) { od $var_prefix_name }
363             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
364             elsif (s{^\.}{}) { od $dir_name }
365             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
366             elsif (s{^\$\-}{}) { $ddbl=undef; }
367             elsif (s{^\$\+}{}) { $ddbl=1; }
368             elsif (s{^\$\(}{}) {
369                 ddbl_only($&); oud "\${";
370                 $note_varref->($2,!!$1) if m{^($esc)?([^()\$]+\))};
371             }
372             elsif (s{^\$(\d+)}{}) { ddbl_only($&); oud "\${$1}"; }
373             elsif (s{^\$\{}{}) {
374                 err 'macro invocation cannot be re-$-doubled' if $ddbl;
375                 od '${eval ${call ';
376                 $evalcall_brackets = 1;
377                 $push_nest->('eval',1, '&${...}');
378                 $note_varref->($2,!!$1) if m{^\s*($esc)?([^,{}\$]+)};
379             } elsif (s{^([~^]?)(?=[ \t])}{}) {
380                 my $prefix = $pfxmap{$1} // die "internal error ($1?)";
381                 my $after='';
382                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
383                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
384                 od $_;
385                 $_ = $after;
386             } elsif (s{^\#}{}) {
387                 $_ = '';
388             } elsif (s{^![ \t]+}{}) {
389                 od $_;
390                 $_ = '';
391             } else {
392                 m{^.{0,5}};
393                 err "bad &-escape \`$$esclitr$&'";
394             }
395         }
396         if (defined $buffering_output) {
397             $_=$buffering_output;
398             $buffering_output=undef;
399             if (m#^(-?)include\s+(\S+)\s+$#) {
400                 my $subf = "$srcdir/$2";
401                 process_input_mk($targets, $subf, $esclitr, $1);
402                 od "\n";
403             } elsif (m#^macro\s+(\S+)\s+$#) {
404                 od "define $1\n";
405                 $push_nest->('macro', 1, '&:macro');
406             } else {
407                 err "bad directive argument syntax";
408             }
409         }
410     }
411     die "subdirmk: $f:$nest[0][3]: unclosed $nest[0][0] ($nest[0][2])\n"
412         if $nest[0][0];
413     $input->error and die "read $f: $!\n";
414     close $input or die "close $f: $!\n";
415 }
416
417 sub filter_subdir_mk ($) {
418     my ($targets) = @_;
419
420     #use Data::Dumper;
421     #print STDERR "filter @_\n";
422
423     my $esclit = '&';
424
425     my $pi = sub {
426         my ($f, $enoentok) = @_;
427         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
428     };
429     $pi->("Prefix.sd.mk",           1);
430     $pi->("${dir_prefix}Dir.sd.mk", 0);
431     $pi->("Suffix.sd.mk",           1);
432 }
433
434 sub process_subtree ($$);
435 sub process_subtree ($$) {
436     # => list of targets (in form SUBDIR/)
437     # recursive, children first
438     my ($node, $path) = @_;
439
440     #use Data::Dumper;
441     #print STDERR Dumper(\@_);
442
443     local %varref_exp;
444
445     my $dir_prefix = dir_prefix($path);
446     # ^ this is the only var which we need before we come back from
447     #   the recursion.
448
449     push @output_makefiles, "${dir_prefix}Dir.mk";
450     write_makefile($dir_prefix, scalar @$path);
451
452     my %targets = (all => []);
453     foreach my $child (@{ $node->[1] }) {
454         my @childpath = (@$path, $child->[0]);
455         my $child_subdir = join '/', @childpath;
456         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!\n";
457         local %warn_ena = @warn_ena_dfl;
458         push @{ $targets{$_} }, $child_subdir foreach
459             process_subtree($child, \@childpath);
460     }
461
462     set_dir_vars($path);
463     start_output_file("${dir_prefix}Dir.mk.tmp");
464
465     if ($node->[2]) {
466         filter_subdir_mk(\%targets);
467     } else {
468         my $sdmk = "${dir_prefix}Dir.sd.mk";
469         if (stat $sdmk) {
470             die
471  "subdirmk: $sdmk unexpectedly exists (${dir_prefix} not mentioned on subdirmk/generate command line, maybe directory is missing from SUBDIRMK_SUBDIRS)";
472         } elsif ($!==ENOENT) {
473         } else {
474             die "stat $sdmk: $!\n";
475         }
476     }
477
478     oraw "\n";
479
480     my @targets = sort keys %targets;
481     foreach my $target (@targets) {
482         my $target_varname = target_varname($var_prefix, $target);
483         oraw "${dir_prefix}${target}:: \$($target_varname)";
484         foreach my $child_subdir (@{ $targets{$target} }) {
485             oraw " $child_subdir/$target";
486         }
487         oraw "\n";
488     }
489     if (@targets) {
490         oraw ".PHONY:";
491         oraw " ${dir_prefix}${_}" foreach @targets;
492         oraw "\n";
493     }
494
495     return @targets;
496 }
497
498 sub process_final ($) {
499     my ($otargets) = @_;
500     set_dir_vars([]);
501     push @output_makefiles, "Final.mk";
502     start_output_file("Final.mk.tmp");
503     my %ntargets;
504     my $esclit='&';
505     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
506     delete $ntargets{$_} foreach @$otargets;
507     my @ntargets = sort keys %ntargets;
508     die "subdirmk: Final.sd.mk may not introduce new top-level targets".
509         " (@ntargets)\n" if @ntargets;
510 }
511
512 sub process_tree() {
513     my @targets = process_subtree($root, [ ]);
514     process_final(\@targets);
515     start_output_file("main.mk.tmp");
516     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
517         oraw "$v=\@$v@\n";
518     }
519     oraw "SUBDIRMK_MAKEFILES :=\n";
520     oraw "MAKEFILE_TEMPLATES :=\n";
521     foreach my $mf (@output_makefiles) {
522         oraw "SUBDIRMK_MAKEFILES += $mf\n";
523     }
524     foreach my $input (sort keys %input_files) {
525         oraw "MAKEFILE_TEMPLATES += $input\n";
526     }
527     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
528 }
529
530 sub flmap ($) { local ($_) = @_; s{:(\d+)$}{ sprintf ":%10d", $1 }e; $_; }
531
532 sub print_varref_warnings () {
533     foreach my $vn (sort keys %varref) {
534         my $vv = $varref{$vn};
535         next unless $vv->{''}{''} && $vv->{''}{1};
536         wrncore 'local+global', "saw both $vn and &$vn" or return;
537         foreach my $exp ('', 1) {
538         foreach my $amp ('', 1) {
539             printf STDERR
540                 ($exp
541                  ? " expectedly saw %s%s at %s\n"
542                  : " saw %s%s at %s\n"),
543                 ($amp ? '&' : ''), $vn, $_
544                 foreach
545                 sort { flmap($a) cmp flmap($b) }
546                 keys %{ $vv->{$exp}{$amp} };
547         }
548         }
549     }
550 }
551
552 sub print_warning_warnings () {
553     return unless $warned;
554     foreach my $wk (sort keys %warn_unk) {
555         wrncore 'unknown-warning',
556             "$warn_unk{$wk}: attempt to suppress unknown warning(s) \`$wk'";
557     }
558 }
559
560 build_tree();
561 process_tree();
562 print_varref_warnings();
563 print_warning_warnings();
564 install_output_files();