This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add a new warning about redundant printf arguments
[perl5.git] / t / op / sprintf2.t
1 #!./perl -w
2
3 # Tests for sprintf that do not fit the format of sprintf.t.
4
5 BEGIN {
6     chdir 't' if -d 't';
7     @INC = '../lib';
8     require './test.pl';
9 }   
10
11 plan tests => 1406;
12
13 use strict;
14 use Config;
15
16 is(
17     sprintf("%.40g ",0.01),
18     sprintf("%.40g", 0.01)." ",
19     q(the sprintf "%.<number>g" optimization)
20 );
21 is(
22     sprintf("%.40f ",0.01),
23     sprintf("%.40f", 0.01)." ",
24     q(the sprintf "%.<number>f" optimization)
25 );
26
27 # cases of $i > 1 are against [perl #39126]
28 for my $i (1, 5, 10, 20, 50, 100) {
29     chop(my $utf8_format = "%-*s\x{100}");
30     my $string = "\xB4"x$i;        # latin1 ACUTE or ebcdic COPYRIGHT
31     my $expect = $string."  "x$i;  # followed by 2*$i spaces
32     is(sprintf($utf8_format, 3*$i, $string), $expect,
33        "width calculation under utf8 upgrade, length=$i");
34 }
35
36 # check simultaneous width & precision with wide characters
37 for my $i (1, 3, 5, 10) {
38     my $string = "\x{0410}"x($i+10);   # cyrillic capital A
39     my $expect = "\x{0410}"x$i;        # cut down to exactly $i characters
40     my $format = "%$i.${i}s";
41     is(sprintf($format, $string), $expect,
42        "width & precision interplay with utf8 strings, length=$i");
43 }
44
45 # Used to mangle PL_sv_undef
46 fresh_perl_like(
47     'print sprintf "xxx%n\n"; print undef',
48     'Modification of a read-only value attempted at - line 1\.',
49     { switches => [ '-w' ] },
50     q(%n should not be able to modify read-only constants),
51 );
52
53 # check overflows
54 for (int(~0/2+1), ~0, "9999999999999999999") {
55     is(eval {sprintf "%${_}d", 0}, undef, "no sprintf result expected %${_}d");
56     like($@, qr/^Integer overflow in format string for sprintf /, "overflow in sprintf");
57     is(eval {printf "%${_}d\n", 0}, undef, "no printf result expected %${_}d");
58     like($@, qr/^Integer overflow in format string for printf /, "overflow in printf");
59 }
60
61 # check %NNN$ for range bounds
62 {
63     my ($warn, $bad) = (0,0);
64     local $SIG{__WARN__} = sub {
65         if ($_[0] =~ /missing argument/i) {
66             $warn++
67         }
68         else {
69             $bad++
70         }
71     };
72
73     my $fmt = join('', map("%$_\$s%" . ((1 << 31)-$_) . '$s', 1..20));
74     my $result = sprintf $fmt, qw(a b c d);
75     is($result, "abcd", "only four valid values in $fmt");
76     is($warn, 36, "expected warnings");
77     is($bad,   0, "unexpected warnings");
78 }
79
80 # Tests for "missing argument" and "redundant argument" warnings
81 {
82     my ($warn_missing, $warn_redundant, $warn_bad) = (0,0,0);
83     local $SIG{__WARN__} = sub {
84         if ($_[0] =~ /missing argument/i) {
85             $warn_missing++
86         }
87         elsif ($_[0] =~ /redundant argument/i) {
88             $warn_redundant++
89         }
90         else {
91             $warn_bad++
92         }
93     };
94
95     my @tests = (
96         # The "", "%s", and "%-p" formats have special-case handling
97         # in sv.c
98         {
99             fmt  => "",
100             args => [ qw( x ) ],
101             res  => "",
102             m    => 0,
103             r    => 1,
104         },
105         {
106             fmt  => "%s",
107             args => [ qw( x y ) ],
108             res  => "x",
109             m    => 0,
110             r    => 1,
111         },
112         {
113             fmt  => "%-p",
114             args => [ qw( x y ) ],
115             res  => qr/^[0-9a-f]+$/as,
116             m    => 0,
117             r    => 1,
118         },
119         # Other non-specialcased patterns
120         {
121             fmt  => "%s : %s",
122             args => [ qw( a b c ) ],
123             res  => "a : b",
124             m    => 0,
125             r    => 1,
126         },
127         {
128             fmt  => "%s : %s : %s",
129             args => [ qw( a b c d e ) ],
130             res  => "a : b : c",
131             m    => 0,
132             # Note how we'll only warn about redundant arguments once,
133             # even though both "d" and "e" are redundant...
134             r    => 1,
135         },
136         {
137             fmt  => "%s : %s : %s",
138             args => [ ],
139             res  => " :  : ",
140             # ...But when arguments are missing we'll warn about every
141             # missing argument. This difference between the two
142             # warnings is a feature.
143             m    => 3,
144             r    => 0,
145         },
146
147         # Tests for format parameter indexes.
148         #
149         # Deciding what to do about these is a bit tricky, and so is
150         # "correctly" warning about missing arguments on them.
151         #
152         # Should we warn if you supply 4 arguments but only use
153         # argument 1,3 & 4? Or only if you supply 5 arguments and your
154         # highest used argument is 4?
155         #
156         # For some uses of this printf feature (e.g. i18n systems)
157         # it's a always a logic error to not print out every provided
158         # argument, but for some other uses skipping some might be a
159         # feature (although you could argue that then printf should be
160         # called as e.g:
161         #
162         #     printf q[%1$s %3$s], x(), undef, z();
163         #
164         # Instead of:
165         #
166         #    printf q[%1$s %3$s], x(), y(), z();
167         #
168         # Since calling the (possibly expensive) y() function is
169         # completely redundant there.
170         #
171         # We deal with all these potential problems by not even
172         # trying. If the pattern contains any format parameter indexes
173         # whatsoever we'll never warn about redundant arguments.
174         {
175             fmt  => '%1$s : %2$s',
176             args => [ qw( x y z ) ],
177             res  => "x : y",
178             m    => 0,
179             r    => 0,
180         },
181         {
182             fmt  => '%2$s : %4$s : %5$s',
183             args => [ qw( a b c d )],
184             res  => "b : d : ",
185             m    => 1,
186             r    => 0,
187         },
188         {
189             fmt  => '%s : %1$s : %s',
190             args => [ qw( x y z ) ],
191             res  => "x : x : y",
192             m    => 0,
193             r    => 0,
194         },
195
196     );
197
198     for my $i (0..$#tests) {
199         my $test = $tests[$i];
200         my $result = sprintf $test->{fmt}, @{$test->{args}};
201
202         my $prefix = "For format '$test->{fmt}' and arguments/result '@{$test->{args}}'/'$result'";
203         if (ref $test->{res} eq 'Regexp') {
204             like($result, $test->{res}, "$prefix got the right result");
205         } else {
206             is($result, $test->{res}, "$prefix got the right result");
207         }
208         is($warn_missing, $test->{m}, "$prefix got '$test->{m}' 'missing argument' warnings");
209         is($warn_redundant, $test->{r}, "$prefix got '$test->{r}' 'redundant argument' warnings");
210         is($warn_bad, 0, "$prefix No unknown warnings");
211
212         ($warn_missing, $warn_redundant, $warn_bad) = (0,0,0);
213     }
214 }
215
216 {
217     foreach my $ord (0 .. 255) {
218         my $bad = 0;
219         local $SIG{__WARN__} = sub {
220             if ($_[0] !~ /^Invalid conversion in sprintf/) {
221                 warn $_[0];
222                 $bad++;
223             }
224         };
225         my $r = eval {sprintf '%v' . chr $ord};
226         is ($bad, 0, "pattern '%v' . chr $ord");
227     }
228 }
229
230 sub mysprintf_int_flags {
231     my ($fmt, $num) = @_;
232     die "wrong format $fmt" if $fmt !~ /^%([-+ 0]+)([1-9][0-9]*)d\z/;
233     my $flag  = $1;
234     my $width = $2;
235     my $sign  = $num < 0 ? '-' :
236                 $flag =~ /\+/ ? '+' :
237                 $flag =~ /\ / ? ' ' :
238                 '';
239     my $abs   = abs($num);
240     my $padlen = $width - length($sign.$abs);
241     return
242         $flag =~ /0/ && $flag !~ /-/ # do zero padding
243             ? $sign . '0' x $padlen . $abs
244             : $flag =~ /-/ # left or right
245                 ? $sign . $abs . ' ' x $padlen
246                 : ' ' x $padlen . $sign . $abs;
247 }
248
249 # Whole tests for "%4d" with 2 to 4 flags;
250 # total counts: 3 * (4**2 + 4**3 + 4**4) == 1008
251
252 my @flags = ("-", "+", " ", "0");
253 for my $num (0, -1, 1) {
254     for my $f1 (@flags) {
255         for my $f2 (@flags) {
256             for my $f3 ('', @flags) { # '' for doubled flags
257                 my $flag = $f1.$f2.$f3;
258                 my $width = 4;
259                 my $fmt   = '%'."${flag}${width}d";
260                 my $result = sprintf($fmt, $num);
261                 my $expect = mysprintf_int_flags($fmt, $num);
262                 is($result, $expect, qq/sprintf("$fmt",$num)/);
263
264                 next if $f3 eq '';
265
266                 for my $f4 (@flags) { # quadrupled flags
267                     my $flag = $f1.$f2.$f3.$f4;
268                     my $fmt   = '%'."${flag}${width}d";
269                     my $result = sprintf($fmt, $num);
270                     my $expect = mysprintf_int_flags($fmt, $num);
271                     is($result, $expect, qq/sprintf("$fmt",$num)/);
272                 }
273             }
274         }
275     }
276 }
277
278 # test that %f doesn't panic with +Inf, -Inf, NaN [perl #45383]
279 foreach my $n (2**1e100, -2**1e100, 2**1e100/2**1e100) { # +Inf, -Inf, NaN
280     eval { my $f = sprintf("%f", $n); };
281     is $@, "", "sprintf(\"%f\", $n)";
282 }
283
284 # test %ll formats with and without HAS_QUAD
285 eval { my $q = pack "q", 0 };
286 my $Q = $@ eq '';
287
288 my @tests = (
289   [ '%lld' => [qw( 4294967296 -100000000000000 )] ],
290   [ '%lli' => [qw( 4294967296 -100000000000000 )] ],
291   [ '%llu' => [qw( 4294967296  100000000000000 )] ],
292   [ '%Ld'  => [qw( 4294967296 -100000000000000 )] ],
293   [ '%Li'  => [qw( 4294967296 -100000000000000 )] ],
294   [ '%Lu'  => [qw( 4294967296  100000000000000 )] ],
295 );
296
297 for my $t (@tests) {
298   my($fmt, $nums) = @$t;
299   for my $num (@$nums) {
300     my $w; local $SIG{__WARN__} = sub { $w = shift };
301     is(sprintf($fmt, $num), $Q ? $num : $fmt, "quad: $fmt -> $num");
302     like($w, $Q ? '' : qr/Invalid conversion in sprintf: "$fmt"/, "warning: $fmt");
303   }
304 }
305
306 # Check unicode vs byte length
307 for my $width (1,2,3,4,5,6,7) {
308     for my $precis (1,2,3,4,5,6,7) {
309         my $v = "\x{20ac}\x{20ac}";
310         my $format = "%" . $width . "." . $precis . "s";
311         my $chars = ($precis > 2 ? 2 : $precis);
312         my $space = ($width < 2 ? 0 : $width - $chars);
313         fresh_perl_is(
314             'my $v = "\x{20ac}\x{20ac}"; my $x = sprintf "'.$format.'", $v; $x =~ /^(\s*)(\S*)$/; print "$_" for map {length} $1, $2',
315             "$space$chars",
316             {},
317             q(sprintf ").$format.q(", "\x{20ac}\x{20ac}"),
318         );
319     }
320 }
321
322 # Overload count
323 package o { use overload '""', sub { ++our $count; $_[0][0]; } }
324 my $o = bless ["\x{100}"], o::;
325 () = sprintf "%1s", $o;
326 is $o::count, '1', 'sprinf %1s overload count';
327 $o::count = 0;
328 () = sprintf "%.1s", $o;
329 is $o::count, '1', 'sprinf %.1s overload count';