This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
new perldelta
[perl5.git] / regen / warnings.pl
CommitLineData
599cee73 1#!/usr/bin/perl
c4a853d1 2#
6294c161
DM
3# Regenerate (overwriting only if changed):
4#
5# lib/warnings.pm
6# warnings.h
7#
0144c000 8# from information hardcoded into this script (the $WARNING_TREE hash), plus the
d2ec25a5 9# template for warnings.pm in the DATA section.
6294c161 10#
91efc02c
KW
11# When changing the number of warnings, t/op/caller.t should change to
12# correspond with the value of $BYTES in lib/warnings.pm
8457b38f 13#
0144c000 14# With an argument of 'tree', just dump the contents of $WARNING_TREE and exits.
6294c161
DM
15# Also accepts the standard regen_lib -q and -v args.
16#
17# This script is normally invoked from regen.pl.
599cee73 18
f1cf82e7 19$VERSION = '1.67';
b75c8c73 20
73f0cc2d 21BEGIN {
3d7c117d 22 require './regen/regen_lib.pl';
b6b9a099 23 push @INC, './lib';
73f0cc2d 24}
599cee73
PM
25use strict ;
26
27sub DEFAULT_ON () { 1 }
28sub DEFAULT_OFF () { 2 }
29
b4353f19
DM
30
31# Define the hierarchy of warnings.
32#
33# Each level in the tree is a hash which lists the names of all the
34# children below that level. Each child is an array consisting of the
35# version when that warnings category was introduced and, if a terminal
36# category, whether that warning is on by default; otherwise a ref to
37# another hash of children.
38#
39# Note that the version numbers are currently only used to sort and to
40# generate code comments in the output files.
41#
42# Note that warning names aren't hierarchical; by having 'pipe' as a child
43# of 'io', a warnings category called 'io::pipe' is NOT automatically
44# created. But the warnings category 'io' WILL include all the mask bits
45# necessary to turn on 'pipe', 'unopened' etc.
46
0144c000 47our $WARNING_TREE = {
3c3f8cd6
AB
48'all' => [ 5.008, {
49 'io' => [ 5.008, {
50 'pipe' => [ 5.008, DEFAULT_OFF],
51 'unopened' => [ 5.008, DEFAULT_OFF],
52 'closed' => [ 5.008, DEFAULT_OFF],
53 'newline' => [ 5.008, DEFAULT_OFF],
54 'exec' => [ 5.008, DEFAULT_OFF],
55 'layer' => [ 5.008, DEFAULT_OFF],
56 'syscalls' => [ 5.019, DEFAULT_OFF],
57 }],
58 'syntax' => [ 5.008, {
59 'ambiguous' => [ 5.008, DEFAULT_OFF],
60 'semicolon' => [ 5.008, DEFAULT_OFF],
61 'precedence' => [ 5.008, DEFAULT_OFF],
62 'bareword' => [ 5.008, DEFAULT_OFF],
63 'reserved' => [ 5.008, DEFAULT_OFF],
64 'digit' => [ 5.008, DEFAULT_OFF],
65 'parenthesis' => [ 5.008, DEFAULT_OFF],
66 'printf' => [ 5.008, DEFAULT_OFF],
67 'prototype' => [ 5.008, DEFAULT_OFF],
68 'qw' => [ 5.008, DEFAULT_OFF],
69 'illegalproto' => [ 5.011, DEFAULT_OFF],
70 }],
71 'severe' => [ 5.008, {
72 'inplace' => [ 5.008, DEFAULT_ON],
73 'internal' => [ 5.008, DEFAULT_OFF],
74 'debugging' => [ 5.008, DEFAULT_ON],
75 'malloc' => [ 5.008, DEFAULT_ON],
76 }],
d81b4f93 77 'deprecated' => [ 5.008, DEFAULT_ON, {
2d8fceed 78 'deprecated::goto_construct' => [ 5.011003, DEFAULT_ON],
2be0f9ab
YO
79 'deprecated::unicode_property_name' => [ 5.011003, DEFAULT_ON],
80 'deprecated::dot_in_inc' => [ 5.025011, DEFAULT_ON],
b689ed93 81 'deprecated::version_downgrade' => [ 5.035009, DEFAULT_ON],
2be0f9ab
YO
82 'deprecated::delimiter_will_be_paired' => [ 5.035010, DEFAULT_ON],
83 'deprecated::apostrophe_as_package_separator'
84 => [ 5.037009, DEFAULT_ON],
bb7d7c52 85 'deprecated::smartmatch' => [ 5.037010, DEFAULT_ON],
f1cf82e7
YO
86 'deprecated::missing_import_called_with_args'
87 => [ 5.039010, DEFAULT_ON],
d81b4f93 88 }],
3c3f8cd6
AB
89 'void' => [ 5.008, DEFAULT_OFF],
90 'recursion' => [ 5.008, DEFAULT_OFF],
91 'redefine' => [ 5.008, DEFAULT_OFF],
92 'numeric' => [ 5.008, DEFAULT_OFF],
93 'uninitialized' => [ 5.008, DEFAULT_OFF],
94 'once' => [ 5.008, DEFAULT_OFF],
95 'misc' => [ 5.008, DEFAULT_OFF],
96 'regexp' => [ 5.008, DEFAULT_OFF],
97 'glob' => [ 5.008, DEFAULT_ON],
98 'untie' => [ 5.008, DEFAULT_OFF],
99 'substr' => [ 5.008, DEFAULT_OFF],
100 'taint' => [ 5.008, DEFAULT_OFF],
101 'signal' => [ 5.008, DEFAULT_OFF],
102 'closure' => [ 5.008, DEFAULT_OFF],
103 'overflow' => [ 5.008, DEFAULT_OFF],
104 'portable' => [ 5.008, DEFAULT_OFF],
105 'utf8' => [ 5.008, {
106 'surrogate' => [ 5.013, DEFAULT_OFF],
107 'nonchar' => [ 5.013, DEFAULT_OFF],
108 'non_unicode' => [ 5.013, DEFAULT_OFF],
109 }],
110 'exiting' => [ 5.008, DEFAULT_OFF],
111 'pack' => [ 5.008, DEFAULT_OFF],
112 'unpack' => [ 5.008, DEFAULT_OFF],
113 'threads' => [ 5.008, DEFAULT_OFF],
114 'imprecision' => [ 5.011, DEFAULT_OFF],
115 'experimental' => [ 5.017, {
116 'experimental::lexical_subs' =>
117 [ 5.017, DEFAULT_ON ],
118 'experimental::regex_sets' =>
737a7c2c 119 [ 5.017, DEFAULT_OFF ],
3c3f8cd6
AB
120 'experimental::smartmatch' =>
121 [ 5.017, DEFAULT_ON ],
122 'experimental::postderef' =>
123 [ 5.019, DEFAULT_ON ],
3c3f8cd6
AB
124 'experimental::signatures' =>
125 [ 5.019, DEFAULT_ON ],
3c3f8cd6
AB
126 'experimental::refaliasing' =>
127 [ 5.021, DEFAULT_ON ],
128 'experimental::re_strict' =>
129 [ 5.021, DEFAULT_ON ],
130 'experimental::const_attr' =>
131 [ 5.021, DEFAULT_ON ],
9f88e537
FC
132 'experimental::bitwise' =>
133 [ 5.021, DEFAULT_ON ],
88d5dae9
FC
134 'experimental::declared_refs' =>
135 [ 5.025, DEFAULT_ON ],
0d76344b
KW
136 'experimental::script_run' =>
137 [ 5.027, DEFAULT_ON ],
948f26d8
KW
138 'experimental::alpha_assertions' =>
139 [ 5.027, DEFAULT_ON ],
21c34e97
KW
140 'experimental::private_use' =>
141 [ 5.029, DEFAULT_ON ],
4fa1c4b6
KW
142 'experimental::uniprop_wildcards' =>
143 [ 5.029, DEFAULT_ON ],
15a9bc0d
KW
144 'experimental::vlb' =>
145 [ 5.029, DEFAULT_ON ],
813e85a0
PE
146 'experimental::isa' =>
147 [ 5.031, DEFAULT_ON ],
a1325b90
PE
148 'experimental::try' =>
149 [ 5.033, DEFAULT_ON ],
f79e2ff9
PE
150 'experimental::defer' =>
151 [ 5.035, DEFAULT_ON ],
3b54923c
NC
152 'experimental::for_list' =>
153 [ 5.035, DEFAULT_ON ],
59802880
PE
154 'experimental::builtin' =>
155 [ 5.035, DEFAULT_ON ],
1c547c3e
PE
156 'experimental::args_array_with_signatures' =>
157 [ 5.035, DEFAULT_ON],
9c9853e8
KW
158 'experimental::extra_paired_delimiters' =>
159 [ 5.035, DEFAULT_ON],
99b497aa
PE
160 'experimental::class' =>
161 [ 5.037, DEFAULT_ON ],
3c3f8cd6
AB
162 }],
163
164 'missing' => [ 5.021, DEFAULT_OFF],
165 'redundant' => [ 5.021, DEFAULT_OFF],
166 'locale' => [ 5.021, DEFAULT_ON],
52e3acf8 167 'shadow' => [ 5.027, DEFAULT_OFF],
4c58833d 168 'scalar' => [ 5.035, DEFAULT_OFF],
3c3f8cd6
AB
169
170 #'default' => [ 5.008, DEFAULT_ON ],
ea5519d6 171}]};
599cee73 172
9e9fbd5d
DM
173
174
175my @DEFAULTS; # List of category numbers which are DEFAULT_ON
176
177 # for each category name, list which category number(s)
178 # it enables; e.g.
179my %CATEGORIES; # { 'name' => [ 1,2,5], ... }
180
9e9fbd5d
DM
181my %VALUE_TO_NAME; # (index_number => [ 'NAME', version ], ...);
182
183my %NAME_TO_VALUE; # ('NAME' => index_number, ....);
599cee73 184
381382f7 185# the experiments were successful (or abandonned),
d7e8a031
PBB
186# so no warning bit is needed anymore
187my %NO_BIT_FOR = map { ( uc $_ => 1, $_ => 1 ) } qw(
188 experimental::lexical_subs
189 experimental::postderef
190 experimental::signatures
191 experimental::bitwise
192 experimental::alpha_assertions
193 experimental::script_run
194 experimental::isa
381382f7 195 experimental::smartmatch
d7e8a031
PBB
196);
197
76f222d7
DM
198###########################################################################
199
200# Generate a hash with keys being the version number and values
201# being a list of node names with that version, e.g.
202#
203# { '5.008' => [ 'all', 'closure', .. ], 5.021' => .... }
204#
205# A ref to the (initially empty) hash is passed as an arg, which is
206# recursively populated
0d658bf5
PM
207
208sub valueWalk
209{
c3193e2d 210 my ($tree, $v_list) = @_;
0d658bf5
PM
211 my ($k, $v) ;
212
c3193e2d
DM
213 foreach $k (sort keys %$tree) {
214 $v = $tree->{$k};
9824c081
MS
215 die "Value associated with key '$k' is not an ARRAY reference"
216 if !ref $v || ref $v ne 'ARRAY' ;
0d658bf5 217
d81b4f93
YO
218 my ($ver, $rest, $rest2) = @{ $v } ;
219 my $ref = ref $rest ? $rest : $rest2;
76f222d7 220 push @{ $v_list->{$ver} }, $k;
c4a853d1 221
d81b4f93
YO
222 if (ref $ref)
223 { valueWalk ($ref, $v_list) }
0d658bf5 224 }
0d658bf5
PM
225}
226
76f222d7
DM
227
228# Assign an index number to each category, ordered by introduced-version.
229# Populate:
230#
231# %VALUE_TO_NAME = (index_number => [ 'NAME', version ], ...);
232# %NAME_TO_VALUE = ('NAME' => index_number, ....);
233#
234# Returns count of categories.
235
236
0d658bf5
PM
237sub orderValues
238{
c3193e2d 239 my ($tree) = @_;
76f222d7
DM
240
241 my %v_list;
c3193e2d 242 valueWalk($tree, \%v_list);
76f222d7 243
0d658bf5
PM
244 my $index = 0;
245 foreach my $ver ( sort { $a <=> $b } keys %v_list ) {
246 foreach my $name (@{ $v_list{$ver} } ) {
d7e8a031 247 next if $NO_BIT_FOR{$name};
9e9fbd5d
DM
248 $VALUE_TO_NAME{ $index } = [ uc $name, $ver ] ;
249 $NAME_TO_VALUE{ uc $name } = $index ++ ;
0d658bf5
PM
250 }
251 }
252
253 return $index ;
254}
255
5595fe1b 256
0d658bf5
PM
257###########################################################################
258
5595fe1b
DM
259# Recurse the tree and populate
260# %CATEGORIES
261# %DEFAULTS
262
599cee73
PM
263sub walk
264{
c3193e2d 265 my $tree = shift ;
599cee73
PM
266 my @list = () ;
267 my ($k, $v) ;
268
c3193e2d
DM
269 foreach $k (sort keys %$tree) {
270 $v = $tree->{$k};
9e9fbd5d 271 die "duplicate key $k\n" if defined $CATEGORIES{$k} ;
d7e8a031 272 next if $NO_BIT_FOR{$k};
9824c081 273 die "Can't find key '$k'"
9e9fbd5d
DM
274 if ! defined $NAME_TO_VALUE{uc $k} ;
275 push @{ $CATEGORIES{$k} }, $NAME_TO_VALUE{uc $k} ;
9824c081
MS
276 die "Value associated with key '$k' is not an ARRAY reference"
277 if !ref $v || ref $v ne 'ARRAY' ;
c4a853d1 278
d81b4f93
YO
279 my ($ver, $rest, $rest2) = @{ $v } ;
280 my $ref = ref $rest ? $rest : $rest2;
281 if (!ref $rest and $rest == DEFAULT_ON)
9e9fbd5d 282 { push @DEFAULTS, $NAME_TO_VALUE{uc $k} }
d81b4f93
YO
283 if (ref $ref)
284 { push (@{ $CATEGORIES{$k} }, walk ($ref)) }
0d658bf5 285
9e9fbd5d 286 push @list, @{ $CATEGORIES{$k} } ;
599cee73
PM
287 }
288
289 return @list ;
599cee73
PM
290}
291
5595fe1b 292
599cee73
PM
293###########################################################################
294
5595fe1b
DM
295# convert a list like (1,2,3,7,8) into a string like '1..3,7,8'
296
599cee73
PM
297sub mkRange
298{
573a192d
DIM
299 my @in = @_ ;
300 my @out = @in ;
599cee73 301
573a192d 302 for my $i (1 .. @in - 1) {
9824c081 303 $out[$i] = ".."
573a192d
DIM
304 if $in[$i] == $in[$i - 1] + 1
305 && ($i >= @in - 1 || $in[$i] + 1 == $in[$i + 1] );
599cee73 306 }
573a192d 307 $out[-1] = $in[-1] if $out[-1] eq "..";
599cee73
PM
308
309 my $out = join(",",@out);
310
311 $out =~ s/,(\.\.,)+/../g ;
312 return $out;
313}
314
5595fe1b 315
599cee73 316###########################################################################
5595fe1b
DM
317
318# return a string containing a visual representation of the warnings tree
319# structure.
320
e15f14b8 321sub warningsTree
e476b1b5 322{
c3193e2d 323 my $tree = shift ;
e476b1b5 324 my $prefix = shift ;
e476b1b5
GS
325 my ($k, $v) ;
326
c3193e2d
DM
327 my $max = (sort {$a <=> $b} map { length $_ } keys %$tree)[-1] ;
328 my @keys = sort keys %$tree ;
e476b1b5 329
e15f14b8
RS
330 my $rv = '';
331
0d658bf5 332 while ($k = shift @keys) {
d7e8a031 333 next if $NO_BIT_FOR{$k};
c3193e2d 334 $v = $tree->{$k};
9824c081
MS
335 die "Value associated with key '$k' is not an ARRAY reference"
336 if !ref $v || ref $v ne 'ARRAY' ;
c4a853d1 337
0d658bf5 338 my $offset ;
0144c000 339 if ($tree ne $WARNING_TREE) {
9824c081
MS
340 $rv .= $prefix . "|\n" ;
341 $rv .= $prefix . "+- $k" ;
342 $offset = ' ' x ($max + 4) ;
343 }
344 else {
345 $rv .= $prefix . "$k" ;
346 $offset = ' ' x ($max + 1) ;
347 }
348
d81b4f93
YO
349 my ($ver, $rest, $rest2) = @{ $v } ;
350 my $ref = ref $rest ? $rest : $rest2;
351 if (ref $ref)
9824c081
MS
352 {
353 my $bar = @keys ? "|" : " ";
354 $rv .= " -" . "-" x ($max - length $k ) . "+\n" ;
d81b4f93 355 $rv .= warningsTree ($ref, $prefix . $bar . $offset )
9824c081
MS
356 }
357 else
358 { $rv .= "\n" }
e476b1b5
GS
359 }
360
e15f14b8 361 return $rv;
e476b1b5
GS
362}
363
5595fe1b 364
e476b1b5 365###########################################################################
599cee73 366
5595fe1b
DM
367# common backend for mkHex() and mkOct()
368
317ea90d 369sub mkHexOct
599cee73 370{
573a192d 371 my ($f, $max, @bits) = @_ ;
599cee73
PM
372 my $mask = "\x00" x $max ;
373 my $string = "" ;
374
573a192d 375 foreach (@bits) {
9824c081 376 vec($mask, $_, 1) = 1 ;
599cee73
PM
377 }
378
599cee73 379 foreach (unpack("C*", $mask)) {
317ea90d
MS
380 if ($f eq 'x') {
381 $string .= '\x' . sprintf("%2.2x", $_)
382 }
383 else {
384 $string .= '\\' . sprintf("%o", $_)
385 }
599cee73
PM
386 }
387 return $string ;
388}
389
5595fe1b
DM
390# Convert a list of bit offsets (0...) into a string containing $max bytes
391# of the form "\xMM\xNN...."
392
317ea90d
MS
393sub mkHex
394{
573a192d
DIM
395 my($max, @bits) = @_;
396 return mkHexOct("x", $max, @bits);
317ea90d
MS
397}
398
5595fe1b
DM
399# Like mkHex(), but outputs "\o..." instead
400
317ea90d
MS
401sub mkOct
402{
573a192d
DIM
403 my($max, @bits) = @_;
404 return mkHexOct("o", $max, @bits);
317ea90d
MS
405}
406
5595fe1b 407
599cee73 408###########################################################################
0144c000 409sub main {
599cee73 410
0144c000
YO
411 if (@ARGV && $ARGV[0] eq "tree")
412 {
413 print warningsTree($WARNING_TREE, " ") ;
414 exit ;
415 }
599cee73 416
0144c000
YO
417 my ($warn_h, $warn_pm) = map {
418 open_new($_, '>', { by => 'regen/warnings.pl' });
419 } 'warnings.h', 'lib/warnings.pm';
c4a853d1 420
0144c000 421 my ($index, $warn_size);
c4a853d1 422
0144c000 423 # generate warnings.h
599cee73 424
0144c000 425 print $warn_h warnings_h_boilerplate_1();
599cee73 426
0144c000 427 $index = orderValues($WARNING_TREE);
599cee73 428
0144c000
YO
429 die <<~EOM if $index > 255 ;
430 Too many warnings categories -- max is 255
431 rewrite packWARN* & unpackWARN* macros
432 EOM
c561877e 433
0144c000
YO
434 walk ($WARNING_TREE) ;
435 for (my $i = $index; $i & 3; $i++) {
436 push @{$CATEGORIES{all}}, $i;
437 }
3d09c062 438
0144c000
YO
439 $index *= 2 ;
440 $warn_size = int($index / 8) + ($index % 8 != 0) ;
441
442 my $k ;
443 my $last_ver = 0;
444 my @names;
445 foreach $k (sort { $a <=> $b } keys %VALUE_TO_NAME) {
446 my ($name, $version) = @{ $VALUE_TO_NAME{$k} };
447 print $warn_h "\n/* Warnings Categories added in Perl $version */\n\n"
448 if $last_ver != $version ;
449 $name =~ y/:/_/;
450 $name = "WARN_$name";
451 print $warn_h tab(6, "#define $name"), " $k\n" ;
452 push @names, $name;
453 $last_ver = $version ;
454 }
c561877e 455
0144c000
YO
456 print $warn_h tab(6, '#define WARNsize'), " $warn_size\n" ;
457 print $warn_h tab(6, '#define WARN_ALLstring'), ' "', ('\125' x $warn_size) , "\"\n" ;
458 print $warn_h tab(6, '#define WARN_NONEstring'), ' "', ('\0' x $warn_size) , "\"\n" ;
c561877e 459
0144c000 460 print $warn_h warnings_h_boilerplate_2();
c561877e 461
0144c000
YO
462 print $warn_h "\n\n/*\n" ;
463 print $warn_h map { "=for apidoc Amnh||$_\n" } @names;
464 print $warn_h "\n=cut\n*/\n\n" ;
465 print $warn_h "/* end of file warnings.h */\n";
1e4d0e87 466
0144c000 467 read_only_bottom_close_and_rename($warn_h);
1e4d0e87 468
c561877e 469
0144c000 470 # generate warnings.pm
3d09c062 471
0144c000
YO
472 while (<DATA>) {
473 last if /^VERSION$/ ;
474 print $warn_pm $_ ;
475 }
3d09c062 476
0144c000 477 print $warn_pm qq(our \$VERSION = "$::VERSION";\n);
3d09c062 478
0144c000
YO
479 while (<DATA>) {
480 last if /^KEYWORDS$/ ;
481 print $warn_pm $_ ;
3d09c062 482 }
3d09c062 483
0144c000
YO
484 $last_ver = 0;
485 print $warn_pm "our %Offsets = (" ;
486 foreach my $k (sort { $a <=> $b } keys %VALUE_TO_NAME) {
487 my ($name, $version) = @{ $VALUE_TO_NAME{$k} };
488 $name = lc $name;
489 $k *= 2 ;
490 if ( $last_ver != $version ) {
491 print $warn_pm "\n";
492 print $warn_pm tab(6, " # Warnings Categories added in Perl $version");
493 print $warn_pm "\n";
494 }
495 print $warn_pm tab(6, " '$name'"), "=> $k,\n" ;
496 $last_ver = $version;
497 }
3d09c062 498
0144c000 499 print $warn_pm ");\n\n" ;
3d09c062 500
0144c000
YO
501 print $warn_pm "our %Bits = (\n" ;
502 foreach my $k (sort keys %CATEGORIES) {
3d09c062 503
0144c000
YO
504 my $v = $CATEGORIES{$k} ;
505 my @list = sort { $a <=> $b } @$v ;
3d09c062 506
0144c000
YO
507 print $warn_pm tab(6, " '$k'"), '=> "',
508 mkHex($warn_size, map $_ * 2 , @list),
509 '", # [', mkRange(@list), "]\n" ;
510 }
3d09c062 511
0144c000 512 print $warn_pm ");\n\n" ;
3d09c062 513
0144c000
YO
514 print $warn_pm "our %DeadBits = (\n" ;
515 foreach my $k (sort keys %CATEGORIES) {
3d09c062 516
0144c000
YO
517 my $v = $CATEGORIES{$k} ;
518 my @list = sort { $a <=> $b } @$v ;
3d09c062 519
0144c000
YO
520 print $warn_pm tab(6, " '$k'"), '=> "',
521 mkHex($warn_size, map $_ * 2 + 1 , @list),
522 '", # [', mkRange(@list), "]\n" ;
523 }
d7e8a031 524
0144c000 525 print $warn_pm ");\n\n" ;
d7e8a031 526
0144c000
YO
527 print $warn_pm "our %NoOp = (\n" ;
528 foreach my $k ( grep /\A[a-z:_]+\z/, sort keys %NO_BIT_FOR ) {
529 print $warn_pm tab(6, " '$k'"), "=> 1,\n";
3d09c062 530 }
3d09c062 531
0144c000
YO
532 print $warn_pm ");\n\n" ;
533 print $warn_pm "# These are used by various things, including our own tests\n";
534 print $warn_pm tab(6, 'our $NONE'), '= "', ('\0' x $warn_size) , "\";\n" ;
535 print $warn_pm tab(6, 'our $DEFAULT'), '= "',
536 mkHex($warn_size, map $_ * 2, @DEFAULTS),
537 '"; # [', mkRange(sort { $a <=> $b } @DEFAULTS), "]\n" ;
538 print $warn_pm tab(6, 'our $LAST_BIT'), '= ' . "$index ;\n" ;
539 print $warn_pm tab(6, 'our $BYTES'), '= ' . "$warn_size ;\n" ;
540 while (<DATA>) {
541 if ($_ eq "=for warnings.pl tree-goes-here\n") {
542 print $warn_pm warningsTree($WARNING_TREE, " ");
543 next;
544 }
545 print $warn_pm $_ ;
546 }
3d09c062 547
0144c000 548 read_only_bottom_close_and_rename($warn_pm);
3d09c062 549
0144c000
YO
550 exit(0);
551}
3d09c062 552
0144c000 553main() unless caller();
3d09c062
DM
554# -----------------------------------------------------------------
555
556sub warnings_h_boilerplate_1 { return <<'EOM'; }
557
558#define Perl_Warn_Off_(x) ((x) / 8)
559#define Perl_Warn_Bit_(x) (1 << ((x) % 8))
560#define PerlWarnIsSet_(a, x) ((a)[Perl_Warn_Off_(x)] & Perl_Warn_Bit_(x))
561
3d09c062
DM
562#define G_WARN_OFF 0 /* $^W == 0 */
563#define G_WARN_ON 1 /* -w flag and $^W != 0 */
564#define G_WARN_ALL_ON 2 /* -W flag */
565#define G_WARN_ALL_OFF 4 /* -X flag */
566#define G_WARN_ONCE 8 /* set if 'once' ever enabled */
567#define G_WARN_ALL_MASK (G_WARN_ALL_ON|G_WARN_ALL_OFF)
568
569#define pWARN_STD NULL
f8552c1a
YO
570#define pWARN_ALL &PL_WARN_ALL /* use warnings 'all' */
571#define pWARN_NONE &PL_WARN_NONE /* no warnings 'all' */
3d09c062
DM
572
573#define specialWARN(x) ((x) == pWARN_STD || (x) == pWARN_ALL || \
574 (x) == pWARN_NONE)
575
576/* if PL_warnhook is set to this value, then warnings die */
577#define PERL_WARNHOOK_FATAL (&PL_sv_placeholder)
578EOM
579
580# -----------------------------------------------------------------
581
582sub warnings_h_boilerplate_2 { return <<'EOM'; }
599cee73 583
a2637ca0 584#define isLEXWARN_on \
9824c081 585 cBOOL(PL_curcop && PL_curcop->cop_warnings != pWARN_STD)
a2637ca0 586#define isLEXWARN_off \
9824c081 587 cBOOL(!PL_curcop || PL_curcop->cop_warnings == pWARN_STD)
d5a71f30 588#define isWARN_ONCE (PL_dowarn & (G_WARN_ON|G_WARN_ONCE))
f8552c1a 589#define hasWARNBIT(c,x) (RCPV_LEN(c) > (2*(x)/8))
f0774ef1 590#define isWARN_on(c,x) (hasWARNBIT(c,x) \
f8552c1a 591 ? PerlWarnIsSet_((U8 *)(c), 2*(x)) \
f0774ef1
YO
592 : 0)
593#define isWARNf_on(c,x) (hasWARNBIT(c,x) \
f8552c1a 594 ? PerlWarnIsSet_((U8 *)(c), 2*(x)+1) \
f0774ef1 595 : 0)
72dc9ed5 596
c1e47bad 597#define DUP_WARNINGS(p) Perl_dup_warnings(aTHX_ p)
d5a71f30 598
94c8b9c1 599#define free_and_set_cop_warnings(cmp,w) STMT_START { \
f8552c1a 600 if (!specialWARN((cmp)->cop_warnings)) rcpv_free((cmp)->cop_warnings); \
1943af61 601 (cmp)->cop_warnings = w; \
94c8b9c1
N
602} STMT_END
603
feff94e1
KW
604/*
605
606=head1 Warning and Dieing
607
bb3eff5d
KW
608In all these calls, the C<U32 wI<n>> parameters are warning category
609constants. You can see the ones currently available in
610L<warnings/Category Hierarchy>, just capitalize all letters in the names
611and prefix them by C<WARN_>. So, for example, the category C<void> used in a
612perl program becomes C<WARN_VOID> when used in XS code and passed to one of
613the calls below.
614
feff94e1 615=for apidoc Am|bool|ckWARN|U32 w
0afc88d2
KW
616=for apidoc_item ||ckWARN2|U32 w1|U32 w2
617=for apidoc_item ||ckWARN3|U32 w1|U32 w2|U32 w3
618=for apidoc_item ||ckWARN4|U32 w1|U32 w2|U32 w3|U32 w4
619These return a boolean as to whether or not warnings are enabled for any of
620the warning category(ies) parameters: C<w>, C<w1>, ....
feff94e1 621
0afc88d2
KW
622Should any of the categories by default be enabled even if not within the
623scope of S<C<use warnings>>, instead use the C<L</ckWARN_d>> macros.
feff94e1 624
0afc88d2
KW
625The categories must be completely independent, one may not be subclassed from
626the other.
feff94e1 627
0afc88d2 628=for apidoc Am|bool|ckWARN_d|U32 w
b8a2649a
KW
629=for apidoc_item ||ckWARN2_d|U32 w1|U32 w2
630=for apidoc_item ||ckWARN3_d|U32 w1|U32 w2|U32 w3
631=for apidoc_item ||ckWARN4_d|U32 w1|U32 w2|U32 w3|U32 w4
feff94e1 632
0afc88d2 633Like C<L</ckWARN>>, but for use if and only if the warning category(ies) is by
feff94e1
KW
634default enabled even if not within the scope of S<C<use warnings>>.
635
b8a2649a
KW
636=for apidoc Am|U32|packWARN|U32 w1
637=for apidoc_item ||packWARN2|U32 w1|U32 w2
638=for apidoc_item ||packWARN3|U32 w1|U32 w2|U32 w3
639=for apidoc_item ||packWARN4|U32 w1|U32 w2|U32 w3|U32 w4
640
641These macros are used to pack warning categories into a single U32 to pass to
642macros and functions that take a warning category parameter. The number of
643categories to pack is given by the name, with a corresponding number of
644category parameters passed.
feff94e1
KW
645
646=cut
647
648*/
649
f54ba1c2 650#define ckWARN(w) Perl_ckwarn(aTHX_ packWARN(w))
7c08c4c5
KW
651
652/* The w1, w2 ... should be independent warnings categories; one shouldn't be
653 * a subcategory of any other */
654
f54ba1c2
DM
655#define ckWARN2(w1,w2) Perl_ckwarn(aTHX_ packWARN2(w1,w2))
656#define ckWARN3(w1,w2,w3) Perl_ckwarn(aTHX_ packWARN3(w1,w2,w3))
657#define ckWARN4(w1,w2,w3,w4) Perl_ckwarn(aTHX_ packWARN4(w1,w2,w3,w4))
658
659#define ckWARN_d(w) Perl_ckwarn_d(aTHX_ packWARN(w))
660#define ckWARN2_d(w1,w2) Perl_ckwarn_d(aTHX_ packWARN2(w1,w2))
661#define ckWARN3_d(w1,w2,w3) Perl_ckwarn_d(aTHX_ packWARN3(w1,w2,w3))
662#define ckWARN4_d(w1,w2,w3,w4) Perl_ckwarn_d(aTHX_ packWARN4(w1,w2,w3,w4))
12bcd1a6 663
98fe6610
NC
664#define WARNshift 8
665
3b9e3074 666#define packWARN(a) (a )
7c08c4c5
KW
667
668/* The a, b, ... should be independent warnings categories; one shouldn't be
669 * a subcategory of any other */
670
3b9e3074
SH
671#define packWARN2(a,b) ((a) | ((b)<<8) )
672#define packWARN3(a,b,c) ((a) | ((b)<<8) | ((c)<<16) )
673#define packWARN4(a,b,c,d) ((a) | ((b)<<8) | ((c)<<16) | ((d) <<24))
12bcd1a6 674
0132fc56
KW
675#define unpackWARN1(x) ((U8) (x) )
676#define unpackWARN2(x) ((U8) ((x) >> 8))
677#define unpackWARN3(x) ((U8) ((x) >> 16))
678#define unpackWARN4(x) ((U8) ((x) >> 24))
12bcd1a6
PM
679
680#define ckDEAD(x) \
006c1a1d
Z
681 (PL_curcop && \
682 !specialWARN(PL_curcop->cop_warnings) && \
683 (isWARNf_on(PL_curcop->cop_warnings, unpackWARN1(x)) || \
684 (unpackWARN2(x) && \
9824c081
MS
685 (isWARNf_on(PL_curcop->cop_warnings, unpackWARN2(x)) || \
686 (unpackWARN3(x) && \
687 (isWARNf_on(PL_curcop->cop_warnings, unpackWARN3(x)) || \
688 (unpackWARN4(x) && \
689 isWARNf_on(PL_curcop->cop_warnings, unpackWARN4(x)))))))))
12bcd1a6 690
599cee73
PM
691EOM
692
3d09c062 693# -----------------------------------------------------------------
599cee73
PM
694
695__END__
4438c4b7 696package warnings;
599cee73 697
3d8ff825 698VERSION
f2c3e829
RGS
699
700# Verify that we're called correctly so that warnings will work.
67ba812d
AP
701# Can't use Carp, since Carp uses us!
702# String regexps because constant folding = smaller optree = less memory vs regexp literal
f2c3e829 703# see also strict.pm.
67ba812d
AP
704die sprintf "Incorrect use of pragma '%s' at %s line %d.\n", __PACKAGE__, +(caller)[1,2]
705 if __FILE__ !~ ( '(?x) \b '.__PACKAGE__.' \.pmc? \z' )
706 && __FILE__ =~ ( '(?x) \b (?i:'.__PACKAGE__.') \.pmc? \z' );
b75c8c73 707
effd17dc
DD
708KEYWORDS
709
effd17dc
DD
710sub Croaker
711{
712 require Carp; # this initializes %CarpInternal
713 local $Carp::CarpInternal{'warnings'};
714 delete $Carp::CarpInternal{'warnings'};
715 Carp::croak(@_);
716}
717
006c1a1d
Z
718sub _expand_bits {
719 my $bits = shift;
720 my $want_len = ($LAST_BIT + 7) >> 3;
721 my $len = length($bits);
722 if ($len != $want_len) {
9824c081
MS
723 if ($bits eq "") {
724 $bits = "\x00" x $want_len;
725 } elsif ($len > $want_len) {
726 substr $bits, $want_len, $len-$want_len, "";
727 } else {
728 my $x = vec($bits, $Offsets{all} >> 1, 2);
729 $x |= $x << 2;
730 $x |= $x << 4;
731 $bits .= chr($x) x ($want_len - $len);
732 }
006c1a1d
Z
733 }
734 return $bits;
735}
736
effd17dc
DD
737sub _bits {
738 my $mask = shift ;
739 my $catmask ;
740 my $fatal = 0 ;
741 my $no_fatal = 0 ;
742
006c1a1d 743 $mask = _expand_bits($mask);
effd17dc 744 foreach my $word ( @_ ) {
d7e8a031 745 next if $NoOp{$word};
9824c081
MS
746 if ($word eq 'FATAL') {
747 $fatal = 1;
748 $no_fatal = 0;
749 }
750 elsif ($word eq 'NONFATAL') {
751 $fatal = 0;
752 $no_fatal = 1;
753 }
754 elsif ($catmask = $Bits{$word}) {
755 $mask |= $catmask ;
756 $mask |= $DeadBits{$word} if $fatal ;
757 $mask = ~(~$mask | $DeadBits{$word}) if $no_fatal ;
758 }
759 else
760 { Croaker("Unknown warnings category '$word'")}
effd17dc
DD
761 }
762
763 return $mask ;
764}
765
766sub bits
767{
768 # called from B::Deparse.pm
769 push @_, 'all' unless @_ ;
006c1a1d 770 return _bits("", @_) ;
effd17dc
DD
771}
772
773sub import
774{
e926558e 775 my $invocant = shift;
effd17dc 776
006c1a1d
Z
777 # append 'all' when implied (empty import list or after a lone
778 # "FATAL" or "NONFATAL")
779 push @_, 'all'
e926558e
DC
780 if !@_ || (@_==1 && ($_[0] eq 'FATAL' || $_[0] eq 'NONFATAL'));
781
782 my @fatal = ();
783 foreach my $warning (@_) {
784 if($warning =~ /^(NON)?FATAL$/) {
785 @fatal = ($warning);
786 } elsif(substr($warning, 0, 1) ne '-') {
787 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
788 ${^WARNING_BITS} = _bits($mask, @fatal, $warning);
789 } else {
790 $invocant->unimport(substr($warning, 1));
791 }
792 }
effd17dc
DD
793}
794
795sub unimport
796{
797 shift;
798
799 my $catmask ;
800 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
801
effd17dc
DD
802 # append 'all' when implied (empty import list or after a lone "FATAL")
803 push @_, 'all' if !@_ || @_==1 && $_[0] eq 'FATAL';
804
006c1a1d 805 $mask = _expand_bits($mask);
effd17dc 806 foreach my $word ( @_ ) {
d7e8a031 807 next if $NoOp{$word};
9824c081
MS
808 if ($word eq 'FATAL') {
809 next;
810 }
811 elsif ($catmask = $Bits{$word}) {
812 $mask = ~(~$mask | $catmask | $DeadBits{$word});
813 }
814 else
815 { Croaker("Unknown warnings category '$word'")}
effd17dc
DD
816 }
817
818 ${^WARNING_BITS} = $mask ;
819}
820
821my %builtin_type; @builtin_type{qw(SCALAR ARRAY HASH CODE REF GLOB LVALUE Regexp)} = ();
822
c4583f59 823sub LEVEL () { 8 };
effd17dc
DD
824sub MESSAGE () { 4 };
825sub FATAL () { 2 };
826sub NORMAL () { 1 };
827
828sub __chk
829{
830 my $category ;
831 my $offset ;
832 my $isobj = 0 ;
833 my $wanted = shift;
834 my $has_message = $wanted & MESSAGE;
c4583f59
FC
835 my $has_level = $wanted & LEVEL ;
836
837 if ($has_level) {
9824c081
MS
838 if (@_ != ($has_message ? 3 : 2)) {
839 my $sub = (caller 1)[3];
840 my $syntax = $has_message
841 ? "category, level, 'message'"
842 : 'category, level';
843 Croaker("Usage: $sub($syntax)");
c4583f59
FC
844 }
845 }
846 elsif (not @_ == 1 || @_ == ($has_message ? 2 : 0)) {
9824c081
MS
847 my $sub = (caller 1)[3];
848 my $syntax = $has_message ? "[category,] 'message'" : '[category]';
849 Croaker("Usage: $sub($syntax)");
effd17dc
DD
850 }
851
852 my $message = pop if $has_message;
853
854 if (@_) {
9824c081
MS
855 # check the category supplied.
856 $category = shift ;
857 if (my $type = ref $category) {
858 Croaker("not an object")
859 if exists $builtin_type{$type};
860 $category = $type;
861 $isobj = 1 ;
862 }
863 $offset = $Offsets{$category};
864 Croaker("Unknown warnings category '$category'")
865 unless defined $offset;
effd17dc
DD
866 }
867 else {
b625025e 868 $category = caller(1);
9824c081
MS
869 $offset = $Offsets{$category};
870 Croaker("package '$category' not registered for warnings")
871 unless defined $offset ;
effd17dc
DD
872 }
873
874 my $i;
875
876 if ($isobj) {
9824c081
MS
877 my $pkg;
878 $i = 2;
879 while (do { { package DB; $pkg = (caller($i++))[0] } } ) {
880 last unless @DB::args && $DB::args[0] =~ /^$category=/ ;
881 }
882 $i -= 2 ;
effd17dc 883 }
c4583f59 884 elsif ($has_level) {
9824c081 885 $i = 2 + shift;
c4583f59 886 }
effd17dc 887 else {
9824c081 888 $i = _error_loc(); # see where Carp will allocate the error
effd17dc
DD
889 }
890
891 # Default to 0 if caller returns nothing. Default to $DEFAULT if it
892 # explicitly returns undef.
893 my(@callers_bitmask) = (caller($i))[9] ;
894 my $callers_bitmask =
9824c081 895 @callers_bitmask ? $callers_bitmask[0] // $DEFAULT : 0 ;
006c1a1d 896 length($callers_bitmask) > ($offset >> 3) or $offset = $Offsets{all};
effd17dc
DD
897
898 my @results;
899 foreach my $type (FATAL, NORMAL) {
9824c081 900 next unless $wanted & $type;
effd17dc 901
9824c081 902 push @results, vec($callers_bitmask, $offset + $type - 1, 1);
effd17dc
DD
903 }
904
905 # &enabled and &fatal_enabled
906 return $results[0] unless $has_message;
907
908 # &warnif, and the category is neither enabled as warning nor as fatal
c4583f59 909 return if ($wanted & (NORMAL | FATAL | MESSAGE))
9824c081
MS
910 == (NORMAL | FATAL | MESSAGE)
911 && !($results[0] || $results[1]);
effd17dc 912
c4583f59
FC
913 # If we have an explicit level, bypass Carp.
914 if ($has_level and @callers_bitmask) {
9824c081
MS
915 # logic copied from util.c:mess_sv
916 my $stuff = " at " . join " line ", (caller $i)[1,2];
917 $stuff .= sprintf ", <%s> %s %d",
918 *${^LAST_FH}{NAME},
919 ($/ eq "\n" ? "line" : "chunk"), $.
920 if $. && ${^LAST_FH};
921 die "$message$stuff.\n" if $results[0];
922 return warn "$message$stuff.\n";
c4583f59
FC
923 }
924
effd17dc
DD
925 require Carp;
926 Carp::croak($message) if $results[0];
927 # will always get here for &warn. will only get here for &warnif if the
928 # category is enabled
929 Carp::carp($message);
930}
931
932sub _mkMask
933{
934 my ($bit) = @_;
935 my $mask = "";
936
937 vec($mask, $bit, 1) = 1;
938 return $mask;
939}
940
941sub register_categories
942{
943 my @names = @_;
944
945 for my $name (@names) {
9824c081
MS
946 if (! defined $Bits{$name}) {
947 $Offsets{$name} = $LAST_BIT;
948 $Bits{$name} = _mkMask($LAST_BIT++);
949 $DeadBits{$name} = _mkMask($LAST_BIT++);
950 if (length($Bits{$name}) > length($Bits{all})) {
951 $Bits{all} .= "\x55";
952 $DeadBits{all} .= "\xaa";
953 }
954 }
effd17dc
DD
955 }
956}
957
958sub _error_loc {
959 require Carp;
960 goto &Carp::short_error_loc; # don't introduce another stack frame
961}
962
963sub enabled
964{
965 return __chk(NORMAL, @_);
966}
967
968sub fatal_enabled
969{
970 return __chk(FATAL, @_);
971}
972
973sub warn
974{
975 return __chk(FATAL | MESSAGE, @_);
976}
977
978sub warnif
979{
980 return __chk(NORMAL | FATAL | MESSAGE, @_);
981}
982
c4583f59
FC
983sub enabled_at_level
984{
985 return __chk(NORMAL | LEVEL, @_);
986}
987
988sub fatal_enabled_at_level
989{
990 return __chk(FATAL | LEVEL, @_);
991}
992
993sub warn_at_level
994{
995 return __chk(FATAL | MESSAGE | LEVEL, @_);
996}
997
998sub warnif_at_level
999{
1000 return __chk(NORMAL | FATAL | MESSAGE | LEVEL, @_);
1001}
1002
effd17dc
DD
1003# These are not part of any public interface, so we can delete them to save
1004# space.
c4583f59 1005delete @warnings::{qw(NORMAL FATAL MESSAGE LEVEL)};
effd17dc
DD
1006
10071;
1008__END__
4bbd41f5 1009
599cee73
PM
1010=head1 NAME
1011
4438c4b7 1012warnings - Perl pragma to control optional warnings
599cee73
PM
1013
1014=head1 SYNOPSIS
1015
4438c4b7
JH
1016 use warnings;
1017 no warnings;
599cee73 1018
1c3cfd87
BC
1019 # Standard warnings are enabled by use v5.35 or above
1020 use v5.35;
1021
4438c4b7 1022 use warnings "all";
e926558e
DC
1023 no warnings "uninitialized";
1024
1025 # or equivalent to those last two ...
1026 use warnings qw(all -uninitialized);
599cee73 1027
d3a7d8c7
GS
1028 use warnings::register;
1029 if (warnings::enabled()) {
1030 warnings::warn("some warning");
1031 }
1032
1033 if (warnings::enabled("void")) {
e476b1b5
GS
1034 warnings::warn("void", "some warning");
1035 }
1036
7e6d00f8
PM
1037 if (warnings::enabled($object)) {
1038 warnings::warn($object, "some warning");
1039 }
1040
721f911b
PM
1041 warnings::warnif("some warning");
1042 warnings::warnif("void", "some warning");
1043 warnings::warnif($object, "some warning");
7e6d00f8 1044
599cee73
PM
1045=head1 DESCRIPTION
1046
188c4f6f
RS
1047The C<warnings> pragma gives control over which warnings are enabled in
1048which parts of a Perl program. It's a more flexible alternative for
1049both the command line flag B<-w> and the equivalent Perl variable,
1050C<$^W>.
33edcb80
RS
1051
1052This pragma works just like the C<strict> pragma.
1053This means that the scope of the warning pragma is limited to the
1054enclosing block. It also means that the pragma setting will not
1055leak across files (via C<use>, C<require> or C<do>). This allows
1056authors to independently define the degree of warning checks that will
1057be applied to their module.
1058
1059By default, optional warnings are disabled, so any legacy code that
1060doesn't attempt to control the warnings will work unchanged.
1061
3c3f8cd6 1062All warnings are enabled in a block by either of these:
33edcb80
RS
1063
1064 use warnings;
1065 use warnings 'all';
1066
3c3f8cd6 1067Similarly all warnings are disabled in a block by either of these:
33edcb80
RS
1068
1069 no warnings;
1070 no warnings 'all';
1071
1072For example, consider the code below:
1073
1074 use warnings;
573a192d 1075 my @x;
33edcb80
RS
1076 {
1077 no warnings;
9824c081 1078 my $y = @x[0];
33edcb80 1079 }
573a192d 1080 my $z = @x[0];
33edcb80
RS
1081
1082The code in the enclosing block has warnings enabled, but the inner
1083block has them disabled. In this case that means the assignment to the
cd2e5170 1084scalar C<$z> will trip the C<"Scalar value @x[0] better written as $x[0]">
573a192d 1085warning, but the assignment to the scalar C<$y> will not.
33edcb80 1086
1c3cfd87
BC
1087All warnings are enabled automatically within the scope of
1088a C<L<use v5.35|perlfunc/use VERSION>> (or higher) declaration.
1089
33edcb80
RS
1090=head2 Default Warnings and Optional Warnings
1091
1092Before the introduction of lexical warnings, Perl had two classes of
56873d42 1093warnings: mandatory and optional.
33edcb80
RS
1094
1095As its name suggests, if your code tripped a mandatory warning, you
1096would get a warning whether you wanted it or not.
1097For example, the code below would always produce an C<"isn't numeric">
1098warning about the "2:".
1099
573a192d 1100 my $x = "2:" + 3;
33edcb80
RS
1101
1102With the introduction of lexical warnings, mandatory warnings now become
1103I<default> warnings. The difference is that although the previously
1104mandatory warnings are still enabled by default, they can then be
1105subsequently enabled or disabled with the lexical warning pragma. For
1106example, in the code below, an C<"isn't numeric"> warning will only
573a192d 1107be reported for the C<$x> variable.
33edcb80 1108
573a192d 1109 my $x = "2:" + 3;
33edcb80 1110 no warnings;
573a192d 1111 my $y = "2:" + 3;
33edcb80
RS
1112
1113Note that neither the B<-w> flag or the C<$^W> can be used to
1114disable/enable default warnings. They are still mandatory in this case.
1115
e926558e
DC
1116=head2 "Negative warnings"
1117
1118As a convenience, you can (as of Perl 5.34) pass arguments to the
1119C<import()> method both positively and negatively. Negative warnings
1120are those with a C<-> sign prepended to their names; positive warnings
1121are anything else. This lets you turn on some warnings and turn off
1122others in one command. So, assuming that you've already turned on a
1123bunch of warnings but want to tweak them a bit in some block, you can
1124do this:
1125
1126 {
1127 use warnings qw(uninitialized -redefine);
1128 ...
1129 }
1130
1131which is equivalent to:
1132
1133 {
1134 use warnings qw(uninitialized);
1135 no warnings qw(redefine);
1136 ...
1137 }
1138
1139The argument list is processed in the order you specify. So, for example, if you
1140don't want to be warned about use of experimental features, except for C<somefeature>
1141that you really dislike, you can say this:
1142
1143 use warnings qw(all -experimental experimental::somefeature);
1144
1145which is equivalent to:
1146
1147 use warnings 'all';
1148 no warnings 'experimental';
1149 use warnings 'experimental::somefeature';
1150
d7e8a031
PBB
1151As experimental features become regular features of Perl,
1152the corresponding warnings are not printed anymore.
1153They also stop being listed in the L</Category Hierarchy> below.
1154
1155It is still possible to request turning on or off these warnings,
1156but doing so has no effect.
1157
33edcb80
RS
1158=head2 What's wrong with B<-w> and C<$^W>
1159
1160Although very useful, the big problem with using B<-w> on the command
1161line to enable warnings is that it is all or nothing. Take the typical
1162scenario when you are writing a Perl program. Parts of the code you
1163will write yourself, but it's very likely that you will make use of
1164pre-written Perl modules. If you use the B<-w> flag in this case, you
1165end up enabling warnings in pieces of code that you haven't written.
1166
1167Similarly, using C<$^W> to either disable or enable blocks of code is
1168fundamentally flawed. For a start, say you want to disable warnings in
1169a block of code. You might expect this to be enough to do the trick:
1170
1171 {
1172 local ($^W) = 0;
9824c081
MS
1173 my $x =+ 2;
1174 my $y; chop $y;
33edcb80
RS
1175 }
1176
1177When this code is run with the B<-w> flag, a warning will be produced
573a192d 1178for the C<$x> line: C<"Reversed += operator">.
33edcb80
RS
1179
1180The problem is that Perl has both compile-time and run-time warnings. To
1181disable compile-time warnings you need to rewrite the code like this:
1182
1183 {
1184 BEGIN { $^W = 0 }
9824c081
MS
1185 my $x =+ 2;
1186 my $y; chop $y;
33edcb80
RS
1187 }
1188
45f87e65
DB
1189And note that unlike the first example, this will permanently set C<$^W>
1190since it cannot both run during compile-time and be localized to a
1191run-time block.
1192
33edcb80
RS
1193The other big problem with C<$^W> is the way you can inadvertently
1194change the warning setting in unexpected places in your code. For example,
1195when the code below is run (without the B<-w> flag), the second call
1196to C<doit> will trip a C<"Use of uninitialized value"> warning, whereas
1197the first will not.
1198
1199 sub doit
1200 {
573a192d 1201 my $y; chop $y;
33edcb80
RS
1202 }
1203
1204 doit();
1205
1206 {
1207 local ($^W) = 1;
1208 doit()
1209 }
1210
1211This is a side-effect of C<$^W> being dynamically scoped.
1212
1213Lexical warnings get around these limitations by allowing finer control
1214over where warnings can or can't be tripped.
1215
1216=head2 Controlling Warnings from the Command Line
1217
1218There are three Command Line flags that can be used to control when
1219warnings are (or aren't) produced:
1220
1221=over 5
1222
1223=item B<-w>
1224X<-w>
1225
1226This is the existing flag. If the lexical warnings pragma is B<not>
677f8b87 1227used in any of your code, or any of the modules that you use, this flag
05a64c17 1228will enable warnings everywhere. See L</Backward Compatibility> for
33edcb80
RS
1229details of how this flag interacts with lexical warnings.
1230
1231=item B<-W>
1232X<-W>
1233
3c3f8cd6 1234If the B<-W> flag is used on the command line, it will enable all warnings
33edcb80
RS
1235throughout the program regardless of whether warnings were disabled
1236locally using C<no warnings> or C<$^W =0>.
1237This includes all files that get
1238included via C<use>, C<require> or C<do>.
1239Think of it as the Perl equivalent of the "lint" command.
1240
1241=item B<-X>
1242X<-X>
1243
3c3f8cd6 1244Does the exact opposite to the B<-W> flag, i.e. it disables all warnings.
33edcb80
RS
1245
1246=back
1247
1248=head2 Backward Compatibility
1249
1250If you are used to working with a version of Perl prior to the
1251introduction of lexically scoped warnings, or have code that uses both
1252lexical warnings and C<$^W>, this section will describe how they interact.
1253
1254How Lexical Warnings interact with B<-w>/C<$^W>:
1255
1256=over 5
1257
1258=item 1.
1259
1260If none of the three command line flags (B<-w>, B<-W> or B<-X>) that
1261control warnings is used and neither C<$^W> nor the C<warnings> pragma
1262are used, then default warnings will be enabled and optional warnings
1263disabled.
1264This means that legacy code that doesn't attempt to control the warnings
1265will work unchanged.
1266
1267=item 2.
1268
1269The B<-w> flag just sets the global C<$^W> variable as in 5.005. This
1270means that any legacy code that currently relies on manipulating C<$^W>
56873d42 1271to control warning behavior will still work as is.
33edcb80
RS
1272
1273=item 3.
1274
1275Apart from now being a boolean, the C<$^W> variable operates in exactly
1276the same horrible uncontrolled global way, except that it cannot
1277disable/enable default warnings.
1278
1279=item 4.
1280
1281If a piece of code is under the control of the C<warnings> pragma,
1282both the C<$^W> variable and the B<-w> flag will be ignored for the
1283scope of the lexical warning.
1284
1285=item 5.
1286
1287The only way to override a lexical warnings setting is with the B<-W>
1288or B<-X> command line flags.
1289
1290=back
1291
1292The combined effect of 3 & 4 is that it will allow code which uses
1293the C<warnings> pragma to control the warning behavior of $^W-type
1294code (using a C<local $^W=0>) if it really wants to, but not vice-versa.
1295
1296=head2 Category Hierarchy
1297X<warning, categories>
1298
1299A hierarchy of "categories" have been defined to allow groups of warnings
1300to be enabled/disabled in isolation.
1301
1302The current hierarchy is:
1303
1304=for warnings.pl tree-goes-here
1305
1306Just like the "strict" pragma any of these categories can be combined
1307
1308 use warnings qw(void redefine);
1309 no warnings qw(io syntax untie);
1310
1311Also like the "strict" pragma, if there is more than one instance of the
56873d42 1312C<warnings> pragma in a given scope the cumulative effect is additive.
33edcb80
RS
1313
1314 use warnings qw(void); # only "void" warnings enabled
1315 ...
1316 use warnings qw(io); # only "void" & "io" warnings enabled
1317 ...
1318 no warnings qw(void); # only "io" warnings enabled
1319
1320To determine which category a specific warning has been assigned to see
1321L<perldiag>.
1322
1323Note: Before Perl 5.8.0, the lexical warnings category "deprecated" was a
1324sub-category of the "syntax" category. It is now a top-level category
1325in its own right.
1326
3664866e
AB
1327Note: Before 5.21.0, the "missing" lexical warnings category was
1328internally defined to be the same as the "uninitialized" category. It
1329is now a top-level category in its own right.
1330
33edcb80
RS
1331=head2 Fatal Warnings
1332X<warning, fatal>
1333
2e4abf26
DG
1334The presence of the word "FATAL" in the category list will escalate
1335warnings in those categories into fatal errors in that lexical scope.
1336
1337B<NOTE:> FATAL warnings should be used with care, particularly
1338C<< FATAL => 'all' >>.
1339
1340Libraries using L<warnings::warn|/FUNCTIONS> for custom warning categories
1341generally don't expect L<warnings::warn|/FUNCTIONS> to be fatal and can wind up
1342in an unexpected state as a result. For XS modules issuing categorized
1343warnings, such unanticipated exceptions could also expose memory leak bugs.
1344
1345Moreover, the Perl interpreter itself has had serious bugs involving
1346fatalized warnings. For a summary of resolved and unresolved problems as
1347of January 2015, please see
1348L<this perl5-porters post|http://www.nntp.perl.org/group/perl.perl5.porters/2015/01/msg225235.html>.
1349
1350While some developers find fatalizing some warnings to be a useful
1351defensive programming technique, using C<< FATAL => 'all' >> to fatalize
1352all possible warning categories -- including custom ones -- is particularly
1353risky. Therefore, the use of C<< FATAL => 'all' >> is
1354L<discouraged|perlpolicy/discouraged>.
1355
1356The L<strictures|strictures/VERSION-2> module on CPAN offers one example of
1357a warnings subset that the module's authors believe is relatively safe to
1358fatalize.
1359
01900a5f 1360B<NOTE:> Users of FATAL warnings, especially those using
2e4abf26
DG
1361C<< FATAL => 'all' >>, should be fully aware that they are risking future
1362portability of their programs by doing so. Perl makes absolutely no
1363commitments to not introduce new warnings or warnings categories in the
1364future; indeed, we explicitly reserve the right to do so. Code that may
1365not warn now may warn in a future release of Perl if the Perl5 development
1366team deems it in the best interests of the community to do so. Should code
1367using FATAL warnings break due to the introduction of a new warning we will
1368NOT consider it an incompatible change. Users of FATAL warnings should
1369take special caution during upgrades to check to see if their code triggers
1370any new warnings and should pay particular attention to the fine print of
1371the documentation of the features they use to ensure they do not exploit
1372features that are documented as risky, deprecated, or unspecified, or where
1373the documentation says "so don't do that", or anything with the same sense
1374and spirit. Use of such features in combination with FATAL warnings is
1375ENTIRELY AT THE USER'S RISK.
1376
1377The following documentation describes how to use FATAL warnings but the
1378perl5 porters strongly recommend that you understand the risks before doing
1379so, especially for library code intended for use by others, as there is no
1380way for downstream users to change the choice of fatal categories.
1381
1382In the code below, the use of C<time>, C<length>
33edcb80
RS
1383and C<join> can all produce a C<"Useless use of xxx in void context">
1384warning.
1385
1386 use warnings;
1387
1388 time;
1389
1390 {
1391 use warnings FATAL => qw(void);
1392 length "abc";
1393 }
1394
1395 join "", 1,2,3;
1396
1397 print "done\n";
1398
1399When run it produces this output
1400
1401 Useless use of time in void context at fatal line 3.
56873d42 1402 Useless use of length in void context at fatal line 7.
33edcb80
RS
1403
1404The scope where C<length> is used has escalated the C<void> warnings
1405category into a fatal error, so the program terminates immediately when it
1406encounters the warning.
1407
1408To explicitly turn off a "FATAL" warning you just disable the warning
1409it is associated with. So, for example, to disable the "void" warning
1410in the example above, either of these will do the trick:
1411
1412 no warnings qw(void);
1413 no warnings FATAL => qw(void);
1414
1415If you want to downgrade a warning that has been escalated into a fatal
1416error back to a normal warning, you can use the "NONFATAL" keyword. For
1417example, the code below will promote all warnings into fatal errors,
1418except for those in the "syntax" category.
1419
1420 use warnings FATAL => 'all', NONFATAL => 'syntax';
1421
1422As of Perl 5.20, instead of C<< use warnings FATAL => 'all'; >> you can
1423use:
1424
1425 use v5.20; # Perl 5.20 or greater is required for the following
1426 use warnings 'FATAL'; # short form of "use warnings FATAL => 'all';"
1427
01900a5f 1428However, you should still heed the guidance earlier in this section against
5624cfff 1429using C<< use warnings FATAL => 'all'; >>.
01900a5f 1430
33edcb80
RS
1431If you want your program to be compatible with versions of Perl before
14325.20, you must use C<< use warnings FATAL => 'all'; >> instead. (In
1433previous versions of Perl, the behavior of the statements
1434C<< use warnings 'FATAL'; >>, C<< use warnings 'NONFATAL'; >> and
1435C<< no warnings 'FATAL'; >> was unspecified; they did not behave as if
1436they included the C<< => 'all' >> portion. As of 5.20, they do.)
1437
33edcb80
RS
1438=head2 Reporting Warnings from a Module
1439X<warning, reporting> X<warning, registering>
1440
1441The C<warnings> pragma provides a number of functions that are useful for
1442module authors. These are used when you want to report a module-specific
78d7b3d6 1443warning to a calling module that has enabled warnings via the C<warnings>
33edcb80
RS
1444pragma.
1445
1446Consider the module C<MyMod::Abc> below.
1447
1448 package MyMod::Abc;
1449
1450 use warnings::register;
1451
1452 sub open {
1453 my $path = shift;
1454 if ($path !~ m#^/#) {
1455 warnings::warn("changing relative path to /var/abc")
1456 if warnings::enabled();
1457 $path = "/var/abc/$path";
1458 }
1459 }
1460
1461 1;
1462
1463The call to C<warnings::register> will create a new warnings category
1464called "MyMod::Abc", i.e. the new category name matches the current
1465package name. The C<open> function in the module will display a warning
78d7b3d6 1466message if it gets given a relative path as a parameter. This warning
33edcb80 1467will only be displayed if the code that uses C<MyMod::Abc> has actually
78d7b3d6
HS
1468enabled them with the C<warnings> pragma as below - note that a plain
1469C<use warnings> enables even warnings that have not yet been registered.
33edcb80 1470
78d7b3d6 1471 use warnings;
33edcb80 1472 use MyMod::Abc;
78d7b3d6
HS
1473 ...
1474 abc::open("../fred.txt");
1475
1476The specific warning can be enabled or disabled, but only after the module
1477has been imported:
1478
1479 # no warnings 'MyMod::Abc'; # error, unknown category before
1480 # the module is loaded
1481 use MyMod::Abc;
1482 no warnings 'MyMod::Abc'; # ok after the module is loaded
33edcb80
RS
1483 ...
1484 abc::open("../fred.txt");
1485
1486It is also possible to test whether the pre-defined warnings categories are
1487set in the calling module with the C<warnings::enabled> function. Consider
1488this snippet of code:
1489
1490 package MyMod::Abc;
1491
78d7b3d6 1492 sub open2 {
4a21999a
TC
1493 if (warnings::enabled("deprecated")) {
1494 warnings::warn("deprecated",
78d7b3d6 1495 "open2 is deprecated, use open instead");
4a21999a 1496 }
78d7b3d6 1497 open(@_);
33edcb80
RS
1498 }
1499
0a92f341 1500 sub open
33edcb80
RS
1501 ...
1502 1;
1503
78d7b3d6 1504The function C<open2> has been deprecated, so code has been included to
33edcb80
RS
1505display a warning message whenever the calling module has (at least) the
1506"deprecated" warnings category enabled. Something like this, say.
1507
1508 use warnings 'deprecated';
1509 use MyMod::Abc;
1510 ...
78d7b3d6 1511 MyMod::Abc::open2($filename);
33edcb80
RS
1512
1513Either the C<warnings::warn> or C<warnings::warnif> function should be
1514used to actually display the warnings message. This is because they can
1515make use of the feature that allows warnings to be escalated into fatal
1516errors. So in this case
1517
1518 use MyMod::Abc;
1519 use warnings FATAL => 'MyMod::Abc';
1520 ...
1521 MyMod::Abc::open('../fred.txt');
1522
1523the C<warnings::warnif> function will detect this and die after
1524displaying the warning message.
1525
1526The three warnings functions, C<warnings::warn>, C<warnings::warnif>
1527and C<warnings::enabled> can optionally take an object reference in place
1528of a category name. In this case the functions will use the class name
1529of the object as the warnings category.
1530
1531Consider this example:
1532
1533 package Original;
1534
1535 no warnings;
1536 use warnings::register;
1537
1538 sub new
1539 {
1540 my $class = shift;
1541 bless [], $class;
1542 }
1543
1544 sub check
1545 {
1546 my $self = shift;
1547 my $value = shift;
1548
1549 if ($value % 2 && warnings::enabled($self))
1550 { warnings::warn($self, "Odd numbers are unsafe") }
1551 }
1552
1553 sub doit
1554 {
1555 my $self = shift;
1556 my $value = shift;
1557 $self->check($value);
1558 # ...
1559 }
1560
1561 1;
1562
1563 package Derived;
1564
1565 use warnings::register;
1566 use Original;
1567 our @ISA = qw( Original );
1568 sub new
1569 {
1570 my $class = shift;
1571 bless [], $class;
1572 }
1573
1574
1575 1;
1576
56873d42 1577The code below makes use of both modules, but it only enables warnings from
33edcb80
RS
1578C<Derived>.
1579
1580 use Original;
1581 use Derived;
1582 use warnings 'Derived';
573a192d
DIM
1583 my $x = Original->new();
1584 $x->doit(1);
1585 my $y = Derived->new();
1586 $x->doit(1);
33edcb80 1587
573a192d 1588When this code is run only the C<Derived> object, C<$y>, will generate
56873d42 1589a warning.
33edcb80
RS
1590
1591 Odd numbers are unsafe at main.pl line 7
1592
1593Notice also that the warning is reported at the line where the object is first
1594used.
1595
1596When registering new categories of warning, you can supply more names to
1597warnings::register like this:
1598
1599 package MyModule;
1600 use warnings::register qw(format precision);
1601
1602 ...
fe2e802c 1603
33edcb80 1604 warnings::warnif('MyModule::format', '...');
599cee73 1605
33edcb80 1606=head1 FUNCTIONS
e476b1b5 1607
c4583f59
FC
1608Note: The functions with names ending in C<_at_level> were added in Perl
16095.28.
1610
39b50539
Z
1611=over 4
1612
d3a7d8c7
GS
1613=item use warnings::register
1614
7e6d00f8
PM
1615Creates a new warnings category with the same name as the package where
1616the call to the pragma is used.
1617
1618=item warnings::enabled()
1619
1620Use the warnings category with the same name as the current package.
1621
1622Return TRUE if that warnings category is enabled in the calling module.
1623Otherwise returns FALSE.
1624
1625=item warnings::enabled($category)
1626
1627Return TRUE if the warnings category, C<$category>, is enabled in the
1628calling module.
1629Otherwise returns FALSE.
1630
1631=item warnings::enabled($object)
1632
1633Use the name of the class for the object reference, C<$object>, as the
1634warnings category.
1635
1636Return TRUE if that warnings category is enabled in the first scope
1637where the object is used.
1638Otherwise returns FALSE.
1639
c4583f59
FC
1640=item warnings::enabled_at_level($category, $level)
1641
1642Like C<warnings::enabled>, but $level specifies the exact call frame, 0
1643being the immediate caller.
1644
ec983580
AR
1645=item warnings::fatal_enabled()
1646
1647Return TRUE if the warnings category with the same name as the current
1648package has been set to FATAL in the calling module.
1649Otherwise returns FALSE.
1650
1651=item warnings::fatal_enabled($category)
1652
1653Return TRUE if the warnings category C<$category> has been set to FATAL in
1654the calling module.
1655Otherwise returns FALSE.
1656
1657=item warnings::fatal_enabled($object)
1658
1659Use the name of the class for the object reference, C<$object>, as the
1660warnings category.
1661
1662Return TRUE if that warnings category has been set to FATAL in the first
1663scope where the object is used.
1664Otherwise returns FALSE.
1665
c4583f59
FC
1666=item warnings::fatal_enabled_at_level($category, $level)
1667
1668Like C<warnings::fatal_enabled>, but $level specifies the exact call frame,
16690 being the immediate caller.
1670
7e6d00f8
PM
1671=item warnings::warn($message)
1672
1673Print C<$message> to STDERR.
1674
1675Use the warnings category with the same name as the current package.
1676
1677If that warnings category has been set to "FATAL" in the calling module
1678then die. Otherwise return.
1679
1680=item warnings::warn($category, $message)
1681
1682Print C<$message> to STDERR.
1683
1684If the warnings category, C<$category>, has been set to "FATAL" in the
1685calling module then die. Otherwise return.
d3a7d8c7 1686
7e6d00f8 1687=item warnings::warn($object, $message)
e476b1b5 1688
7e6d00f8 1689Print C<$message> to STDERR.
e476b1b5 1690
7e6d00f8
PM
1691Use the name of the class for the object reference, C<$object>, as the
1692warnings category.
e476b1b5 1693
7e6d00f8
PM
1694If that warnings category has been set to "FATAL" in the scope where C<$object>
1695is first used then die. Otherwise return.
599cee73 1696
c4583f59
FC
1697=item warnings::warn_at_level($category, $level, $message)
1698
1699Like C<warnings::warn>, but $level specifies the exact call frame,
17000 being the immediate caller.
e476b1b5 1701
7e6d00f8
PM
1702=item warnings::warnif($message)
1703
1704Equivalent to:
1705
1706 if (warnings::enabled())
1707 { warnings::warn($message) }
1708
1709=item warnings::warnif($category, $message)
1710
1711Equivalent to:
1712
1713 if (warnings::enabled($category))
1714 { warnings::warn($category, $message) }
1715
1716=item warnings::warnif($object, $message)
1717
1718Equivalent to:
1719
1720 if (warnings::enabled($object))
1721 { warnings::warn($object, $message) }
d3a7d8c7 1722
c4583f59
FC
1723=item warnings::warnif_at_level($category, $level, $message)
1724
1725Like C<warnings::warnif>, but $level specifies the exact call frame,
17260 being the immediate caller.
1727
5e7ad92a 1728=item warnings::register_categories(@names)
13781810
FR
1729
1730This registers warning categories for the given names and is primarily for
d2ec25a5 1731use by the warnings::register pragma.
13781810 1732
e476b1b5
GS
1733=back
1734
d2ec25a5 1735See also L<perlmodlib/Pragmatic Modules> and L<perldiag>.
599cee73
PM
1736
1737=cut