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