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