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