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