chiark / gitweb /
generate: Track output Makefiles properly
[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        from in each subdirectory
10 #     Subdir.mk.tmp                         Subdir.sd.mk
11 #     Makefile                          and included files
12 # and in toplevel                       and in toplevel
13 #     main.mk.tmp                           Perdir.sd.mk
14
15 use strict;
16 use POSIX;
17
18 print "$0 @ARGV\n" or die $!;
19
20 our $srcdir='.';
21
22 while (@ARGV && $ARGV[0] =~ m/^-/) {
23     $_ = shift @ARGV;
24     last if $_ eq '--';
25     if (s/^--srcdir=//) {
26         $srcdir=$';
27     } else {
28         die "$0: unknown option \`$_'\n";
29     }
30 }
31 our @subdirs = @ARGV;
32
33 s{/+$}{} foreach @subdirs;
34
35 our $root = [ '.', [ ], 1 ];
36 # each node is [ 'relative subdir name', \@children, $mentioned ]
37
38 sub build_tree () {
39     foreach my $subdir (@subdirs) {
40         my @path = $subdir eq '.' ? () : split m{/+}, $subdir;
41         my $node = $root;
42         foreach my $d (@path) {
43             my ($c,) = grep { $_->[0] eq $d } @{ $node->[1] };
44             if (!$c) {
45                 $c = [ $d, [ ] ];
46                 push @{ $node->[1] }, $c;
47             }
48             $node = $c;
49         }
50         $node->[2] = 1;
51     }
52 }
53
54 sub target_varname ($$) {
55     my ($var_prefix, $target) = @_;
56     return $var_prefix.'TARGETS'.($target eq 'all' ? '' : "_$target");
57 }
58
59 our $writing_output;
60 our $buffering_output;
61 our %output_files;
62 our %input_files;
63 our @output_makefiles;
64
65 sub close_any_output_file() {
66     return unless defined $writing_output;
67     O->error and die "error writing $writing_output.tmp: $! (?)\n";
68     close O or die "error closing $writing_output.tmp: $!\n";
69     $writing_output = undef;
70 }
71
72 sub o {
73     if (defined $buffering_output) {
74         $buffering_output .= $_ foreach @_;
75         return;
76     }
77     die unless defined $writing_output;
78     print O @_ or die "error writing $writing_output.tmp: $!\n";
79 }
80
81 sub start_output_file ($) {
82     close_any_output_file();
83     ($writing_output) = @_;
84     die "$writing_output ?" if $output_files{$writing_output}++;
85     my $tmp = "$writing_output.tmp";
86     open O, ">", $tmp or die "create $tmp: $!\n";
87     o "# autogenerated - do not edit\n";
88 }
89
90 sub install_output_files () {
91     close_any_output_file();
92     foreach my $f (sort keys %output_files) {
93         rename "$f.tmp", $f or die "install new $f: $!\n";
94     }
95 }
96
97 sub write_makefile ($$) {
98     my ($dir_prefix,$depth) = @_;
99     #print STDERR "write_makefile @_\n";
100     start_output_file("${dir_prefix}Makefile");
101     my $cd = $depth ? join('/', ('..',) x $depth) : '.';
102     my $suppress_templates=
103         '$(if $(filter-out clean real-clean, $(subdirmk_targets)),,'.
104         ' MAKEFILE_TEMPLATES=)';
105     o <<END;
106 default: all
107 \$(filter-out all,\$(MAKECMDGOALS)) all: run-main.mk
108         \@:
109 subdirmk_targets:=\$(or \$(MAKECMDGOALS),all)
110 Makefile run-main.mk:
111         \$(MAKE) -C $cd -f main.mk \$(addprefix ${dir_prefix},\$(subdirmk_targets))$suppress_templates
112 .SUFFIXES:
113 .PHONY: run-main.mk
114 END
115 }
116
117 sub process_input_mk ($$$$$$$$);
118 sub process_input_mk ($$$$$$$$) {
119     my ($dir_prefix, $dir_suffix, $dir_name,
120         $var_prefix, $targets,
121         $f, $esclitr, $enoent_ok) = @_;
122
123     my $caps_re = qr{[A-Z]};
124     my $lc_re = qr{[a-z]};
125
126     my $esc;
127     my $set_esc = sub {
128         $esc = $$esclitr;
129         $esc =~ s/\W/\\$&/g;
130     };
131     $set_esc->();
132
133     my $input = new IO::File $f, '<';
134     if (!$input) {
135         die "open $f: $!\n" unless $!==ENOENT && $enoent_ok;
136         return;
137     }
138     $input_files{$f}++;
139
140     my %pfxmap = (
141                   ''  => $dir_prefix,
142                   '^' => "\$(top_srcdir)${dir_suffix}/",
143                   '~' => "\$(top_srcdir)/",
144                  );
145
146     while (<$input>) {
147         if (s#^\s*$esc\:##) {
148             $buffering_output='';
149         }
150         for (;;) {
151             unless (s{^(.*?)(\\)?(?=$esc)}{}) { o $_; last; }
152             o $1;
153             if ($2) { s#^$esc##; o $$esclitr; next; }
154             s{^$esc}{} or die "$_ ?";
155             if (s{^$esc}{}) { o "$$esclitr$$esclitr" }
156             elsif (s{^TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
157                 my $t = $1 // 'all';
158                 o target_varname($var_prefix, $t);
159                 $targets->{$t} //= [ ];
160             }
161             elsif (m{^(?=$caps_re)}) { o $var_prefix }
162             elsif (s{^([~^]?)(?=$lc_re)}{}) { o $pfxmap{$1} }
163             elsif (s{^_}{}) { o $var_prefix }
164             elsif (s{^=_}{}) { o $var_prefix }
165             elsif (s{^([~^]?)/}{}) { o $pfxmap{$1} }
166             elsif (s{^=/}{}) { o $dir_name }
167             elsif (s{^([~^]?)(?=[ \t])}{}) {
168                 my $prefix = $pfxmap{$1} // die;
169                 my $after='';
170                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
171                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
172                 o $_;
173                 $_ = $after;
174             } elsif (s{^\#}{}) {
175                 $_ = '';
176             } elsif (s{^![ \t]+}{}) {
177                 o $_;
178                 $_ = '';
179             } elsif (s{^!(\S+)(?:[ \t]+|$)}{}) {
180                 $$esclitr = $1;
181                 $set_esc->();
182             } else {
183                 die "bad escape $$esclitr$_ ";
184             }
185         }
186         if (defined $buffering_output) {
187             $_=$buffering_output;
188             $buffering_output=undef;
189             if (m#^(-?)include\s+(\S+)\s+$#) {
190                 my $subf = "$srcdir/$2";
191                 process_input_mk($dir_prefix, $dir_suffix, $dir_name,
192                                  $var_prefix, $targets,
193                                  $subf, $esclitr, $1);
194                 o "\n";
195             } else {
196                 die "unknown directive $_ ";
197             }
198         }
199     }
200     $input->error and die "read $f: $!\n";
201     close $input or die "close $f: $!\n";
202 }
203
204 sub filter_subdir_mk ($$$$$) {
205     my ($dir_prefix, $dir_suffix, $dir_name,
206         $var_prefix, $targets) = @_;
207
208     #use Data::Dumper;
209     #print STDERR "filter @_\n";
210
211     my $esclit = '&';
212
213     my $pi = sub {
214         my ($f, $enoentok) = @_;
215         process_input_mk($dir_prefix, $dir_suffix, $dir_name,
216                          $var_prefix, $targets,
217                          "${srcdir}/$f", \$esclit, $enoentok);
218     };
219     $pi->("${dir_prefix}Subdir.sd.mk", 0);
220     $pi->("Perdir.sd.mk",              1);
221 }
222
223 sub process_subtree ($$);
224 sub process_subtree ($$) {
225     # => list of descendants (in form SUBDIR/)
226     # recursive, children first
227     my ($node, $path) = @_;
228
229     #use Data::Dumper;
230     #print STDERR Dumper(\@_);
231
232     my $dir_prefix = join '', map { "$_/" } @$path;
233     my $dir_suffix = join '', map { "/$_" } @$path;
234     my $dir_name = join '/', @$path ? @$path : '.';
235     my $var_prefix = join '', map { "${_}_" } @$path ? @$path : qw(TOP);
236
237     push @output_makefiles, "${dir_prefix}Subdir.mk";
238     write_makefile($dir_prefix, scalar @$path);
239
240     my %targets = (all => []);
241     foreach my $child (@{ $node->[1] }) {
242         my @childpath = (@$path, $child->[0]);
243         my $child_subdir = join '/', @childpath;
244         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!";
245         push @{ $targets{$_} }, $child_subdir foreach
246             process_subtree($child, \@childpath);
247     }
248     start_output_file("${dir_prefix}Subdir.mk.tmp");
249
250     if ($node->[2]) {
251         filter_subdir_mk($dir_prefix, $dir_suffix, $dir_name,
252                          $var_prefix, \%targets);
253     } else {
254         my $sdmk = "${dir_prefix}Subdir.sd.mk";
255         if (stat $sdmk) {
256             die "$sdmk unexpectedly exists (${dir_prefix} not mentioned)";
257         } elsif ($!==ENOENT) {
258         } else {
259             die "stat $sdmk: $!";
260         }
261     }
262
263     o "\n";
264
265     my @targets = sort keys %targets;
266     foreach my $target (@targets) {
267         my $target_varname = target_varname($var_prefix, $target);
268         print O "${dir_prefix}${target}:: \$($target_varname)";
269         foreach my $child_subdir (@{ $targets{$target} }) {
270             print O " $child_subdir/$target";
271         }
272         print O "\n";
273     }
274     if (@targets) {
275         print O ".PHONY:";
276         print O " ${dir_prefix}${_}" foreach @targets;
277         print O "\n";
278     }
279
280     return @targets;
281 }
282
283 sub process_tree() {
284     process_subtree($root, [ ]);
285     start_output_file("main.mk.tmp");
286     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
287         o "$v=\@$v@\n";
288     }
289     o "SUBDIRMK_MAKEFILES :=\n";
290     o "MAKEFILE_TEMPLATES :=\n";
291     foreach my $mf (@output_makefiles) {
292         o "SUBDIRMK_MAKEFILES += $mf\n";
293     }
294     foreach my $input (sort keys %input_files) {
295         o "MAKEFILE_TEMPLATES += $input\n";
296     }
297     o "include \$(SUBDIRMK_MAKEFILES)\n";
298 }
299
300 build_tree();
301 process_tree();
302 install_output_files();