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