This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add new warnings category for "use re 'strict'"
[perl5.git] / regen / warnings.pl
... / ...
CommitLineData
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 $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 $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.03';
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
30my $tree = {
31'everything' => [ 5.021, {
32 'all' => [ 5.008, {
33 'io' => [ 5.008, {
34 'pipe' => [ 5.008, DEFAULT_OFF],
35 'unopened' => [ 5.008, DEFAULT_OFF],
36 'closed' => [ 5.008, DEFAULT_OFF],
37 'newline' => [ 5.008, DEFAULT_OFF],
38 'exec' => [ 5.008, DEFAULT_OFF],
39 'layer' => [ 5.008, DEFAULT_OFF],
40 'syscalls' => [ 5.019, DEFAULT_OFF],
41 }],
42 'syntax' => [ 5.008, {
43 'ambiguous' => [ 5.008, DEFAULT_OFF],
44 'semicolon' => [ 5.008, DEFAULT_OFF],
45 'precedence' => [ 5.008, DEFAULT_OFF],
46 'bareword' => [ 5.008, DEFAULT_OFF],
47 'reserved' => [ 5.008, DEFAULT_OFF],
48 'digit' => [ 5.008, DEFAULT_OFF],
49 'parenthesis' => [ 5.008, DEFAULT_OFF],
50 'printf' => [ 5.008, DEFAULT_OFF],
51 'prototype' => [ 5.008, DEFAULT_OFF],
52 'qw' => [ 5.008, DEFAULT_OFF],
53 'illegalproto' => [ 5.011, DEFAULT_OFF],
54 }],
55 'severe' => [ 5.008, {
56 'inplace' => [ 5.008, DEFAULT_ON],
57 'internal' => [ 5.008, DEFAULT_OFF],
58 'debugging' => [ 5.008, DEFAULT_ON],
59 'malloc' => [ 5.008, DEFAULT_ON],
60 }],
61 'deprecated' => [ 5.008, DEFAULT_ON],
62 'void' => [ 5.008, DEFAULT_OFF],
63 'recursion' => [ 5.008, DEFAULT_OFF],
64 'redefine' => [ 5.008, DEFAULT_OFF],
65 'numeric' => [ 5.008, DEFAULT_OFF],
66 'uninitialized' => [ 5.008, DEFAULT_OFF],
67 'once' => [ 5.008, DEFAULT_OFF],
68 'misc' => [ 5.008, DEFAULT_OFF],
69 'regexp' => [ 5.008, DEFAULT_OFF],
70 'glob' => [ 5.008, DEFAULT_ON],
71 'untie' => [ 5.008, DEFAULT_OFF],
72 'substr' => [ 5.008, DEFAULT_OFF],
73 'taint' => [ 5.008, DEFAULT_OFF],
74 'signal' => [ 5.008, DEFAULT_OFF],
75 'closure' => [ 5.008, DEFAULT_OFF],
76 'overflow' => [ 5.008, DEFAULT_OFF],
77 'portable' => [ 5.008, DEFAULT_OFF],
78 'utf8' => [ 5.008, {
79 'surrogate' => [ 5.013, DEFAULT_OFF],
80 'nonchar' => [ 5.013, DEFAULT_OFF],
81 'non_unicode' => [ 5.013, DEFAULT_OFF],
82 }],
83 'exiting' => [ 5.008, DEFAULT_OFF],
84 'pack' => [ 5.008, DEFAULT_OFF],
85 'unpack' => [ 5.008, DEFAULT_OFF],
86 'threads' => [ 5.008, DEFAULT_OFF],
87 'imprecision' => [ 5.011, DEFAULT_OFF],
88 'experimental' => [ 5.017, {
89 'experimental::lexical_subs' =>
90 [ 5.017, DEFAULT_ON ],
91 'experimental::regex_sets' =>
92 [ 5.017, DEFAULT_ON ],
93 'experimental::lexical_topic' =>
94 [ 5.017, DEFAULT_ON ],
95 'experimental::smartmatch' =>
96 [ 5.017, DEFAULT_ON ],
97 'experimental::postderef' =>
98 [ 5.019, DEFAULT_ON ],
99 'experimental::autoderef' =>
100 [ 5.019, DEFAULT_ON ],
101 'experimental::signatures' =>
102 [ 5.019, DEFAULT_ON ],
103 'experimental::win32_perlio' =>
104 [ 5.021, DEFAULT_ON ],
105 'experimental::refaliasing' =>
106 [ 5.021, DEFAULT_ON ],
107 'experimental::re_strict' =>
108 [ 5.021, DEFAULT_ON ],
109 }],
110
111 'missing' => [ 5.021, DEFAULT_OFF],
112 'redundant' => [ 5.021, DEFAULT_OFF],
113 'locale' => [ 5.021, DEFAULT_ON],
114
115 #'default' => [ 5.008, DEFAULT_ON ],
116 }],
117
118 # When adding new warnings outside of "all" make sure to
119 # either patch util.c to ignore them under -w and -W, or to
120 # generalize the facility for adding them so that it knows
121 # about warnings outside of "all".
122 'extra' => [ 5.021, {
123 'void_unusual' => [ 5.021, DEFAULT_OFF],
124 }],
125}]};
126
127my @def ;
128my %list ;
129my %Value ;
130my %ValueToName ;
131my %NameToValue ;
132
133my %v_list = () ;
134
135sub valueWalk
136{
137 my $tre = shift ;
138 my @list = () ;
139 my ($k, $v) ;
140
141 foreach $k (sort keys %$tre) {
142 $v = $tre->{$k};
143 die "duplicate key $k\n" if defined $list{$k} ;
144 die "Value associated with key '$k' is not an ARRAY reference"
145 if !ref $v || ref $v ne 'ARRAY' ;
146
147 my ($ver, $rest) = @{ $v } ;
148 push @{ $v_list{$ver} }, $k;
149
150 if (ref $rest)
151 { valueWalk ($rest) }
152
153 }
154
155}
156
157sub orderValues
158{
159 my $index = 0;
160 foreach my $ver ( sort { $a <=> $b } keys %v_list ) {
161 foreach my $name (@{ $v_list{$ver} } ) {
162 $ValueToName{ $index } = [ uc $name, $ver ] ;
163 $NameToValue{ uc $name } = $index ++ ;
164 }
165 }
166
167 return $index ;
168}
169
170###########################################################################
171
172sub walk
173{
174 my $tre = shift ;
175 my @list = () ;
176 my ($k, $v) ;
177
178 foreach $k (sort keys %$tre) {
179 $v = $tre->{$k};
180 die "duplicate key $k\n" if defined $list{$k} ;
181 die "Can't find key '$k'"
182 if ! defined $NameToValue{uc $k} ;
183 push @{ $list{$k} }, $NameToValue{uc $k} ;
184 die "Value associated with key '$k' is not an ARRAY reference"
185 if !ref $v || ref $v ne 'ARRAY' ;
186
187 my ($ver, $rest) = @{ $v } ;
188 if (ref $rest)
189 { push (@{ $list{$k} }, walk ($rest)) }
190 elsif ($rest == DEFAULT_ON)
191 { push @def, $NameToValue{uc $k} }
192
193 push @list, @{ $list{$k} } ;
194 }
195
196 return @list ;
197}
198
199###########################################################################
200
201sub mkRange
202{
203 my @a = @_ ;
204 my @out = @a ;
205
206 for my $i (1 .. @a - 1) {
207 $out[$i] = ".."
208 if $a[$i] == $a[$i - 1] + 1
209 && ($i >= @a - 1 || $a[$i] + 1 == $a[$i + 1] );
210 }
211 $out[-1] = $a[-1] if $out[-1] eq "..";
212
213 my $out = join(",",@out);
214
215 $out =~ s/,(\.\.,)+/../g ;
216 return $out;
217}
218
219###########################################################################
220sub warningsTree
221{
222 my $tre = shift ;
223 my $prefix = shift ;
224 my ($k, $v) ;
225
226 my $max = (sort {$a <=> $b} map { length $_ } keys %$tre)[-1] ;
227 my @keys = sort keys %$tre ;
228
229 my $rv = '';
230
231 while ($k = shift @keys) {
232 $v = $tre->{$k};
233 die "Value associated with key '$k' is not an ARRAY reference"
234 if !ref $v || ref $v ne 'ARRAY' ;
235
236 my $offset ;
237 if ($tre ne $tree) {
238 $rv .= $prefix . "|\n" ;
239 $rv .= $prefix . "+- $k" ;
240 $offset = ' ' x ($max + 4) ;
241 }
242 else {
243 $rv .= $prefix . "$k" ;
244 $offset = ' ' x ($max + 1) ;
245 }
246
247 my ($ver, $rest) = @{ $v } ;
248 if (ref $rest)
249 {
250 my $bar = @keys ? "|" : " ";
251 $rv .= " -" . "-" x ($max - length $k ) . "+\n" ;
252 $rv .= warningsTree ($rest, $prefix . $bar . $offset )
253 }
254 else
255 { $rv .= "\n" }
256 }
257
258 return $rv;
259}
260
261###########################################################################
262
263sub mkHexOct
264{
265 my ($f, $max, @a) = @_ ;
266 my $mask = "\x00" x $max ;
267 my $string = "" ;
268
269 foreach (@a) {
270 vec($mask, $_, 1) = 1 ;
271 }
272
273 foreach (unpack("C*", $mask)) {
274 if ($f eq 'x') {
275 $string .= '\x' . sprintf("%2.2x", $_)
276 }
277 else {
278 $string .= '\\' . sprintf("%o", $_)
279 }
280 }
281 return $string ;
282}
283
284sub mkHex
285{
286 my($max, @a) = @_;
287 return mkHexOct("x", $max, @a);
288}
289
290sub mkOct
291{
292 my($max, @a) = @_;
293 return mkHexOct("o", $max, @a);
294}
295
296###########################################################################
297
298if (@ARGV && $ARGV[0] eq "tree")
299{
300 print warningsTree($tree, " ") ;
301 exit ;
302}
303
304my ($warn, $pm) = map {
305 open_new($_, '>', { by => 'regen/warnings.pl' });
306} 'warnings.h', 'lib/warnings.pm';
307
308my ($index, $warn_size);
309
310{
311 # generate warnings.h
312
313 print $warn <<'EOM';
314
315#define Off(x) ((x) / 8)
316#define Bit(x) (1 << ((x) % 8))
317#define IsSet(a, x) ((a)[Off(x)] & Bit(x))
318
319
320#define G_WARN_OFF 0 /* $^W == 0 */
321#define G_WARN_ON 1 /* -w flag and $^W != 0 */
322#define G_WARN_ALL_ON 2 /* -W flag */
323#define G_WARN_ALL_OFF 4 /* -X flag */
324#define G_WARN_ONCE 8 /* set if 'once' ever enabled */
325#define G_WARN_ALL_MASK (G_WARN_ALL_ON|G_WARN_ALL_OFF)
326
327#define pWARN_STD NULL
328#define pWARN_ALL (((STRLEN*)0)+1) /* use warnings 'all' */
329#define pWARN_NONE (((STRLEN*)0)+2) /* no warnings 'all' */
330
331#define specialWARN(x) ((x) == pWARN_STD || (x) == pWARN_ALL || \
332 (x) == pWARN_NONE)
333
334/* if PL_warnhook is set to this value, then warnings die */
335#define PERL_WARNHOOK_FATAL (&PL_sv_placeholder)
336EOM
337
338 my $offset = 0 ;
339
340 valueWalk ($tree) ;
341 $index = orderValues();
342
343 die <<EOM if $index > 255 ;
344Too many warnings categories -- max is 255
345 rewrite packWARN* & unpackWARN* macros
346EOM
347
348 walk ($tree) ;
349
350 $index *= 2 ;
351 $warn_size = int($index / 8) + ($index % 8 != 0) ;
352
353 my $k ;
354 my $last_ver = 0;
355 foreach $k (sort { $a <=> $b } keys %ValueToName) {
356 my ($name, $version) = @{ $ValueToName{$k} };
357 print $warn "\n/* Warnings Categories added in Perl $version */\n\n"
358 if $last_ver != $version ;
359 $name =~ y/:/_/;
360 print $warn tab(5, "#define WARN_$name"), " $k\n" ;
361 $last_ver = $version ;
362 }
363 print $warn "\n" ;
364
365 print $warn tab(5, '#define WARNsize'), "$warn_size\n" ;
366 print $warn tab(5, '#define WARN_ALLstring'), '"', ('\125' x $warn_size) , "\"\n" ;
367 print $warn tab(5, '#define WARN_NONEstring'), '"', ('\0' x $warn_size) , "\"\n" ;
368
369 print $warn <<'EOM';
370
371#define isLEXWARN_on (PL_curcop->cop_warnings != pWARN_STD)
372#define isLEXWARN_off (PL_curcop->cop_warnings == pWARN_STD)
373#define isWARN_ONCE (PL_dowarn & (G_WARN_ON|G_WARN_ONCE))
374#define isWARN_on(c,x) (IsSet((U8 *)(c + 1), 2*(x)))
375#define isWARNf_on(c,x) (IsSet((U8 *)(c + 1), 2*(x)+1))
376
377#define DUP_WARNINGS(p) \
378 (specialWARN(p) ? (STRLEN*)(p) \
379 : (STRLEN*)CopyD(p, PerlMemShared_malloc(sizeof(*p)+*p), sizeof(*p)+*p, \
380 char))
381
382#define ckWARN(w) Perl_ckwarn(aTHX_ packWARN(w))
383
384/* The w1, w2 ... should be independent warnings categories; one shouldn't be
385 * a subcategory of any other */
386
387#define ckWARN2(w1,w2) Perl_ckwarn(aTHX_ packWARN2(w1,w2))
388#define ckWARN3(w1,w2,w3) Perl_ckwarn(aTHX_ packWARN3(w1,w2,w3))
389#define ckWARN4(w1,w2,w3,w4) Perl_ckwarn(aTHX_ packWARN4(w1,w2,w3,w4))
390
391#define ckWARN_d(w) Perl_ckwarn_d(aTHX_ packWARN(w))
392#define ckWARN2_d(w1,w2) Perl_ckwarn_d(aTHX_ packWARN2(w1,w2))
393#define ckWARN3_d(w1,w2,w3) Perl_ckwarn_d(aTHX_ packWARN3(w1,w2,w3))
394#define ckWARN4_d(w1,w2,w3,w4) Perl_ckwarn_d(aTHX_ packWARN4(w1,w2,w3,w4))
395
396#define WARNshift 8
397
398#define packWARN(a) (a )
399
400/* The a, b, ... should be independent warnings categories; one shouldn't be
401 * a subcategory of any other */
402
403#define packWARN2(a,b) ((a) | ((b)<<8) )
404#define packWARN3(a,b,c) ((a) | ((b)<<8) | ((c)<<16) )
405#define packWARN4(a,b,c,d) ((a) | ((b)<<8) | ((c)<<16) | ((d) <<24))
406
407#define unpackWARN1(x) ((x) & 0xFF)
408#define unpackWARN2(x) (((x) >>8) & 0xFF)
409#define unpackWARN3(x) (((x) >>16) & 0xFF)
410#define unpackWARN4(x) (((x) >>24) & 0xFF)
411
412#define ckDEAD(x) \
413 ( ! specialWARN(PL_curcop->cop_warnings) && \
414 ( isWARNf_on(PL_curcop->cop_warnings, WARN_ALL) || \
415 isWARNf_on(PL_curcop->cop_warnings, unpackWARN1(x)) || \
416 isWARNf_on(PL_curcop->cop_warnings, unpackWARN2(x)) || \
417 isWARNf_on(PL_curcop->cop_warnings, unpackWARN3(x)) || \
418 isWARNf_on(PL_curcop->cop_warnings, unpackWARN4(x))))
419
420/* end of file warnings.h */
421EOM
422
423 read_only_bottom_close_and_rename($warn);
424}
425
426while (<DATA>) {
427 last if /^KEYWORDS$/ ;
428 print $pm $_ ;
429}
430
431my $last_ver = 0;
432print $pm "our %Offsets = (\n" ;
433foreach my $k (sort { $a <=> $b } keys %ValueToName) {
434 my ($name, $version) = @{ $ValueToName{$k} };
435 $name = lc $name;
436 $k *= 2 ;
437 if ( $last_ver != $version ) {
438 print $pm "\n";
439 print $pm tab(4, " # Warnings Categories added in Perl $version");
440 print $pm "\n\n";
441 }
442 print $pm tab(4, " '$name'"), "=> $k,\n" ;
443 $last_ver = $version;
444}
445
446print $pm " );\n\n" ;
447
448print $pm "our %Bits = (\n" ;
449foreach my $k (sort keys %list) {
450
451 my $v = $list{$k} ;
452 my @list = sort { $a <=> $b } @$v ;
453
454 print $pm tab(4, " '$k'"), '=> "',
455 mkHex($warn_size, map $_ * 2 , @list),
456 '", # [', mkRange(@list), "]\n" ;
457}
458
459print $pm " );\n\n" ;
460
461print $pm "our %DeadBits = (\n" ;
462foreach my $k (sort keys %list) {
463
464 my $v = $list{$k} ;
465 my @list = sort { $a <=> $b } @$v ;
466
467 print $pm tab(4, " '$k'"), '=> "',
468 mkHex($warn_size, map $_ * 2 + 1 , @list),
469 '", # [', mkRange(@list), "]\n" ;
470}
471
472print $pm " );\n\n" ;
473print $pm '$NONE = "', ('\0' x $warn_size) , "\";\n" ;
474print $pm '$DEFAULT = "', mkHex($warn_size, map $_ * 2, @def),
475 '", # [', mkRange(@def), "]\n" ;
476print $pm '$LAST_BIT = ' . "$index ;\n" ;
477print $pm '$BYTES = ' . "$warn_size ;\n" ;
478while (<DATA>) {
479 if ($_ eq "=for warnings.pl tree-goes-here\n") {
480 print $pm warningsTree($tree, " ");
481 next;
482 }
483 print $pm $_ ;
484}
485
486read_only_bottom_close_and_rename($pm);
487
488__END__
489package warnings;
490
491our $VERSION = '1.30';
492
493# Verify that we're called correctly so that warnings will work.
494# see also strict.pm.
495unless ( __FILE__ =~ /(^|[\/\\])\Q${\__PACKAGE__}\E\.pmc?$/ ) {
496 my (undef, $f, $l) = caller;
497 die("Incorrect use of pragma '${\__PACKAGE__}' at $f line $l.\n");
498}
499
500KEYWORDS
501
502$All = "" ; vec($All, $Offsets{'all'}, 2) = 3 ;
503
504sub Croaker
505{
506 require Carp; # this initializes %CarpInternal
507 local $Carp::CarpInternal{'warnings'};
508 delete $Carp::CarpInternal{'warnings'};
509 Carp::croak(@_);
510}
511
512sub _bits {
513 my $mask = shift ;
514 my $catmask ;
515 my $fatal = 0 ;
516 my $no_fatal = 0 ;
517
518 foreach my $word ( @_ ) {
519 if ($word eq 'FATAL') {
520 $fatal = 1;
521 $no_fatal = 0;
522 }
523 elsif ($word eq 'NONFATAL') {
524 $fatal = 0;
525 $no_fatal = 1;
526 }
527 elsif ($catmask = $Bits{$word}) {
528 $mask |= $catmask ;
529 $mask |= $DeadBits{$word} if $fatal ;
530 $mask &= ~($DeadBits{$word}|$All) if $no_fatal ;
531 }
532 else
533 { Croaker("Unknown warnings category '$word'")}
534 }
535
536 return $mask ;
537}
538
539sub bits
540{
541 # called from B::Deparse.pm
542 push @_, 'all' unless @_ ;
543 return _bits(undef, @_) ;
544}
545
546sub import
547{
548 shift;
549
550 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
551
552 if (vec($mask, $Offsets{'all'}, 1)) {
553 $mask |= $Bits{'all'} ;
554 $mask |= $DeadBits{'all'} if vec($mask, $Offsets{'all'}+1, 1);
555 }
556
557 # append 'all' when implied (after a lone "FATAL" or "NONFATAL")
558 push @_, 'all' if @_==1 && ( $_[0] eq 'FATAL' || $_[0] eq 'NONFATAL' );
559
560 # Empty @_ is equivalent to @_ = 'all' ;
561 ${^WARNING_BITS} = @_ ? _bits($mask, @_) : $mask | $Bits{all} ;
562}
563
564sub unimport
565{
566 shift;
567
568 my $catmask ;
569 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
570
571 if (vec($mask, $Offsets{'all'}, 1)) {
572 $mask |= $Bits{'all'} ;
573 $mask |= $DeadBits{'all'} if vec($mask, $Offsets{'all'}+1, 1);
574 }
575
576 # append 'all' when implied (empty import list or after a lone "FATAL")
577 push @_, 'all' if !@_ || @_==1 && $_[0] eq 'FATAL';
578
579 foreach my $word ( @_ ) {
580 if ($word eq 'FATAL') {
581 next;
582 }
583 elsif ($catmask = $Bits{$word}) {
584 $mask &= ~($catmask | $DeadBits{$word} | $All);
585 }
586 else
587 { Croaker("Unknown warnings category '$word'")}
588 }
589
590 ${^WARNING_BITS} = $mask ;
591}
592
593my %builtin_type; @builtin_type{qw(SCALAR ARRAY HASH CODE REF GLOB LVALUE Regexp)} = ();
594
595sub MESSAGE () { 4 };
596sub FATAL () { 2 };
597sub NORMAL () { 1 };
598
599sub __chk
600{
601 my $category ;
602 my $offset ;
603 my $isobj = 0 ;
604 my $wanted = shift;
605 my $has_message = $wanted & MESSAGE;
606
607 unless (@_ == 1 || @_ == ($has_message ? 2 : 0)) {
608 my $sub = (caller 1)[3];
609 my $syntax = $has_message ? "[category,] 'message'" : '[category]';
610 Croaker("Usage: $sub($syntax)");
611 }
612
613 my $message = pop if $has_message;
614
615 if (@_) {
616 # check the category supplied.
617 $category = shift ;
618 if (my $type = ref $category) {
619 Croaker("not an object")
620 if exists $builtin_type{$type};
621 $category = $type;
622 $isobj = 1 ;
623 }
624 $offset = $Offsets{$category};
625 Croaker("Unknown warnings category '$category'")
626 unless defined $offset;
627 }
628 else {
629 $category = (caller(1))[0] ;
630 $offset = $Offsets{$category};
631 Croaker("package '$category' not registered for warnings")
632 unless defined $offset ;
633 }
634
635 my $i;
636
637 if ($isobj) {
638 my $pkg;
639 $i = 2;
640 while (do { { package DB; $pkg = (caller($i++))[0] } } ) {
641 last unless @DB::args && $DB::args[0] =~ /^$category=/ ;
642 }
643 $i -= 2 ;
644 }
645 else {
646 $i = _error_loc(); # see where Carp will allocate the error
647 }
648
649 # Default to 0 if caller returns nothing. Default to $DEFAULT if it
650 # explicitly returns undef.
651 my(@callers_bitmask) = (caller($i))[9] ;
652 my $callers_bitmask =
653 @callers_bitmask ? $callers_bitmask[0] // $DEFAULT : 0 ;
654
655 my @results;
656 foreach my $type (FATAL, NORMAL) {
657 next unless $wanted & $type;
658
659 push @results, (vec($callers_bitmask, $offset + $type - 1, 1) ||
660 vec($callers_bitmask, $Offsets{'all'} + $type - 1, 1));
661 }
662
663 # &enabled and &fatal_enabled
664 return $results[0] unless $has_message;
665
666 # &warnif, and the category is neither enabled as warning nor as fatal
667 return if $wanted == (NORMAL | FATAL | MESSAGE)
668 && !($results[0] || $results[1]);
669
670 require Carp;
671 Carp::croak($message) if $results[0];
672 # will always get here for &warn. will only get here for &warnif if the
673 # category is enabled
674 Carp::carp($message);
675}
676
677sub _mkMask
678{
679 my ($bit) = @_;
680 my $mask = "";
681
682 vec($mask, $bit, 1) = 1;
683 return $mask;
684}
685
686sub register_categories
687{
688 my @names = @_;
689
690 for my $name (@names) {
691 if (! defined $Bits{$name}) {
692 $Bits{$name} = _mkMask($LAST_BIT);
693 vec($Bits{'all'}, $LAST_BIT, 1) = 1;
694 $Offsets{$name} = $LAST_BIT ++;
695 foreach my $k (keys %Bits) {
696 vec($Bits{$k}, $LAST_BIT, 1) = 0;
697 }
698 $DeadBits{$name} = _mkMask($LAST_BIT);
699 vec($DeadBits{'all'}, $LAST_BIT++, 1) = 1;
700 }
701 }
702}
703
704sub _error_loc {
705 require Carp;
706 goto &Carp::short_error_loc; # don't introduce another stack frame
707}
708
709sub enabled
710{
711 return __chk(NORMAL, @_);
712}
713
714sub fatal_enabled
715{
716 return __chk(FATAL, @_);
717}
718
719sub warn
720{
721 return __chk(FATAL | MESSAGE, @_);
722}
723
724sub warnif
725{
726 return __chk(NORMAL | FATAL | MESSAGE, @_);
727}
728
729# These are not part of any public interface, so we can delete them to save
730# space.
731delete @warnings::{qw(NORMAL FATAL MESSAGE)};
732
7331;
734__END__
735=head1 NAME
736
737warnings - Perl pragma to control optional warnings
738
739=head1 SYNOPSIS
740
741 use warnings;
742 no warnings;
743
744 use warnings "all";
745 no warnings "all";
746
747 use warnings::register;
748 if (warnings::enabled()) {
749 warnings::warn("some warning");
750 }
751
752 if (warnings::enabled("void")) {
753 warnings::warn("void", "some warning");
754 }
755
756 if (warnings::enabled($object)) {
757 warnings::warn($object, "some warning");
758 }
759
760 warnings::warnif("some warning");
761 warnings::warnif("void", "some warning");
762 warnings::warnif($object, "some warning");
763
764=head1 DESCRIPTION
765
766The C<warnings> pragma gives control over which warnings are enabled in
767which parts of a Perl program. It's a more flexible alternative for
768both the command line flag B<-w> and the equivalent Perl variable,
769C<$^W>.
770
771This pragma works just like the C<strict> pragma.
772This means that the scope of the warning pragma is limited to the
773enclosing block. It also means that the pragma setting will not
774leak across files (via C<use>, C<require> or C<do>). This allows
775authors to independently define the degree of warning checks that will
776be applied to their module.
777
778By default, optional warnings are disabled, so any legacy code that
779doesn't attempt to control the warnings will work unchanged.
780
781When we talk about "all" warnings we don't actually mean "all the
782warnings we support". See L</Top-level warning categories & associated
783confusion> for details. The "all" category should really be called the
784"default" category, if not for backwards-compatibility concerns.
785
786"All" warnings are enabled in a block by either of these:
787
788 use warnings;
789 use warnings 'all';
790
791Similarly "all" warnings are disabled in a block by either of these:
792
793 no warnings;
794 no warnings 'all';
795
796For example, consider the code below:
797
798 use warnings;
799 my @a;
800 {
801 no warnings;
802 my $b = @a[0];
803 }
804 my $c = @a[0];
805
806The code in the enclosing block has warnings enabled, but the inner
807block has them disabled. In this case that means the assignment to the
808scalar C<$c> will trip the C<"Scalar value @a[0] better written as $a[0]">
809warning, but the assignment to the scalar C<$b> will not.
810
811=head2 Default Warnings and Optional Warnings
812
813Before the introduction of lexical warnings, Perl had two classes of
814warnings: mandatory and optional.
815
816As its name suggests, if your code tripped a mandatory warning, you
817would get a warning whether you wanted it or not.
818For example, the code below would always produce an C<"isn't numeric">
819warning about the "2:".
820
821 my $a = "2:" + 3;
822
823With the introduction of lexical warnings, mandatory warnings now become
824I<default> warnings. The difference is that although the previously
825mandatory warnings are still enabled by default, they can then be
826subsequently enabled or disabled with the lexical warning pragma. For
827example, in the code below, an C<"isn't numeric"> warning will only
828be reported for the C<$a> variable.
829
830 my $a = "2:" + 3;
831 no warnings;
832 my $b = "2:" + 3;
833
834Note that neither the B<-w> flag or the C<$^W> can be used to
835disable/enable default warnings. They are still mandatory in this case.
836
837=head2 What's wrong with B<-w> and C<$^W>
838
839Although very useful, the big problem with using B<-w> on the command
840line to enable warnings is that it is all or nothing. Take the typical
841scenario when you are writing a Perl program. Parts of the code you
842will write yourself, but it's very likely that you will make use of
843pre-written Perl modules. If you use the B<-w> flag in this case, you
844end up enabling warnings in pieces of code that you haven't written.
845
846Similarly, using C<$^W> to either disable or enable blocks of code is
847fundamentally flawed. For a start, say you want to disable warnings in
848a block of code. You might expect this to be enough to do the trick:
849
850 {
851 local ($^W) = 0;
852 my $a =+ 2;
853 my $b; chop $b;
854 }
855
856When this code is run with the B<-w> flag, a warning will be produced
857for the C<$a> line: C<"Reversed += operator">.
858
859The problem is that Perl has both compile-time and run-time warnings. To
860disable compile-time warnings you need to rewrite the code like this:
861
862 {
863 BEGIN { $^W = 0 }
864 my $a =+ 2;
865 my $b; chop $b;
866 }
867
868The other big problem with C<$^W> is the way you can inadvertently
869change the warning setting in unexpected places in your code. For example,
870when the code below is run (without the B<-w> flag), the second call
871to C<doit> will trip a C<"Use of uninitialized value"> warning, whereas
872the first will not.
873
874 sub doit
875 {
876 my $b; chop $b;
877 }
878
879 doit();
880
881 {
882 local ($^W) = 1;
883 doit()
884 }
885
886This is a side-effect of C<$^W> being dynamically scoped.
887
888Lexical warnings get around these limitations by allowing finer control
889over where warnings can or can't be tripped.
890
891=head2 Controlling Warnings from the Command Line
892
893There are three Command Line flags that can be used to control when
894warnings are (or aren't) produced:
895
896=over 5
897
898=item B<-w>
899X<-w>
900
901This is the existing flag. If the lexical warnings pragma is B<not>
902used in any of you code, or any of the modules that you use, this flag
903will enable warnings everywhere. See L<Backward Compatibility> for
904details of how this flag interacts with lexical warnings.
905
906=item B<-W>
907X<-W>
908
909If the B<-W> flag is used on the command line, it will enable "all" warnings
910throughout the program regardless of whether warnings were disabled
911locally using C<no warnings> or C<$^W =0>.
912This includes all files that get
913included via C<use>, C<require> or C<do>.
914Think of it as the Perl equivalent of the "lint" command.
915
916=item B<-X>
917X<-X>
918
919Does the exact opposite to the B<-W> flag, i.e. it disables "all" warnings.
920
921=back
922
923=head2 Top-level warning categories & associated confusion
924
925The lexical warning pragma was introduced in v5.6.0 of perl, and from
926the very beginning doing C<use warnings> would enable the "all"
927category of warnings, which were all the warnings we support.
928
929This led to arguments whenever someone suggested a new warning be
930added to perl, since that implicitly meant that existing programs that
931used the warnings pragma would be retroactively subjected to them when
932perl was upgraded.
933
934So similarly to how most C compilers support C<-Wall> to mean "not
935quite all warnings" along with extra options like C<-Wextra>, we
936support warnings outside of the "all" category. Think of the "all"
937category as "default", that's what we'd call it we were starting out
938today and didn't have a bunch of programs doing C<use warnings "all">
939in the wild already.
940
941The categories we support are:
942
943=over
944
945=item * all
946
947This is the "default" category for warnings that we've supported ever
948since v5.6.0. We have and might occasionally add new warnings here if
949they're deemed to be similar in nature to our existing warnings, but
950mostly these are things we're pretty sure are a logic error, but
951aren't irrecoverable, so they're not a runtime error.
952
953When you upgrade perl you might find that we've added some new
954warnings here, but they won't be anything wildly different from the
955current set of warnings, so the burden of going through your existing
956code and auditing the new parts that are warning should be fairly
957light.
958
959=item * everything
960
961This is what "all" would be if the world made any sense, but since we
962started out with "all" you need to enable "everything" to really
963enable "all the warnings".
964
965You almost definitely don't want to enable "everything", unless you're
966willing to potentially get a flood of new warnings with every perl
967upgrade, and those warnings may be entirely different in spirit to
968existing warnings shipped with previous releases.
969
970Maybe we'll start introducing really pedantic warnings that aren't
971useful for most cases, maybe we'll start warning about inconsistent
972indentation, who knows? If you really want ALL the warnings perl has
973to offer enable these, otherwise stick with some more sane category.
974
975=item * extra
976
977These are warnings that we might have put into "all"
978(a.k.a. "default") if we had a time machine and were starting out with
979perl today, but they'd probably cause too much of a disruption today
980so we're not doing that.
981
982As of writing this the sole warning in this category is a warning
983about useless use of grep in void context, but unlike for the "all"
984category we reserve the right to freely add things to this category in
985the future.
986
987=back
988
989In the future we might add any number of other top-level
990categories. The backwards-compatibility promises of those categories
991(if any) will be documented here.
992
993=head2 Backward Compatibility
994
995If you are used to working with a version of Perl prior to the
996introduction of lexically scoped warnings, or have code that uses both
997lexical warnings and C<$^W>, this section will describe how they interact.
998
999How Lexical Warnings interact with B<-w>/C<$^W>:
1000
1001=over 5
1002
1003=item 1.
1004
1005If none of the three command line flags (B<-w>, B<-W> or B<-X>) that
1006control warnings is used and neither C<$^W> nor the C<warnings> pragma
1007are used, then default warnings will be enabled and optional warnings
1008disabled.
1009This means that legacy code that doesn't attempt to control the warnings
1010will work unchanged.
1011
1012=item 2.
1013
1014The B<-w> flag just sets the global C<$^W> variable as in 5.005. This
1015means that any legacy code that currently relies on manipulating C<$^W>
1016to control warning behavior will still work as is.
1017
1018=item 3.
1019
1020Apart from now being a boolean, the C<$^W> variable operates in exactly
1021the same horrible uncontrolled global way, except that it cannot
1022disable/enable default warnings.
1023
1024=item 4.
1025
1026If a piece of code is under the control of the C<warnings> pragma,
1027both the C<$^W> variable and the B<-w> flag will be ignored for the
1028scope of the lexical warning.
1029
1030=item 5.
1031
1032The only way to override a lexical warnings setting is with the B<-W>
1033or B<-X> command line flags.
1034
1035=back
1036
1037The combined effect of 3 & 4 is that it will allow code which uses
1038the C<warnings> pragma to control the warning behavior of $^W-type
1039code (using a C<local $^W=0>) if it really wants to, but not vice-versa.
1040
1041=head2 Category Hierarchy
1042X<warning, categories>
1043
1044A hierarchy of "categories" have been defined to allow groups of warnings
1045to be enabled/disabled in isolation.
1046
1047The current hierarchy is:
1048
1049=for warnings.pl tree-goes-here
1050
1051Just like the "strict" pragma any of these categories can be combined
1052
1053 use warnings qw(void redefine);
1054 no warnings qw(io syntax untie);
1055
1056Also like the "strict" pragma, if there is more than one instance of the
1057C<warnings> pragma in a given scope the cumulative effect is additive.
1058
1059 use warnings qw(void); # only "void" warnings enabled
1060 ...
1061 use warnings qw(io); # only "void" & "io" warnings enabled
1062 ...
1063 no warnings qw(void); # only "io" warnings enabled
1064
1065To determine which category a specific warning has been assigned to see
1066L<perldiag>.
1067
1068Note: Before Perl 5.8.0, the lexical warnings category "deprecated" was a
1069sub-category of the "syntax" category. It is now a top-level category
1070in its own right.
1071
1072Note: Before 5.21.0, the "missing" lexical warnings category was
1073internally defined to be the same as the "uninitialized" category. It
1074is now a top-level category in its own right.
1075
1076=head2 Fatal Warnings
1077X<warning, fatal>
1078
1079The presence of the word "FATAL" in the category list will escalate any
1080warnings detected from the categories specified in the lexical scope
1081into fatal errors. In the code below, the use of C<time>, C<length>
1082and C<join> can all produce a C<"Useless use of xxx in void context">
1083warning.
1084
1085 use warnings;
1086
1087 time;
1088
1089 {
1090 use warnings FATAL => qw(void);
1091 length "abc";
1092 }
1093
1094 join "", 1,2,3;
1095
1096 print "done\n";
1097
1098When run it produces this output
1099
1100 Useless use of time in void context at fatal line 3.
1101 Useless use of length in void context at fatal line 7.
1102
1103The scope where C<length> is used has escalated the C<void> warnings
1104category into a fatal error, so the program terminates immediately when it
1105encounters the warning.
1106
1107To explicitly turn off a "FATAL" warning you just disable the warning
1108it is associated with. So, for example, to disable the "void" warning
1109in the example above, either of these will do the trick:
1110
1111 no warnings qw(void);
1112 no warnings FATAL => qw(void);
1113
1114If you want to downgrade a warning that has been escalated into a fatal
1115error back to a normal warning, you can use the "NONFATAL" keyword. For
1116example, the code below will promote all warnings into fatal errors,
1117except for those in the "syntax" category.
1118
1119 use warnings FATAL => 'all', NONFATAL => 'syntax';
1120
1121As of Perl 5.20, instead of C<< use warnings FATAL => 'all'; >> you can
1122use:
1123
1124 use v5.20; # Perl 5.20 or greater is required for the following
1125 use warnings 'FATAL'; # short form of "use warnings FATAL => 'all';"
1126
1127If you want your program to be compatible with versions of Perl before
11285.20, you must use C<< use warnings FATAL => 'all'; >> instead. (In
1129previous versions of Perl, the behavior of the statements
1130C<< use warnings 'FATAL'; >>, C<< use warnings 'NONFATAL'; >> and
1131C<< no warnings 'FATAL'; >> was unspecified; they did not behave as if
1132they included the C<< => 'all' >> portion. As of 5.20, they do.)
1133
1134B<NOTE:> Users of FATAL warnings, especially
1135those using C<< FATAL => 'all' >>
1136should be fully aware that they are risking future portability of their
1137programs by doing so. Perl makes absolutely no commitments to not
1138introduce new warnings, or warnings categories in the future, and indeed
1139we explicitly reserve the right to do so. Code that may not warn now may
1140warn in a future release of Perl if the Perl5 development team deems it
1141in the best interests of the community to do so. Should code using FATAL
1142warnings break due to the introduction of a new warning we will NOT
1143consider it an incompatible change. Users of FATAL warnings should take
1144special caution during upgrades to check to see if their code triggers
1145any new warnings and should pay particular attention to the fine print of
1146the documentation of the features they use to ensure they do not exploit
1147features that are documented as risky, deprecated, or unspecified, or where
1148the documentation says "so don't do that", or anything with the same sense
1149and spirit. Use of such features in combination with FATAL warnings is
1150ENTIRELY AT THE USER'S RISK.
1151
1152=head2 Reporting Warnings from a Module
1153X<warning, reporting> X<warning, registering>
1154
1155The C<warnings> pragma provides a number of functions that are useful for
1156module authors. These are used when you want to report a module-specific
1157warning to a calling module has enabled warnings via the C<warnings>
1158pragma.
1159
1160Consider the module C<MyMod::Abc> below.
1161
1162 package MyMod::Abc;
1163
1164 use warnings::register;
1165
1166 sub open {
1167 my $path = shift;
1168 if ($path !~ m#^/#) {
1169 warnings::warn("changing relative path to /var/abc")
1170 if warnings::enabled();
1171 $path = "/var/abc/$path";
1172 }
1173 }
1174
1175 1;
1176
1177The call to C<warnings::register> will create a new warnings category
1178called "MyMod::Abc", i.e. the new category name matches the current
1179package name. The C<open> function in the module will display a warning
1180message if it gets given a relative path as a parameter. This warnings
1181will only be displayed if the code that uses C<MyMod::Abc> has actually
1182enabled them with the C<warnings> pragma like below.
1183
1184 use MyMod::Abc;
1185 use warnings 'MyMod::Abc';
1186 ...
1187 abc::open("../fred.txt");
1188
1189It is also possible to test whether the pre-defined warnings categories are
1190set in the calling module with the C<warnings::enabled> function. Consider
1191this snippet of code:
1192
1193 package MyMod::Abc;
1194
1195 sub open {
1196 warnings::warnif("deprecated",
1197 "open is deprecated, use new instead");
1198 new(@_);
1199 }
1200
1201 sub new
1202 ...
1203 1;
1204
1205The function C<open> has been deprecated, so code has been included to
1206display a warning message whenever the calling module has (at least) the
1207"deprecated" warnings category enabled. Something like this, say.
1208
1209 use warnings 'deprecated';
1210 use MyMod::Abc;
1211 ...
1212 MyMod::Abc::open($filename);
1213
1214Either the C<warnings::warn> or C<warnings::warnif> function should be
1215used to actually display the warnings message. This is because they can
1216make use of the feature that allows warnings to be escalated into fatal
1217errors. So in this case
1218
1219 use MyMod::Abc;
1220 use warnings FATAL => 'MyMod::Abc';
1221 ...
1222 MyMod::Abc::open('../fred.txt');
1223
1224the C<warnings::warnif> function will detect this and die after
1225displaying the warning message.
1226
1227The three warnings functions, C<warnings::warn>, C<warnings::warnif>
1228and C<warnings::enabled> can optionally take an object reference in place
1229of a category name. In this case the functions will use the class name
1230of the object as the warnings category.
1231
1232Consider this example:
1233
1234 package Original;
1235
1236 no warnings;
1237 use warnings::register;
1238
1239 sub new
1240 {
1241 my $class = shift;
1242 bless [], $class;
1243 }
1244
1245 sub check
1246 {
1247 my $self = shift;
1248 my $value = shift;
1249
1250 if ($value % 2 && warnings::enabled($self))
1251 { warnings::warn($self, "Odd numbers are unsafe") }
1252 }
1253
1254 sub doit
1255 {
1256 my $self = shift;
1257 my $value = shift;
1258 $self->check($value);
1259 # ...
1260 }
1261
1262 1;
1263
1264 package Derived;
1265
1266 use warnings::register;
1267 use Original;
1268 our @ISA = qw( Original );
1269 sub new
1270 {
1271 my $class = shift;
1272 bless [], $class;
1273 }
1274
1275
1276 1;
1277
1278The code below makes use of both modules, but it only enables warnings from
1279C<Derived>.
1280
1281 use Original;
1282 use Derived;
1283 use warnings 'Derived';
1284 my $a = Original->new();
1285 $a->doit(1);
1286 my $b = Derived->new();
1287 $a->doit(1);
1288
1289When this code is run only the C<Derived> object, C<$b>, will generate
1290a warning.
1291
1292 Odd numbers are unsafe at main.pl line 7
1293
1294Notice also that the warning is reported at the line where the object is first
1295used.
1296
1297When registering new categories of warning, you can supply more names to
1298warnings::register like this:
1299
1300 package MyModule;
1301 use warnings::register qw(format precision);
1302
1303 ...
1304
1305 warnings::warnif('MyModule::format', '...');
1306
1307=head1 FUNCTIONS
1308
1309=over 4
1310
1311=item use warnings::register
1312
1313Creates a new warnings category with the same name as the package where
1314the call to the pragma is used.
1315
1316=item warnings::enabled()
1317
1318Use the warnings category with the same name as the current package.
1319
1320Return TRUE if that warnings category is enabled in the calling module.
1321Otherwise returns FALSE.
1322
1323=item warnings::enabled($category)
1324
1325Return TRUE if the warnings category, C<$category>, is enabled in the
1326calling module.
1327Otherwise returns FALSE.
1328
1329=item warnings::enabled($object)
1330
1331Use the name of the class for the object reference, C<$object>, as the
1332warnings category.
1333
1334Return TRUE if that warnings category is enabled in the first scope
1335where the object is used.
1336Otherwise returns FALSE.
1337
1338=item warnings::fatal_enabled()
1339
1340Return TRUE if the warnings category with the same name as the current
1341package has been set to FATAL in the calling module.
1342Otherwise returns FALSE.
1343
1344=item warnings::fatal_enabled($category)
1345
1346Return TRUE if the warnings category C<$category> has been set to FATAL in
1347the calling module.
1348Otherwise returns FALSE.
1349
1350=item warnings::fatal_enabled($object)
1351
1352Use the name of the class for the object reference, C<$object>, as the
1353warnings category.
1354
1355Return TRUE if that warnings category has been set to FATAL in the first
1356scope where the object is used.
1357Otherwise returns FALSE.
1358
1359=item warnings::warn($message)
1360
1361Print C<$message> to STDERR.
1362
1363Use the warnings category with the same name as the current package.
1364
1365If that warnings category has been set to "FATAL" in the calling module
1366then die. Otherwise return.
1367
1368=item warnings::warn($category, $message)
1369
1370Print C<$message> to STDERR.
1371
1372If the warnings category, C<$category>, has been set to "FATAL" in the
1373calling module then die. Otherwise return.
1374
1375=item warnings::warn($object, $message)
1376
1377Print C<$message> to STDERR.
1378
1379Use the name of the class for the object reference, C<$object>, as the
1380warnings category.
1381
1382If that warnings category has been set to "FATAL" in the scope where C<$object>
1383is first used then die. Otherwise return.
1384
1385
1386=item warnings::warnif($message)
1387
1388Equivalent to:
1389
1390 if (warnings::enabled())
1391 { warnings::warn($message) }
1392
1393=item warnings::warnif($category, $message)
1394
1395Equivalent to:
1396
1397 if (warnings::enabled($category))
1398 { warnings::warn($category, $message) }
1399
1400=item warnings::warnif($object, $message)
1401
1402Equivalent to:
1403
1404 if (warnings::enabled($object))
1405 { warnings::warn($object, $message) }
1406
1407=item warnings::register_categories(@names)
1408
1409This registers warning categories for the given names and is primarily for
1410use by the warnings::register pragma.
1411
1412=back
1413
1414See also L<perlmodlib/Pragmatic Modules> and L<perldiag>.
1415
1416=cut