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