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