3 # subdirmk - &-filter (makefile generation program)
4 # Copyright 2019 Ian Jackson
5 # SPDX-License-Identifier: LGPL-2.0-or-later
7 # $(srcdir)/subdirmk/generate [--srcdir=SRCDIR] [--] SUBDIR...
9 # generates in each subdirectory
18 print "$0 @ARGV\n" or die $!;
22 # error handling methods:
24 # Error in input file, while $err_file and $. set, eg in most of
28 # Other input or usage errors:
29 # die "subdirmk: $file:$lno: problem\n";
30 # die "subdirmk: some problem not locatable in that way\n";
33 # die "subdirmk $0: explanation of problem\n";
35 # System call error (not ENOENT) accessing input/output files:
36 # die "description of problem eg maybe erbing noun: $!\n";
38 # Bug detedcted in `generate':
39 # die "internal error (some information)?"; # or similar
41 while (@ARGV && $ARGV[0] =~ m/^-/) {
47 die "subdirmk $0: unknown option \`$_'\n";
52 s{/+$}{} foreach @subdirs;
54 our $root = [ '.', [ ], 1 ];
55 # each node is [ 'relative subdir name', \@children, $mentioned ]
58 foreach my $subdir (@subdirs) {
59 my @path = $subdir eq '.' ? () : split m{/+}, $subdir;
61 foreach my $d (@path) {
62 my ($c,) = grep { $_->[0] eq $d } @{ $node->[1] };
65 push @{ $node->[1] }, $c;
73 sub target_varname ($$) {
74 my ($var_prefix, $target) = @_;
75 return $var_prefix.'TARGETS'.($target eq 'all' ? '' : "_$target");
79 our $buffering_output;
82 our @output_makefiles;
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;
92 die 'internal error' unless defined $writing_output;
93 print O @_ or die "error writing $writing_output.tmp: $!\n";
97 if (defined $buffering_output) {
98 $buffering_output .= $_ foreach @_;
106 sub od { # maybe $-doubled
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";
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";
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=)';
145 \$(filter-out all,\$(MAKECMDGOALS)) all: run-main.mk
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
158 our ($dir_prefix, $dir_suffix, $dir_name,
159 $var_prefix, $var_prefix_name);
163 join '', map { "$_/" } @$path;
166 sub set_dir_vars ($) {
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}_";
177 our @warn_ena_dfl = map { $_ => 1 } qw(
183 our %warn_ena = @warn_ena_dfl;
190 die "subdirmk: ${err_file}:$.: $m\n";
195 return 0 unless $warn_ena{$wk} // warn "internal error $wk ?";
197 print STDERR "subdirmk: warning ($wk): $m\n";
204 return 0 if $warn_dedupe{$err_file,$.,$wk,$m}++;
205 wrncore($wk, "${err_file}:$.: $m");
211 err "escape &$e is valid only during \$-doubling";
214 sub process_input_mk ($$$$);
215 sub process_input_mk ($$$$) {
216 my ($targets, $f, $esclitr, $enoent_ok) = @_;
218 my $caps_re = qr{[A-Z]};
219 my $lc_re = qr{[a-z]};
228 my $input = new IO::File $f, '<';
230 err "open $f: $!" unless $!==ENOENT && $enoent_ok;
238 '^' => "\${top_srcdir}${dir_suffix}",
239 '~' => "\${top_srcdir}",
244 $pfxmap{$_} = $srcdirmap{$_}.'/' foreach keys %srcdirmap;
248 my $evalcall_brackets;
250 my $push_nest = sub {
251 my ($nk, $nndbl, $what) = @_;
252 unshift @nest, [ $nk, $ddbl, $what, $. ];
257 err "unexpectedly closed $nk in middle of $nest[0][0] ($nest[0][2])"
258 unless $nest[0][0] eq $nk;
259 $ddbl = (shift @nest)[1];
262 # Our detection of variable settings does not have to be completely
263 # accurate, since it is only going to be used for advice to the user.
264 my $note_varref = sub {
266 my $exp = !!$varref_exp{$vn}{$amp};
267 $varref{$vn}{$exp}{$amp}{"$f:$."} = 1;
271 if (m#^\s*($esc)?(\w+)\s*(?:=|\+=|\?=|:=)# ||
272 m#^\s*(?:$esc\:macro|define)\s+($esc)?(\S+)\s#) {
273 $note_varref->($2,!!$1);
275 if (s#^\s*$esc\:changequote\s+(\S+)\s+$##) {
279 } elsif (s#^\s*$esc\:endm\s+$##) {
280 $pop_nest->('macro');
283 } elsif (s#^\s*$esc\:warn\s+(\S.*)$##) {
284 foreach my $wk (split /\s+/, $1) {
285 my $yes = $wk !~ s{^!}{};
286 if (defined $warn_ena{$wk}) {
287 $warn_ena{$wk} = $yes;
290 wrn 'unknown-warning',
291 "unknown warning $wk requested";
293 $warn_unk{$wk} //= "$f:$.";
297 } elsif (s#^\s*$esc\:local\+global\s+(\S.*)$##) {
298 foreach my $vn (split /\s+/, $1) {
299 my $pos = !($vn =~ s{^!}{});
300 my $amp = $vn =~ s{^$esc}{};
301 $varref_exp{$vn}{!!$amp} = $pos;
304 } elsif (s#^\s*$esc\:(?=(-?)include|macro)##) {
305 $buffering_output='';
306 } elsif (m#^\s*$esc\:([a-z][-+0-9a-z_]*)#) {
307 err "unknown directive &:$1 or bad argumnt syntax";
308 } elsif (s{^\s*${esc}TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
310 my $vn = target_varname($var_prefix, $t);
311 $note_varref->($vn,1);
313 $targets->{$t} //= [ ];
316 err 'cannot $-double &-processed RHS of directive'
317 if $ddbl && defined $buffering_output;
318 unless ($nest[0][0] eq 'eval'
319 ? s{^(.*?)($esc|\$|[{}])}{}
320 : s{^(.*?)($esc|\$)}{}) { od $_; last; }
324 $evalcall_brackets++;
326 } elsif ($2 eq '}') {
328 next if --$evalcall_brackets;
332 } elsif ($2 eq '$') {
334 if (s{^\$}{}) { od $&; }
335 elsif (m{^[a-zA-Z]\w}) {
336 wrn 'single-char-var',
337 'possibly confusing unbracketed single-char $-expansion';
340 wrn 'broken-var-ref',
341 'broken $&... expansion; you probably meant &$';
343 elsif (m{^\(($esc)?([^()\$]+)\)} ||
344 m{^\{($esc)?([^{}\$]+)\}}) {
345 $note_varref->($2,!!$1);
349 if (s{^\\$esc}{}) { od "$$esclitr" }
350 elsif (s{^\\\$}{}) { oud '$' }
351 elsif (s{^\\\s+$}{}) { }
352 elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
353 elsif (m{^(?=$caps_re)}) { od $var_prefix }
354 elsif (s{^\$([A-Za-z]\w+)}{}) {
355 $note_varref->($1,1);
356 od "\${${var_prefix}$1}";
358 elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
359 elsif (s{^_}{}) { od $var_prefix }
360 elsif (s{^=}{}) { od $var_prefix_name }
361 elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
362 elsif (s{^\.}{}) { od $dir_name }
363 elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
364 elsif (s{^\$\-}{}) { $ddbl=undef; }
365 elsif (s{^\$\+}{}) { $ddbl=1; }
367 ddbl_only($&); oud "\${";
368 $note_varref->($2,!!$1) if m{^($esc)?([^()\$]+\))};
370 elsif (s{^\$(\d+)}{}) { ddbl_only($&); oud "\${$1}"; }
372 err 'macro invocation cannot be re-$-doubled' if $ddbl;
374 $evalcall_brackets = 1;
375 $push_nest->('eval',1, '&${...}');
376 $note_varref->($2,!!$1) if m{^\s*($esc)?([^,{}\$]+)};
377 } elsif (s{^([~^]?)(?=[ \t])}{}) {
378 my $prefix = $pfxmap{$1} // die "internal error ($1?)";
380 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
381 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
386 } elsif (s{^![ \t]+}{}) {
391 err "bad &-escape \`$$esclitr$&'";
394 if (defined $buffering_output) {
395 $_=$buffering_output;
396 $buffering_output=undef;
397 if (m#^(-?)include\s+(\S+)\s+$#) {
398 my $subf = "$srcdir/$2";
399 process_input_mk($targets, $subf, $esclitr, $1);
401 } elsif (m#^macro\s+(\S+)\s+$#) {
403 $push_nest->('macro', 1, '&:macro');
405 err "bad directive argument syntax";
409 die "subdirmk: $f:$nest[0][3]: unclosed $nest[0][0] ($nest[0][2])\n"
411 $input->error and die "read $f: $!\n";
412 close $input or die "close $f: $!\n";
415 sub filter_subdir_mk ($) {
419 #print STDERR "filter @_\n";
424 my ($f, $enoentok) = @_;
425 process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
427 $pi->("Prefix.sd.mk", 1);
428 $pi->("${dir_prefix}Dir.sd.mk", 0);
429 $pi->("Suffix.sd.mk", 1);
432 sub process_subtree ($$);
433 sub process_subtree ($$) {
434 # => list of targets (in form SUBDIR/)
435 # recursive, children first
436 my ($node, $path) = @_;
439 #print STDERR Dumper(\@_);
443 my $dir_prefix = dir_prefix($path);
444 # ^ this is the only var which we need before we come back from
447 push @output_makefiles, "${dir_prefix}Dir.mk";
448 write_makefile($dir_prefix, scalar @$path);
450 my %targets = (all => []);
451 foreach my $child (@{ $node->[1] }) {
452 my @childpath = (@$path, $child->[0]);
453 my $child_subdir = join '/', @childpath;
454 mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!\n";
455 local %warn_ena = @warn_ena_dfl;
456 push @{ $targets{$_} }, $child_subdir foreach
457 process_subtree($child, \@childpath);
461 start_output_file("${dir_prefix}Dir.mk.tmp");
464 filter_subdir_mk(\%targets);
466 my $sdmk = "${dir_prefix}Dir.sd.mk";
469 "subdirmk: $sdmk unexpectedly exists (${dir_prefix} not mentioned on subdirmk/generate command line, maybe directory is missing from SUBDIRMK_SUBDIRS)";
470 } elsif ($!==ENOENT) {
472 die "stat $sdmk: $!\n";
478 my @targets = sort keys %targets;
479 foreach my $target (@targets) {
480 my $target_varname = target_varname($var_prefix, $target);
481 oraw "${dir_prefix}${target}:: \$($target_varname)";
482 foreach my $child_subdir (@{ $targets{$target} }) {
483 oraw " $child_subdir/$target";
489 oraw " ${dir_prefix}${_}" foreach @targets;
496 sub process_final ($) {
499 push @output_makefiles, "Final.mk";
500 start_output_file("Final.mk.tmp");
503 process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
504 delete $ntargets{$_} foreach @$otargets;
505 my @ntargets = sort keys %ntargets;
506 die "subdirmk: Final.sd.mk may not introduce new top-level targets".
507 " (@ntargets)\n" if @ntargets;
511 my @targets = process_subtree($root, [ ]);
512 process_final(\@targets);
513 start_output_file("main.mk.tmp");
514 foreach my $v (qw(top_srcdir abs_top_srcdir)) {
517 oraw "SUBDIRMK_MAKEFILES :=\n";
518 oraw "MAKEFILE_TEMPLATES :=\n";
519 foreach my $mf (@output_makefiles) {
520 oraw "SUBDIRMK_MAKEFILES += $mf\n";
522 foreach my $input (sort keys %input_files) {
523 oraw "MAKEFILE_TEMPLATES += $input\n";
525 oraw "include \$(SUBDIRMK_MAKEFILES)\n";
528 sub flmap ($) { local ($_) = @_; s{:(\d+)$}{ sprintf ":%10d", $1 }e; $_; }
530 sub print_varref_warnings () {
531 foreach my $vn (sort keys %varref) {
532 my $vv = $varref{$vn};
533 next unless $vv->{''}{''} && $vv->{''}{1};
534 wrncore 'local+global', "saw both $vn and &$vn" or return;
535 foreach my $exp ('', 1) {
536 foreach my $amp ('', 1) {
539 ? " expectedly saw %s%s at %s\n"
540 : " saw %s%s at %s\n"),
541 ($amp ? '&' : ''), $vn, $_
543 sort { flmap($a) cmp flmap($b) }
544 keys %{ $vv->{$exp}{$amp} };
550 sub print_warning_warnings () {
551 return unless $warned;
552 foreach my $wk (sort keys %warn_unk) {
553 wrncore 'unknown-warning',
554 "$warn_unk{$wk}: attempt to suppress unknown warning(s) \`$wk'";
560 print_varref_warnings();
561 print_warning_warnings();
562 install_output_files();