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