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