3 # script for extracting doctests from README
6 # expand <README | tests/filter/extract-doctest tests/filter/
8 # tests/filter/doctest.mk.part
9 # tests/filter/sub/dir/doctest.mk.part
11 # Relies on some properties of the way README is laid out.
12 # See comments below marked `parse:' and `adhoc:'.
27 my $withspcs = qr{\S+(?: \S+)*};
29 my $outdir = shift @ARGV // confess;
32 # adhoc: rely on structure of indented examples in &:changequote part
33 $in_changequote = (m{^\&\:changequote}...m{^\S}) && m{^\s};
34 if (m{^-----|^- - - - -}) {
35 # parse: rely on underlines for (sub)section headings
41 # parse: rely on looking for => (and .. on subsequent lines)
42 next unless m{\=\>} or ($cent and m{ \.\. });
44 # adhoc: special case NEWQUOTE here so we recognise things in changequote
45 if (s{^(\s*)(\&\S+|NEWQUOTE\S+|\$)\s+(\=\>|\.\.)\s+(\S+)\s+}{} ||
46 s{^()(\&\:\w+(?: \S+)*)\s{2,}(\=\>)\s{2,}($withspcs)$}{} ||
47 $cent && s{^()($withspcs)\s{2,}(\.\.)\s{2,}($withspcs)$}{}) {
48 # adhoc: expected indented iff in changequote part
49 confess if length($1) xor $in_changequote;
51 confess if !$cent && $mapop ne '=>';
54 if (# adhoc: `or ...' introduces the `at toplevel' expansion
56 $e->{OutTop} = $1 eq 'nothing' ? '' : $1;
57 } elsif (# parse: expect other wordish things to be comments
58 m{^(?!or\b)\w{2,} }) {
60 $e->{CQ} = $in_changequote;
65 if ($e->{In} =~ m/\bNN\b/) {
66 # adhoc: special case NN in examples
67 confess if defined $cent->{OutTop};
68 foreach my $nn (0..11, 999) {
70 foreach my $k (qw(In Out)) {
72 ($f->{$k} =~ s/\bNN\b/$nn/g) == 1 or confess;
81 } elsif ($mapop eq '..') {
82 confess if defined $cent->{OutTop};
83 foreach my $k (qw(In Out)) {
84 $cent->{$k} .= "\n".$e->{$k};
91 sub oi { print I @_ or die $!; }
92 sub oo { print O @_ or die $!; }
93 sub oh { oi @_; oo @_; }
95 sub write_permode ($$$$$;$$) {
96 my ($dir_prefix, $start, $end, $senl, $what,
98 $filter //= sub { 1 };
99 $omap //= sub { $_[0] };
101 oh "${senl}# ----- $what starts -----\n";
102 foreach my $e (@exp) {
103 next unless $filter->($e);
104 my $rubric = $e->{In};
105 $rubric =~ s/\&/AMP /g;
106 $rubric =~ s/\$/DOLLAR /g;
107 $rubric =~ s/NEWQUOTE/NEW_QUOTE /g;
108 my $f = $e->{In} =~ m/\n/
112 $o = $e->{OutTop} if $dir_prefix eq '';
114 $o =~ s{/sub/dir}{} if $dir_prefix eq '' && !defined $e->{OutTop};
115 $o = $omap->($o, $e);
116 oi sprintf $f, $rubric, $e->{In};
117 oo sprintf $f, $rubric, $o;
120 oh "${senl}# ----- $what ends -----\n";
124 my ($dir_prefix) = @_;
125 open I, '>', "$outdir/${dir_prefix}doctest.sd.mk" or die $!;
126 open O, '>', "$outdir/${dir_prefix}doctest.mk.part" or die $!;
127 oh "# doctest starts $dir_prefix\n";
128 write_permode($dir_prefix,
130 sub { !$_[0]{CQ} } );
131 write_permode($dir_prefix,
132 "&:changequote NEWQUOTE",
133 "NEWQUOTE:changequote &",
137 oh "# doctest ends\n";
142 writeout('sub/dir/');