chiark / gitweb /
3ccfa0dd090673a2f4a04d1bd799450a191fd025
[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 #     Subdir.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 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 oraw {
73     die unless defined $writing_output;
74     print O @_ or die "error writing $writing_output.tmp: $!\n";
75 }
76
77 sub oud { # undoubled
78     if (defined $buffering_output) {
79         $buffering_output .= $_ foreach @_;
80         return;
81     }
82     oraw @_;
83 }
84
85 our $ddbl;
86
87 sub od { # maybe $-doubled
88     if (!$ddbl) {
89         oud @_;
90         return;
91     }
92     foreach (@_) {
93         my $e = $_;
94         $e =~ s{\$}{\$\$}g;
95         oud $e;
96     }
97 }
98
99 sub start_output_file ($) {
100     close_any_output_file();
101     ($writing_output) = @_;
102     die "$writing_output ?" if $output_files{$writing_output}++;
103     my $tmp = "$writing_output.tmp";
104     open O, ">", $tmp or die "create $tmp: $!\n";
105     oraw "# autogenerated - do not edit\n";
106 }
107
108 sub install_output_files () {
109     close_any_output_file();
110     foreach my $f (sort keys %output_files) {
111         rename "$f.tmp", $f or die "install new $f: $!\n";
112     }
113 }
114
115 sub write_makefile ($$) {
116     my ($dir_prefix,$depth) = @_;
117     #print STDERR "write_makefile @_\n";
118     start_output_file("${dir_prefix}Makefile");
119     my $cd = $depth ? join('/', ('..',) x $depth) : '.';
120     my $suppress_templates=
121         '$(if $(filter-out clean real-clean, $(subdirmk_targets)),,'.
122         ' MAKEFILE_TEMPLATES=)';
123     oraw <<END;
124 default: all
125 \$(filter-out all,\$(MAKECMDGOALS)) all: run-main.mk
126         \@:
127 subdirmk_targets:=\$(or \$(MAKECMDGOALS),all)
128 Makefile run-main.mk:
129         \$(MAKE) -C $cd -f main.mk \$(addprefix ${dir_prefix},\$(subdirmk_targets))$suppress_templates
130 .SUFFIXES:
131 .PHONY: run-main.mk
132 END
133 }
134
135 our ($dir_prefix, $dir_suffix, $dir_name,
136      $var_prefix, $var_prefix_name);
137
138 sub dir_prefix ($) {
139     my ($path) = @_;
140     join '', map { "$_/" } @$path;
141 }
142
143 sub set_dir_vars ($) {
144     my ($path) = @_;
145     $dir_prefix = dir_prefix($path);
146     $dir_suffix = join '', map { "/$_" } @$path;
147     $dir_name = join '/', @$path ? @$path : '.';
148     $var_prefix_name = join '_', @$path ? @$path : qw(TOP);
149     $var_prefix = "${var_prefix_name}_";
150 }
151
152 sub process_input_mk ($$$$);
153 sub process_input_mk ($$$$) {
154     my ($targets, $f, $esclitr, $enoent_ok) = @_;
155
156     my $caps_re = qr{[A-Z]};
157     my $lc_re = qr{[a-z]};
158
159     my $esc;
160     my $set_esc = sub {
161         $esc = $$esclitr;
162         $esc =~ s/\W/\\$&/g;
163     };
164     $set_esc->();
165
166     my $input = new IO::File $f, '<';
167     if (!$input) {
168         die "open $f: $!\n" unless $!==ENOENT && $enoent_ok;
169         return;
170     }
171     $input_files{$f}++;
172
173     my %srcdirmap = (
174                   '^' => "\$(top_srcdir)${dir_suffix}",
175                   '~' => "\$(top_srcdir)",
176                     );
177     my %pfxmap = (
178                   ''  => $dir_prefix,
179                  );
180     $pfxmap{$_} = $srcdirmap{$_}.'/' foreach keys %srcdirmap;
181
182     local $ddbl;
183     my @nest;
184
185     my $push_nest = sub {
186         my ($nk, $nndbl) = @_;
187         unshift @nest, [ $nk, $ddbl ];
188         $ddbl = $nndbl;
189     };
190     my $pop_nest = sub {
191         my ($nk) = @_;
192         die unless $nest[0][0] eq $nk;
193         $ddbl = (shift @nest)[1];
194     };
195
196     while (<$input>) {
197         if (s#^\s*$esc\:changequote\s+(\S+)\s+$##) {
198             $$esclitr = $1;
199             $set_esc->();
200             next;
201         } elsif (s#^\s*$esc\:endm\s+$##) {
202             $pop_nest->('Macro');
203             od "endef\n";
204             next;
205         } elsif (s#^\s*$esc\:(?=(-?)include|macro)##) {
206             $buffering_output='';
207         } elsif (m#^\s*$esc\:([a-z][-0-9a-z_]*)#) {
208             die "unknown directive $1";
209         } elsif (s{^\s*${esc}TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
210             my $t = $1 // 'all';
211             od target_varname($var_prefix, $t);
212             $targets->{$t} //= [ ];
213         }
214         for (;;) {
215             die if $ddbl && defined $buffering_output;
216             unless (s{^(.*?)$esc}{}) { od $_; last; }
217             od $1;
218             if (s{^\\$esc}{}) { od "$$esclitr" }
219             elsif (s{^\\\$}{}) { oud '$' }
220             elsif (s{^\\\s+$}{}) { }
221             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
222             elsif (m{^(?=$caps_re)}) { od $var_prefix }
223             elsif (s{^\$([A-Za-z]\w+)}{}) { od "\$(${var_prefix}$1)" }
224             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
225             elsif (s{^_}{}) { od $var_prefix }
226             elsif (s{^=}{}) { od $var_prefix_name }
227             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
228             elsif (s{^\.}{}) { od $dir_name }
229             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
230             elsif (s{^\$\-}{}) { $ddbl=undef; }
231             elsif (s{^\$\+}{}) { $ddbl=1; }
232             elsif (s{^\$\(}{}) { die unless $ddbl; oud "\$("; }
233             elsif (s{^\$(\d+)}{}) { die unless $ddbl; oud "\$($1)"; }
234             elsif (s{^([~^]?)(?=[ \t])}{}) {
235                 my $prefix = $pfxmap{$1} // die;
236                 my $after='';
237                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
238                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
239                 od $_;
240                 $_ = $after;
241             } elsif (s{^\#}{}) {
242                 $_ = '';
243             } elsif (s{^![ \t]+}{}) {
244                 od $_;
245                 $_ = '';
246             } else {
247                 die "bad escape $$esclitr$_ ";
248             }
249         }
250         if (defined $buffering_output) {
251             $_=$buffering_output;
252             $buffering_output=undef;
253             if (m#^(-?)include\s+(\S+)\s+$#) {
254                 my $subf = "$srcdir/$2";
255                 process_input_mk($targets, $subf, $esclitr, $1);
256                 od "\n";
257             } elsif (m#^macro\s+(\S+)\s+$#) {
258                 od "define $1\n";
259                 $push_nest->('Macro', 1);
260             } else {
261                 die "internal error buffering directive $_ ";
262             }
263         }
264     }
265     $input->error and die "read $f: $!\n";
266     close $input or die "close $f: $!\n";
267 }
268
269 sub filter_subdir_mk ($) {
270     my ($targets) = @_;
271
272     #use Data::Dumper;
273     #print STDERR "filter @_\n";
274
275     my $esclit = '&';
276
277     my $pi = sub {
278         my ($f, $enoentok) = @_;
279         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
280     };
281     $pi->("Prefix.sd.mk",              1);
282     $pi->("${dir_prefix}Subdir.sd.mk", 0);
283     $pi->("Suffix.sd.mk",              1);
284 }
285
286 sub process_subtree ($$);
287 sub process_subtree ($$) {
288     # => list of targets (in form SUBDIR/)
289     # recursive, children first
290     my ($node, $path) = @_;
291
292     #use Data::Dumper;
293     #print STDERR Dumper(\@_);
294
295     my $dir_prefix = dir_prefix($path);
296     # ^ this is the only var which we need before we come back from
297     #   the recursion.
298
299     push @output_makefiles, "${dir_prefix}Subdir.mk";
300     write_makefile($dir_prefix, scalar @$path);
301
302     my %targets = (all => []);
303     foreach my $child (@{ $node->[1] }) {
304         my @childpath = (@$path, $child->[0]);
305         my $child_subdir = join '/', @childpath;
306         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!";
307         push @{ $targets{$_} }, $child_subdir foreach
308             process_subtree($child, \@childpath);
309     }
310
311     set_dir_vars($path);
312     start_output_file("${dir_prefix}Subdir.mk.tmp");
313
314     if ($node->[2]) {
315         filter_subdir_mk(\%targets);
316     } else {
317         my $sdmk = "${dir_prefix}Subdir.sd.mk";
318         if (stat $sdmk) {
319             die "$sdmk unexpectedly exists (${dir_prefix} not mentioned)";
320         } elsif ($!==ENOENT) {
321         } else {
322             die "stat $sdmk: $!";
323         }
324     }
325
326     oraw "\n";
327
328     my @targets = sort keys %targets;
329     foreach my $target (@targets) {
330         my $target_varname = target_varname($var_prefix, $target);
331         print O "${dir_prefix}${target}:: \$($target_varname)";
332         foreach my $child_subdir (@{ $targets{$target} }) {
333             print O " $child_subdir/$target";
334         }
335         print O "\n";
336     }
337     if (@targets) {
338         print O ".PHONY:";
339         print O " ${dir_prefix}${_}" foreach @targets;
340         print O "\n";
341     }
342
343     return @targets;
344 }
345
346 sub process_final ($) {
347     my ($otargets) = @_;
348     set_dir_vars([]);
349     push @output_makefiles, "Final.mk";
350     start_output_file("Final.mk.tmp");
351     my %ntargets;
352     my $esclit='&';
353     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
354     delete $ntargets{$_} foreach @$otargets;
355     my @ntargets = sort keys %ntargets;
356     die "late new targets @ntargets" if @ntargets;
357 }
358
359 sub process_tree() {
360     my @targets = process_subtree($root, [ ]);
361     process_final(\@targets);
362     start_output_file("main.mk.tmp");
363     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
364         oraw "$v=\@$v@\n";
365     }
366     oraw "SUBDIRMK_MAKEFILES :=\n";
367     oraw "MAKEFILE_TEMPLATES :=\n";
368     foreach my $mf (@output_makefiles) {
369         oraw "SUBDIRMK_MAKEFILES += $mf\n";
370     }
371     foreach my $input (sort keys %input_files) {
372         oraw "MAKEFILE_TEMPLATES += $input\n";
373     }
374     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
375 }
376
377 build_tree();
378 process_tree();
379 install_output_files();