chiark / gitweb /
Syntax: Incompatible change: &$( does not do daft { thing
[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{^\\\$}{}) { oud '$' }
354             elsif (s{^\\\s+$}{}) { }
355             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
356             elsif (m{^(?=$caps_re)}) { od $var_prefix }
357             elsif (s{^\$([A-Za-z]\w+)}{}) {
358                 $note_varref->($1,1);
359                 od "\${${var_prefix}$1}";
360             }
361             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
362             elsif (s{^_}{}) { od $var_prefix }
363             elsif (s{^=}{}) { od $var_prefix_name }
364             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
365             elsif (s{^\.}{}) { od $dir_name }
366             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
367             elsif (s{^\$\-}{}) { $ddbl=undef; }
368             elsif (s{^\$\+}{}) { $ddbl=1; }
369             elsif (s{^\$\(}{}) {
370                 ddbl_only($&); oud "\$(";
371                 $note_varref->($2,!!$1) if m{^($esc)?([^()\$]+\))};
372             }
373             elsif (s{^\$(\d+)}{}) { ddbl_only($&); oud "\${$1}"; }
374             elsif (s{^\(\s*$esc(?=$lc_re)}{}) { od "\$(call ${var_prefix}" }
375             elsif (s{^\(\s*(?=\S)}{}        ) { od "\$(call "              }
376             elsif (s{^\{}{}) {
377                 err 'macro invocation cannot be re-$-doubled' if $ddbl;
378                 od '${eval ${call ';
379                 $evalcall_brackets = 1;
380                 $push_nest->('eval',1, '&{...}');
381                 $note_varref->($2,!!$1) if m{^\s*($esc)?([^,{}\$]+)};
382             } elsif (s{^([~^]?)(?=[ \t])}{}) {
383                 my $prefix = $pfxmap{$1} // die "internal error ($1?)";
384                 my $after='';
385                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
386                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
387                 od $_;
388                 $_ = $after;
389             } elsif (s{^\#}{}) {
390                 $_ = '';
391             } elsif (s{^![ \t]+}{}) {
392                 od $_;
393                 $_ = '';
394             } else {
395                 m{^.{0,5}};
396                 err "bad &-escape \`$$esclitr$&'";
397             }
398         }
399         if (defined $buffering_output) {
400             $_=$buffering_output;
401             $buffering_output=undef;
402             if (m#^(-?)include\s+(\S+)\s+$#) {
403                 my $subf = "$srcdir/$2";
404                 process_input_mk($targets, $subf, $esclitr, $1);
405                 od "\n";
406             } elsif (m#^macro\s+(\S+)\s+$#) {
407                 od "define $1\n";
408                 $push_nest->('macro', 1, '&:macro');
409             } else {
410                 err "bad directive argument syntax";
411             }
412         }
413     }
414     die "subdirmk: $f:$nest[0][3]: unclosed $nest[0][0] ($nest[0][2])\n"
415         if $nest[0][0];
416     $input->error and die "read $f: $!\n";
417     close $input or die "close $f: $!\n";
418 }
419
420 sub filter_subdir_mk ($) {
421     my ($targets) = @_;
422
423     #use Data::Dumper;
424     #print STDERR "filter @_\n";
425
426     my $esclit = '&';
427
428     my $pi = sub {
429         my ($f, $enoentok) = @_;
430         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
431     };
432     $pi->("Prefix.sd.mk",           1);
433     $pi->("${dir_prefix}Dir.sd.mk", 0);
434     $pi->("Suffix.sd.mk",           1);
435 }
436
437 sub process_subtree ($$);
438 sub process_subtree ($$) {
439     # => list of targets (in form SUBDIR/)
440     # recursive, children first
441     my ($node, $path) = @_;
442
443     #use Data::Dumper;
444     #print STDERR Dumper(\@_);
445
446     local %varref_exp;
447
448     my $dir_prefix = dir_prefix($path);
449     # ^ this is the only var which we need before we come back from
450     #   the recursion.
451
452     push @output_makefiles, "${dir_prefix}Dir.mk";
453     write_makefile($dir_prefix, scalar @$path);
454
455     my %targets = (all => []);
456     foreach my $child (@{ $node->[1] }) {
457         my @childpath = (@$path, $child->[0]);
458         my $child_subdir = join '/', @childpath;
459         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!\n";
460         local %warn_ena = @warn_ena_dfl;
461         push @{ $targets{$_} }, $child_subdir foreach
462             process_subtree($child, \@childpath);
463     }
464
465     set_dir_vars($path);
466     start_output_file("${dir_prefix}Dir.mk.tmp");
467
468     if ($node->[2]) {
469         filter_subdir_mk(\%targets);
470     } else {
471         my $sdmk = "${dir_prefix}Dir.sd.mk";
472         if (stat $sdmk) {
473             die
474  "subdirmk: $sdmk unexpectedly exists (${dir_prefix} not mentioned on subdirmk/generate command line, maybe directory is missing from SUBDIRMK_SUBDIRS)";
475         } elsif ($!==ENOENT) {
476         } else {
477             die "stat $sdmk: $!\n";
478         }
479     }
480
481     oraw "\n";
482
483     my @targets = sort keys %targets;
484     foreach my $target (@targets) {
485         my $target_varname = target_varname($var_prefix, $target);
486         oraw "${dir_prefix}${target}:: \$($target_varname)";
487         foreach my $child_subdir (@{ $targets{$target} }) {
488             oraw " $child_subdir/$target";
489         }
490         oraw "\n";
491     }
492     if (@targets) {
493         oraw ".PHONY:";
494         oraw " ${dir_prefix}${_}" foreach @targets;
495         oraw "\n";
496     }
497
498     return @targets;
499 }
500
501 sub process_final ($) {
502     my ($otargets) = @_;
503     set_dir_vars([]);
504     push @output_makefiles, "Final.mk";
505     start_output_file("Final.mk.tmp");
506     my %ntargets;
507     my $esclit='&';
508     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
509     delete $ntargets{$_} foreach @$otargets;
510     my @ntargets = sort keys %ntargets;
511     die "subdirmk: Final.sd.mk may not introduce new top-level targets".
512         " (@ntargets)\n" if @ntargets;
513 }
514
515 sub process_tree() {
516     my @targets = process_subtree($root, [ ]);
517     process_final(\@targets);
518     start_output_file("main.mk.tmp");
519     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
520         oraw "$v=\@$v@\n";
521     }
522     oraw "SUBDIRMK_MAKEFILES :=\n";
523     oraw "MAKEFILE_TEMPLATES :=\n";
524     foreach my $mf (@output_makefiles) {
525         oraw "SUBDIRMK_MAKEFILES += $mf\n";
526     }
527     foreach my $input (sort keys %input_files) {
528         oraw "MAKEFILE_TEMPLATES += $input\n";
529     }
530     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
531 }
532
533 sub flmap ($) { local ($_) = @_; s{:(\d+)$}{ sprintf ":%10d", $1 }e; $_; }
534
535 sub print_varref_warnings () {
536     foreach my $vn (sort keys %varref) {
537         my $vv = $varref{$vn};
538         next unless $vv->{''}{''} && $vv->{''}{1};
539         wrncore 'local+global', "saw both $vn and &$vn" or return;
540         foreach my $exp ('', 1) {
541         foreach my $amp ('', 1) {
542             printf STDERR
543                 ($exp
544                  ? " expectedly saw %s%s at %s\n"
545                  : " saw %s%s at %s\n"),
546                 ($amp ? '&' : ''), $vn, $_
547                 foreach
548                 sort { flmap($a) cmp flmap($b) }
549                 keys %{ $vv->{$exp}{$amp} };
550         }
551         }
552     }
553 }
554
555 sub print_warning_warnings () {
556     return unless $warned;
557     foreach my $wk (sort keys %warn_unk) {
558         wrncore 'unknown-warning',
559             "$warn_unk{$wk}: attempt to suppress unknown warning(s) \`$wk'";
560     }
561 }
562
563 build_tree();
564 process_tree();
565 print_varref_warnings();
566 print_warning_warnings();
567 install_output_files();