chiark / gitweb /
2e77df3749084dc480b997e9bb83fdcb3329178a
[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 (@nest && $nest[0][0] eq 'Eval'
217                     ? s{^(.*?)($esc|[{}])}{}
218                     : s{^(.*?)($esc)}{}) { od $_; last; }
219             od $1;
220             if ($2 eq '{') {
221                 $ddbl++;
222                 next;
223             } elsif ($2 eq '}') {
224                 next if --$ddbl;
225                 $pop_nest->('Eval');
226                 od '}}';
227                 next;
228             }
229             if (s{^\\$esc}{}) { od "$$esclitr" }
230             elsif (s{^\\\$}{}) { oud '$' }
231             elsif (s{^\\\s+$}{}) { }
232             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
233             elsif (m{^(?=$caps_re)}) { od $var_prefix }
234             elsif (s{^\$([A-Za-z]\w+)}{}) { od "\$(${var_prefix}$1)" }
235             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
236             elsif (s{^_}{}) { od $var_prefix }
237             elsif (s{^=}{}) { od $var_prefix_name }
238             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
239             elsif (s{^\.}{}) { od $dir_name }
240             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
241             elsif (s{^\$\-}{}) { $ddbl=undef; }
242             elsif (s{^\$\+}{}) { $ddbl=1; }
243             elsif (s{^\$\(}{}) { die unless $ddbl; oud "\$("; }
244             elsif (s{^\$(\d+)}{}) { die unless $ddbl; oud "\$($1)"; }
245             elsif (s{^\$\{}{}) {
246                 die if $ddbl;
247                 od '${eval ${call ';
248                 $push_nest->('Eval',1);
249             } elsif (s{^([~^]?)(?=[ \t])}{}) {
250                 my $prefix = $pfxmap{$1} // die;
251                 my $after='';
252                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
253                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
254                 od $_;
255                 $_ = $after;
256             } elsif (s{^\#}{}) {
257                 $_ = '';
258             } elsif (s{^![ \t]+}{}) {
259                 od $_;
260                 $_ = '';
261             } else {
262                 die "bad escape $$esclitr$_ ";
263             }
264         }
265         if (defined $buffering_output) {
266             $_=$buffering_output;
267             $buffering_output=undef;
268             if (m#^(-?)include\s+(\S+)\s+$#) {
269                 my $subf = "$srcdir/$2";
270                 process_input_mk($targets, $subf, $esclitr, $1);
271                 od "\n";
272             } elsif (m#^macro\s+(\S+)\s+$#) {
273                 od "define $1\n";
274                 $push_nest->('Macro', 1);
275             } else {
276                 die "internal error buffering directive $_ ";
277             }
278         }
279     }
280     die "unclosed $nest[0][0]" if @nest;
281     $input->error and die "read $f: $!\n";
282     close $input or die "close $f: $!\n";
283 }
284
285 sub filter_subdir_mk ($) {
286     my ($targets) = @_;
287
288     #use Data::Dumper;
289     #print STDERR "filter @_\n";
290
291     my $esclit = '&';
292
293     my $pi = sub {
294         my ($f, $enoentok) = @_;
295         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
296     };
297     $pi->("Prefix.sd.mk",              1);
298     $pi->("${dir_prefix}Subdir.sd.mk", 0);
299     $pi->("Suffix.sd.mk",              1);
300 }
301
302 sub process_subtree ($$);
303 sub process_subtree ($$) {
304     # => list of targets (in form SUBDIR/)
305     # recursive, children first
306     my ($node, $path) = @_;
307
308     #use Data::Dumper;
309     #print STDERR Dumper(\@_);
310
311     my $dir_prefix = dir_prefix($path);
312     # ^ this is the only var which we need before we come back from
313     #   the recursion.
314
315     push @output_makefiles, "${dir_prefix}Subdir.mk";
316     write_makefile($dir_prefix, scalar @$path);
317
318     my %targets = (all => []);
319     foreach my $child (@{ $node->[1] }) {
320         my @childpath = (@$path, $child->[0]);
321         my $child_subdir = join '/', @childpath;
322         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!";
323         push @{ $targets{$_} }, $child_subdir foreach
324             process_subtree($child, \@childpath);
325     }
326
327     set_dir_vars($path);
328     start_output_file("${dir_prefix}Subdir.mk.tmp");
329
330     if ($node->[2]) {
331         filter_subdir_mk(\%targets);
332     } else {
333         my $sdmk = "${dir_prefix}Subdir.sd.mk";
334         if (stat $sdmk) {
335             die "$sdmk unexpectedly exists (${dir_prefix} not mentioned)";
336         } elsif ($!==ENOENT) {
337         } else {
338             die "stat $sdmk: $!";
339         }
340     }
341
342     oraw "\n";
343
344     my @targets = sort keys %targets;
345     foreach my $target (@targets) {
346         my $target_varname = target_varname($var_prefix, $target);
347         print O "${dir_prefix}${target}:: \$($target_varname)";
348         foreach my $child_subdir (@{ $targets{$target} }) {
349             print O " $child_subdir/$target";
350         }
351         print O "\n";
352     }
353     if (@targets) {
354         print O ".PHONY:";
355         print O " ${dir_prefix}${_}" foreach @targets;
356         print O "\n";
357     }
358
359     return @targets;
360 }
361
362 sub process_final ($) {
363     my ($otargets) = @_;
364     set_dir_vars([]);
365     push @output_makefiles, "Final.mk";
366     start_output_file("Final.mk.tmp");
367     my %ntargets;
368     my $esclit='&';
369     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
370     delete $ntargets{$_} foreach @$otargets;
371     my @ntargets = sort keys %ntargets;
372     die "late new targets @ntargets" if @ntargets;
373 }
374
375 sub process_tree() {
376     my @targets = process_subtree($root, [ ]);
377     process_final(\@targets);
378     start_output_file("main.mk.tmp");
379     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
380         oraw "$v=\@$v@\n";
381     }
382     oraw "SUBDIRMK_MAKEFILES :=\n";
383     oraw "MAKEFILE_TEMPLATES :=\n";
384     foreach my $mf (@output_makefiles) {
385         oraw "SUBDIRMK_MAKEFILES += $mf\n";
386     }
387     foreach my $input (sort keys %input_files) {
388         oraw "MAKEFILE_TEMPLATES += $input\n";
389     }
390     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
391 }
392
393 build_tree();
394 process_tree();
395 install_output_files();