chiark / gitweb /
doctests: Improve entry description filter
[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
184     while (<$input>) {
185         if (s#^\s*$esc\:changequote\s+(\S+)\s+$##) {
186             $$esclitr = $1;
187             $set_esc->();
188             next;
189         } elsif (s#^\s*$esc\:(?=(-?)include)##) {
190             $buffering_output='';
191         } elsif (m#^\s*$esc\:([a-z][-0-9a-z_]*)#) {
192             die "unknown directive $1";
193         } elsif (s{^\s*${esc}TARGETS(?:_([0-9a-zA-Z_]+))?(?=\W)}{}) {
194             my $t = $1 // 'all';
195             od target_varname($var_prefix, $t);
196             $targets->{$t} //= [ ];
197         }
198         for (;;) {
199             die if $ddbl && defined $buffering_output;
200             unless (s{^(.*?)$esc}{}) { od $_; last; }
201             od $1;
202             if (s{^\\$esc}{}) { od "$$esclitr" }
203             elsif (s{^\\\$}{}) { oud '$' }
204             elsif (s{^\\\s+$}{}) { }
205             elsif (s{^$esc}{}) { od "$$esclitr$$esclitr" }
206             elsif (m{^(?=$caps_re)}) { od $var_prefix }
207             elsif (s{^\$([A-Za-z]\w+)}{}) { od "\$(${var_prefix}$1)" }
208             elsif (s{^([~^]?)(?=$lc_re)}{}) { od $pfxmap{$1} }
209             elsif (s{^_}{}) { od $var_prefix }
210             elsif (s{^=}{}) { od $var_prefix_name }
211             elsif (s{^([~^]?)/}{}) { od $pfxmap{$1} }
212             elsif (s{^\.}{}) { od $dir_name }
213             elsif (s{^([~^])\.}{}) { od $srcdirmap{$1} }
214             elsif (s{^\$\-}{}) { $ddbl=undef; }
215             elsif (s{^\$\+}{}) { $ddbl=1; }
216             elsif (s{^\$\(}{}) { die unless $ddbl; oud "\$("; }
217             elsif (s{^\$(\d+)}{}) { die unless $ddbl; oud "\$($1)"; }
218             elsif (s{^([~^]?)(?=[ \t])}{}) {
219                 my $prefix = $pfxmap{$1} // die;
220                 my $after='';
221                 if (m{([ \t])$esc}) { ($_,$after) = ($`, $1.$'); }
222                 s{(?<=[ \t])(?=\S)(?!\\\s*$)}{$prefix}g;
223                 od $_;
224                 $_ = $after;
225             } elsif (s{^\#}{}) {
226                 $_ = '';
227             } elsif (s{^![ \t]+}{}) {
228                 od $_;
229                 $_ = '';
230             } else {
231                 die "bad escape $$esclitr$_ ";
232             }
233         }
234         if (defined $buffering_output) {
235             $_=$buffering_output;
236             $buffering_output=undef;
237             if (m#^(-?)include\s+(\S+)\s+$#) {
238                 my $subf = "$srcdir/$2";
239                 process_input_mk($targets, $subf, $esclitr, $1);
240                 od "\n";
241             } else {
242                 die "internal error buffering directive $_ ";
243             }
244         }
245     }
246     $input->error and die "read $f: $!\n";
247     close $input or die "close $f: $!\n";
248 }
249
250 sub filter_subdir_mk ($) {
251     my ($targets) = @_;
252
253     #use Data::Dumper;
254     #print STDERR "filter @_\n";
255
256     my $esclit = '&';
257
258     my $pi = sub {
259         my ($f, $enoentok) = @_;
260         process_input_mk($targets, "${srcdir}/$f", \$esclit, $enoentok);
261     };
262     $pi->("Prefix.sd.mk",              1);
263     $pi->("${dir_prefix}Subdir.sd.mk", 0);
264     $pi->("Suffix.sd.mk",              1);
265 }
266
267 sub process_subtree ($$);
268 sub process_subtree ($$) {
269     # => list of targets (in form SUBDIR/)
270     # recursive, children first
271     my ($node, $path) = @_;
272
273     #use Data::Dumper;
274     #print STDERR Dumper(\@_);
275
276     my $dir_prefix = dir_prefix($path);
277     # ^ this is the only var which we need before we come back from
278     #   the recursion.
279
280     push @output_makefiles, "${dir_prefix}Subdir.mk";
281     write_makefile($dir_prefix, scalar @$path);
282
283     my %targets = (all => []);
284     foreach my $child (@{ $node->[1] }) {
285         my @childpath = (@$path, $child->[0]);
286         my $child_subdir = join '/', @childpath;
287         mkdir $child_subdir or $!==EEXIST or die "mkdir $child_subdir: $!";
288         push @{ $targets{$_} }, $child_subdir foreach
289             process_subtree($child, \@childpath);
290     }
291
292     set_dir_vars($path);
293     start_output_file("${dir_prefix}Subdir.mk.tmp");
294
295     if ($node->[2]) {
296         filter_subdir_mk(\%targets);
297     } else {
298         my $sdmk = "${dir_prefix}Subdir.sd.mk";
299         if (stat $sdmk) {
300             die "$sdmk unexpectedly exists (${dir_prefix} not mentioned)";
301         } elsif ($!==ENOENT) {
302         } else {
303             die "stat $sdmk: $!";
304         }
305     }
306
307     oraw "\n";
308
309     my @targets = sort keys %targets;
310     foreach my $target (@targets) {
311         my $target_varname = target_varname($var_prefix, $target);
312         print O "${dir_prefix}${target}:: \$($target_varname)";
313         foreach my $child_subdir (@{ $targets{$target} }) {
314             print O " $child_subdir/$target";
315         }
316         print O "\n";
317     }
318     if (@targets) {
319         print O ".PHONY:";
320         print O " ${dir_prefix}${_}" foreach @targets;
321         print O "\n";
322     }
323
324     return @targets;
325 }
326
327 sub process_final ($) {
328     my ($otargets) = @_;
329     set_dir_vars([]);
330     push @output_makefiles, "Final.mk";
331     start_output_file("Final.mk.tmp");
332     my %ntargets;
333     my $esclit='&';
334     process_input_mk(\%ntargets, "${srcdir}/Final.sd.mk", \$esclit, 1);
335     delete $ntargets{$_} foreach @$otargets;
336     my @ntargets = sort keys %ntargets;
337     die "late new targets @ntargets" if @ntargets;
338 }
339
340 sub process_tree() {
341     my @targets = process_subtree($root, [ ]);
342     process_final(\@targets);
343     start_output_file("main.mk.tmp");
344     foreach my $v (qw(top_srcdir abs_top_srcdir)) {
345         oraw "$v=\@$v@\n";
346     }
347     oraw "SUBDIRMK_MAKEFILES :=\n";
348     oraw "MAKEFILE_TEMPLATES :=\n";
349     foreach my $mf (@output_makefiles) {
350         oraw "SUBDIRMK_MAKEFILES += $mf\n";
351     }
352     foreach my $input (sort keys %input_files) {
353         oraw "MAKEFILE_TEMPLATES += $input\n";
354     }
355     oraw "include \$(SUBDIRMK_MAKEFILES)\n";
356 }
357
358 build_tree();
359 process_tree();
360 install_output_files();