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