xref: /openbsd-src/gnu/usr.bin/perl/regen/feature.pl (revision 3d61058aa5c692477b6d18acfbbdb653a9930ff9)
1#!/usr/bin/perl
2#
3# Regenerate (overwriting only if changed):
4#
5#    lib/feature.pm
6#    feature.h
7#
8# from information hardcoded into this script and from two #defines
9# in perl.h.
10#
11# This script is normally invoked from regen.pl.
12
13BEGIN {
14    push @INC, './lib';
15    require './regen/regen_lib.pl';
16    require './regen/HeaderParser.pm';
17}
18
19use strict;
20use warnings;
21
22###########################################################################
23# Hand-editable data
24
25# (feature name) => (internal name, used in %^H and macro names)
26my %feature = (
27    say                     => 'say',
28    state                   => 'state',
29    switch                  => 'switch',
30    bitwise                 => 'bitwise',
31    evalbytes               => 'evalbytes',
32    current_sub             => '__SUB__',
33    refaliasing             => 'refaliasing',
34    postderef_qq            => 'postderef_qq',
35    unicode_eval            => 'unieval',
36    declared_refs           => 'myref',
37    unicode_strings         => 'unicode',
38    fc                      => 'fc',
39    signatures              => 'signatures',
40    isa                     => 'isa',
41    indirect                => 'indirect',
42    multidimensional        => 'multidimensional',
43    bareword_filehandles    => 'bareword_filehandles',
44    try                     => 'try',
45    defer                   => 'defer',
46    extra_paired_delimiters => 'more_delims',
47    module_true             => 'module_true',
48    class                   => 'class',
49);
50
51# NOTE: If a feature is ever enabled in a non-contiguous range of Perl
52#       versions, any code below that uses %BundleRanges will have to
53#       be changed to account.
54
55# 5.odd implies the next 5.even, but an explicit 5.even can override it.
56
57# features bundles
58use constant V5_9_5 => sort qw{say state switch indirect multidimensional bareword_filehandles};
59use constant V5_11  => sort ( +V5_9_5, qw{unicode_strings} );
60use constant V5_15  => sort ( +V5_11, qw{unicode_eval evalbytes current_sub fc} );
61use constant V5_23  => sort ( +V5_15, qw{postderef_qq} );
62use constant V5_27  => sort ( +V5_23, qw{bitwise} );
63
64use constant V5_35  => sort grep {; $_ ne 'switch'
65                                 && $_ ne 'indirect'
66                                 && $_ ne 'multidimensional' } +V5_27, qw{isa signatures};
67
68use constant V5_37  => sort grep {; $_ ne 'bareword_filehandles' } +V5_35, qw{module_true};
69
70use constant V5_39  => sort ( +V5_37, qw{try} );
71
72#
73# when updating features please also update the Pod entry for L</"FEATURES CHEAT SHEET">
74#
75my %feature_bundle = (
76    all     => [ sort keys %feature ],
77    default => [ qw{indirect multidimensional bareword_filehandles} ],
78    # using 5.9.5 features bundle
79    "5.9.5" => [ +V5_9_5 ],
80    "5.10"  => [ +V5_9_5 ],
81    # using 5.11 features bundle
82    "5.11"  => [ +V5_11 ],
83    "5.13"  => [ +V5_11 ],
84    # using 5.15 features bundle
85    "5.15"  => [ +V5_15 ],
86    "5.17"  => [ +V5_15 ],
87    "5.19"  => [ +V5_15 ],
88    "5.21"  => [ +V5_15 ],
89    # using 5.23 features bundle
90    "5.23"  => [ +V5_23 ],
91    "5.25"  => [ +V5_23 ],
92    # using 5.27 features bundle
93    "5.27"  => [ +V5_27 ],
94    "5.29"  => [ +V5_27 ],
95    "5.31"  => [ +V5_27 ],
96    "5.33"  => [ +V5_27 ],
97    # using 5.35 features bundle
98    "5.35"  => [ +V5_35 ],
99    # using 5.37 features bundle
100    "5.37"  => [ +V5_37 ],
101    # using 5.39 features bundle
102    "5.39"  => [ +V5_39 ],
103);
104
105my @noops = qw( postderef lexical_subs );
106my @removed = qw( array_base );
107
108
109###########################################################################
110# More data generated from the above
111
112if (keys %feature > 32) {
113    die "cop_features only has room for 32 features";
114}
115
116my %feature_bits;
117my $mask = 1;
118for my $feature (sort keys %feature) {
119    $feature_bits{$feature} = $mask;
120    $mask <<= 1;
121}
122
123for (keys %feature_bundle) {
124    next unless /^5\.(\d*[13579])\z/;
125    $feature_bundle{"5.".($1+1)} ||= $feature_bundle{$_};
126}
127
128my %UniqueBundles; # "say state switch" => 5.10
129my %Aliases;       #  5.12 => 5.11
130for( sort keys %feature_bundle ) {
131    my $value = join(' ', sort @{$feature_bundle{$_}});
132    if (exists $UniqueBundles{$value}) {
133	$Aliases{$_} = $UniqueBundles{$value};
134    }
135    else {
136	$UniqueBundles{$value} = $_;
137    }
138}
139			   # start   end
140my %BundleRanges; # say => ['5.10', '5.15'] # unique bundles for values
141for my $bund (
142    sort { $a eq 'default' ? -1 : $b eq 'default' ? 1 : $a cmp $b }
143         values %UniqueBundles
144) {
145    next if $bund =~ /[^\d.]/ and $bund ne 'default';
146    for (@{$feature_bundle{$bund}}) {
147	if (@{$BundleRanges{$_} ||= []} == 2) {
148	    $BundleRanges{$_}[1] = $bund
149	}
150	else {
151	    push @{$BundleRanges{$_}}, $bund;
152	}
153    }
154}
155
156my $HintShift;
157my $HintMask;
158my $Uni8Bit;
159my $hp = HeaderParser->new()->read_file("perl.h");
160
161foreach my $line_data (@{$hp->lines}) {
162    next unless $line_data->{type} eq "content"
163            and $line_data->{sub_type} eq "#define";
164    my $line = $line_data->{line};
165    next unless $line=~/^\s*#\s*define\s+(HINT_FEATURE_MASK|HINT_UNI_8_BIT)/;
166    my $is_u8b = $1 =~ 8;
167    $line=~/(0x[A-Fa-f0-9]+)/ or die "No hex number in:\n\n$line\n ";
168    if ($is_u8b) {
169	$Uni8Bit = $1;
170    }
171    else {
172	my $hex = $HintMask = $1;
173	my $bits = sprintf "%b", oct $1;
174	$bits =~ /^0*1+(0*)\z/
175         or die "Non-contiguous bits in $bits (binary for $hex):\n\n$line\n ";
176	$HintShift = length $1;
177	my $bits_needed =
178	    length sprintf "%b", scalar keys %UniqueBundles;
179	$bits =~ /1{$bits_needed}/
180	    or die "Not enough bits (need $bits_needed)"
181                 . " in $bits (binary for $hex):\n\n$line\n ";
182    }
183    if ($Uni8Bit && $HintMask) { last }
184}
185die "No HINT_FEATURE_MASK defined in perl.h" unless $HintMask;
186die "No HINT_UNI_8_BIT defined in perl.h"    unless $Uni8Bit;
187
188my @HintedBundles =
189    ('default', grep !/[^\d.]/, sort values %UniqueBundles);
190
191
192###########################################################################
193# Open files to be generated
194
195my ($pm, $h) = map {
196    open_new($_, '>', { by => 'regen/feature.pl' });
197} 'lib/feature.pm', 'feature.h';
198
199
200###########################################################################
201# Generate lib/feature.pm
202
203while (<DATA>) {
204    last if /^FEATURES$/ ;
205    print $pm $_ ;
206}
207
208sub longest {
209    my $long;
210    for(@_) {
211	if (!defined $long or length $long < length) {
212	    $long = $_;
213	}
214    }
215    $long;
216}
217
218print $pm "our %feature = (\n";
219my $width = length longest keys %feature;
220for(sort { length $a <=> length $b || $a cmp $b } keys %feature) {
221    print $pm "    $_" . " "x($width-length)
222	    . " => 'feature_$feature{$_}',\n";
223}
224print $pm ");\n\n";
225
226print $pm "our %feature_bundle = (\n";
227my $bund_width = length longest values %UniqueBundles;
228for( sort { $UniqueBundles{$a} cmp $UniqueBundles{$b} }
229          keys %UniqueBundles ) {
230    my $bund = $UniqueBundles{$_};
231    print $pm qq'    "$bund"' . " "x($bund_width-length $bund)
232	    . qq' => [qw($_)],\n';
233}
234print $pm ");\n\n";
235
236for (sort keys %Aliases) {
237    print $pm
238	qq'\$feature_bundle{"$_"} = \$feature_bundle{"$Aliases{$_}"};\n';
239};
240
241print $pm "my \%noops = (\n";
242print $pm "    $_ => 1,\n", for @noops;
243print $pm ");\n";
244
245print $pm "my \%removed = (\n";
246print $pm "    $_ => 1,\n", for @removed;
247print $pm ");\n";
248
249print $pm <<EOPM;
250
251our \$hint_shift   = $HintShift;
252our \$hint_mask    = $HintMask;
253our \@hint_bundles = qw( @HintedBundles );
254
255# This gets set (for now) in \$^H as well as in %^H,
256# for runtime speed of the uc/lc/ucfirst/lcfirst functions.
257# See HINT_UNI_8_BIT in perl.h.
258our \$hint_uni8bit = $Uni8Bit;
259EOPM
260
261
262while (<DATA>) {
263    last if /^PODTURES$/ ;
264    print $pm $_ ;
265}
266
267select +(select($pm), $~ = 'PODTURES')[0];
268format PODTURES =
269  ^<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
270$::bundle, $::feature
271.
272
273for ('default', sort grep /\.\d[02468]/, keys %feature_bundle) {
274    $::bundle = ":$_";
275    $::feature = join ' ', @{$feature_bundle{$_}};
276    write $pm;
277    print $pm "\n";
278}
279
280while (<DATA>) {
281    print $pm $_ ;
282}
283
284read_only_bottom_close_and_rename($pm);
285
286
287###########################################################################
288# Generate feature.h
289
290print $h <<EOH;
291
292#ifndef PERL_FEATURE_H_
293#define PERL_FEATURE_H_
294
295#if defined(PERL_CORE) || defined (PERL_EXT)
296
297#define HINT_FEATURE_SHIFT	$HintShift
298
299EOH
300
301for (sort keys %feature_bits) {
302    printf $h "#define FEATURE_%s_BIT%*s %#06x\n", uc($feature{$_}),
303      $width-length($feature{$_}), "", $feature_bits{$_};
304}
305print $h "\n";
306
307my $count;
308for (@HintedBundles) {
309    (my $key = uc) =~ y/.//d;
310    print $h "#define FEATURE_BUNDLE_$key	", $count++, "\n";
311}
312
313print $h <<'EOH';
314#define FEATURE_BUNDLE_CUSTOM	(HINT_FEATURE_MASK >> HINT_FEATURE_SHIFT)
315
316/* this is preserved for testing and asserts */
317#define OLD_CURRENT_HINTS \
318    (PL_curcop == &PL_compiling ? PL_hints : PL_curcop->cop_hints)
319/* this is the same thing, but simpler (no if) as PL_hints expands
320   to PL_compiling.cop_hints */
321#define CURRENT_HINTS \
322    PL_curcop->cop_hints
323#define CURRENT_FEATURE_BUNDLE \
324    ((CURRENT_HINTS & HINT_FEATURE_MASK) >> HINT_FEATURE_SHIFT)
325
326#define FEATURE_IS_ENABLED_MASK(mask)                   \
327  ((CURRENT_HINTS & HINT_LOCALIZE_HH)                \
328    ? (PL_curcop->cop_features & (mask)) : FALSE)
329
330/* The longest string we pass in.  */
331EOH
332
333my $longest_internal_feature_name = longest values %feature;
334print $h <<EOL;
335#define MAX_FEATURE_LEN (sizeof("$longest_internal_feature_name")-1)
336
337EOL
338
339for (
340    sort { length $a <=> length $b || $a cmp $b } keys %feature
341) {
342    my($first,$last) =
343	map { (my $__ = uc) =~ y/.//d; $__ } @{$BundleRanges{$_}};
344    my $name = $feature{$_};
345    my $NAME = uc $name;
346    if ($last && $first eq 'DEFAULT') { #  '>= DEFAULT' warns
347	print $h <<EOI;
348#define FEATURE_${NAME}_IS_ENABLED \\
349    ( \\
350	CURRENT_FEATURE_BUNDLE <= FEATURE_BUNDLE_$last \\
351     || (CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM && \\
352	 FEATURE_IS_ENABLED_MASK(FEATURE_${NAME}_BIT)) \\
353    )
354
355EOI
356    }
357    elsif ($last) {
358	print $h <<EOH3;
359#define FEATURE_${NAME}_IS_ENABLED \\
360    ( \\
361	(CURRENT_FEATURE_BUNDLE >= FEATURE_BUNDLE_$first && \\
362	 CURRENT_FEATURE_BUNDLE <= FEATURE_BUNDLE_$last) \\
363     || (CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM && \\
364	 FEATURE_IS_ENABLED_MASK(FEATURE_${NAME}_BIT)) \\
365    )
366
367EOH3
368    }
369    elsif ($first) {
370	print $h <<EOH4;
371#define FEATURE_${NAME}_IS_ENABLED \\
372    ( \\
373	CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_$first \\
374     || (CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM && \\
375	 FEATURE_IS_ENABLED_MASK(FEATURE_${NAME}_BIT)) \\
376    )
377
378EOH4
379    }
380    else {
381	print $h <<EOH5;
382#define FEATURE_${NAME}_IS_ENABLED \\
383    ( \\
384	CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM && \\
385	 FEATURE_IS_ENABLED_MASK(FEATURE_${NAME}_BIT) \\
386    )
387
388EOH5
389    }
390}
391
392print $h <<EOH;
393
394#define SAVEFEATUREBITS() SAVEI32(PL_compiling.cop_features)
395
396#define CLEARFEATUREBITS() (PL_compiling.cop_features = 0)
397
398#define FETCHFEATUREBITSHH(hh) S_fetch_feature_bits_hh(aTHX_ (hh))
399
400#endif /* PERL_CORE or PERL_EXT */
401
402#ifdef PERL_IN_OP_C
403PERL_STATIC_INLINE void
404S_enable_feature_bundle(pTHX_ SV *ver)
405{
406    SV *comp_ver = sv_newmortal();
407    PL_hints = (PL_hints &~ HINT_FEATURE_MASK)
408	     | (
409EOH
410
411for (reverse @HintedBundles[1..$#HintedBundles]) { # skip default
412    my $numver = $_;
413    if ($numver eq '5.10') { $numver = '5.009005' } # special case
414    else		   { $numver =~ s/\./.0/  } # 5.11 => 5.011
415    (my $macrover = $_) =~ y/.//d;
416    print $h <<"    EOK";
417		  (sv_setnv(comp_ver, $numver),
418		   vcmp(ver, upg_version(comp_ver, FALSE)) >= 0)
419			? FEATURE_BUNDLE_$macrover :
420    EOK
421}
422
423print $h <<EOJ;
424			  FEATURE_BUNDLE_DEFAULT
425	       ) << HINT_FEATURE_SHIFT;
426    /* special case */
427    assert(PL_curcop == &PL_compiling);
428    if (FEATURE_UNICODE_IS_ENABLED) PL_hints |=  HINT_UNI_8_BIT;
429    else			    PL_hints &= ~HINT_UNI_8_BIT;
430}
431#endif /* PERL_IN_OP_C */
432
433#if defined(PERL_IN_MG_C) || defined(PERL_IN_PP_CTL_C)
434
435#define magic_sethint_feature(keysv, keypv, keylen, valsv, valbool) \\
436    S_magic_sethint_feature(aTHX_ (keysv), (keypv), (keylen), (valsv), (valbool))
437PERL_STATIC_INLINE void
438S_magic_sethint_feature(pTHX_ SV *keysv, const char *keypv, STRLEN keylen,
439                        SV *valsv, bool valbool) {
440    if (keysv)
441      keypv = SvPV_const(keysv, keylen);
442
443    if (memBEGINs(keypv, keylen, "feature_")) {
444        const char *subf = keypv + (sizeof("feature_")-1);
445        U32 mask = 0;
446        switch (*subf) {
447EOJ
448
449my %pref;
450for my $key (sort values %feature) {
451    push @{$pref{substr($key, 0, 1)}}, $key;
452}
453
454for my $pref (sort keys %pref) {
455    print $h <<EOS;
456        case '$pref':
457EOS
458    my $first = 1;
459    for my $subkey (@{$pref{$pref}}) {
460        my $rest = substr($subkey, 1);
461        my $if = $first ? "if" : "else if";
462        print $h <<EOJ;
463            $if (keylen == sizeof("feature_$subkey")-1
464                 && memcmp(subf+1, "$rest", keylen - sizeof("feature_")) == 0) {
465                mask = FEATURE_\U${subkey}\E_BIT;
466                break;
467            }
468EOJ
469
470        $first = 0;
471    }
472    print $h <<EOS;
473            return;
474
475EOS
476}
477
478print $h <<EOJ;
479        default:
480            return;
481        }
482        if (valsv ? SvTRUE(valsv) : valbool)
483            PL_compiling.cop_features |= mask;
484        else
485            PL_compiling.cop_features &= ~mask;
486    }
487}
488#endif /* PERL_IN_MG_C */
489
490/* subject to change */
491struct perl_feature_bit {
492  const char *name;
493  STRLEN namelen;
494  U32 mask;
495};
496
497#ifdef PERL_IN_PP_CTL_C
498
499static const struct perl_feature_bit
500PL_feature_bits[] = {
501EOJ
502for my $key (sort keys %feature) {
503    my $val = $feature{$key};
504    print $h <<EOJ;
505    {
506        /* feature $key */
507        "feature_$val",
508        STRLENs("feature_$val"),
509        FEATURE_\U$val\E_BIT
510    },
511EOJ
512}
513
514print $h <<EOJ;
515    { NULL, 0, 0U }
516};
517
518PERL_STATIC_INLINE void
519S_fetch_feature_bits_hh(pTHX_ HV *hh) {
520    PL_compiling.cop_features = 0;
521
522    const struct perl_feature_bit *fb = PL_feature_bits;
523    while (fb->name) {
524        SV **svp = hv_fetch(hh, fb->name, (I32)fb->namelen, 0);
525        if (svp && SvTRUE(*svp))
526               PL_compiling.cop_features |= fb->mask;
527        ++fb;
528    }
529}
530
531#endif
532
533#endif /* PERL_FEATURE_H_ */
534EOJ
535
536read_only_bottom_close_and_rename($h);
537
538
539###########################################################################
540# Template for feature.pm
541
542__END__
543package feature;
544our $VERSION = '1.89';
545
546FEATURES
547
548# TODO:
549# - think about versioned features (use feature switch => 2)
550
551=encoding utf8
552
553=head1 NAME
554
555feature - Perl pragma to enable new features
556
557=head1 SYNOPSIS
558
559    use feature qw(fc say);
560
561    # Without the "use feature" above, this code would not be able to find
562    # the built-ins "say" or "fc":
563    say "The case-folded version of $x is: " . fc $x;
564
565
566    # set features to match the :5.36 bundle, which may turn off or on
567    # multiple features (see "FEATURE BUNDLES" below)
568    use feature ':5.36';
569
570
571    # implicitly loads :5.36 feature bundle
572    use v5.36;
573
574=head1 DESCRIPTION
575
576It is usually impossible to add new syntax to Perl without breaking
577some existing programs.  This pragma provides a way to minimize that
578risk. New syntactic constructs, or new semantic meanings to older
579constructs, can be enabled by C<use feature 'foo'>, and will be parsed
580only when the appropriate feature pragma is in scope.  (Nevertheless, the
581C<CORE::> prefix provides access to all Perl keywords, regardless of this
582pragma.)
583
584=head2 Lexical effect
585
586Like other pragmas (C<use strict>, for example), features have a lexical
587effect.  C<use feature qw(foo)> will only make the feature "foo" available
588from that point to the end of the enclosing block.
589
590    {
591        use feature 'say';
592        say "say is available here";
593    }
594    print "But not here.\n";
595
596=head2 C<no feature>
597
598Features can also be turned off by using C<no feature "foo">.  This too
599has lexical effect.
600
601    use feature 'say';
602    say "say is available here";
603    {
604        no feature 'say';
605        print "But not here.\n";
606    }
607    say "Yet it is here.";
608
609C<no feature> with no features specified will reset to the default group.  To
610disable I<all> features (an unusual request!) use C<no feature ':all'>.
611
612=head1 AVAILABLE FEATURES
613
614Read L</"FEATURE BUNDLES"> for the feature cheat sheet summary.
615
616=head2 The 'say' feature
617
618C<use feature 'say'> tells the compiler to enable the Raku-inspired
619C<say> function.
620
621See L<perlfunc/say> for details.
622
623This feature is available starting with Perl 5.10.
624
625=head2 The 'state' feature
626
627C<use feature 'state'> tells the compiler to enable C<state>
628variables.
629
630See L<perlsub/"Persistent Private Variables"> for details.
631
632This feature is available starting with Perl 5.10.
633
634=head2 The 'switch' feature
635
636B<WARNING>: This feature is still experimental and the implementation may
637change or be removed in future versions of Perl.  For this reason, Perl will
638warn when you use the feature, unless you have explicitly disabled the warning:
639
640    no warnings "experimental::smartmatch";
641
642C<use feature 'switch'> tells the compiler to enable the Raku
643given/when construct.
644
645See L<perlsyn/"Switch Statements"> for details.
646
647This feature is available starting with Perl 5.10.
648It is deprecated starting with Perl 5.38, and using
649C<given>, C<when> or smartmatch will throw a warning.
650It will be removed in Perl 5.42.
651
652=head2 The 'unicode_strings' feature
653
654C<use feature 'unicode_strings'> tells the compiler to use Unicode rules
655in all string operations executed within its scope (unless they are also
656within the scope of either C<use locale> or C<use bytes>).  The same applies
657to all regular expressions compiled within the scope, even if executed outside
658it.  It does not change the internal representation of strings, but only how
659they are interpreted.
660
661C<no feature 'unicode_strings'> tells the compiler to use the traditional
662Perl rules wherein the native character set rules is used unless it is
663clear to Perl that Unicode is desired.  This can lead to some surprises
664when the behavior suddenly changes.  (See
665L<perlunicode/The "Unicode Bug"> for details.)  For this reason, if you are
666potentially using Unicode in your program, the
667C<use feature 'unicode_strings'> subpragma is B<strongly> recommended.
668
669This feature is available starting with Perl 5.12; was almost fully
670implemented in Perl 5.14; and extended in Perl 5.16 to cover C<quotemeta>;
671was extended further in Perl 5.26 to cover L<the range
672operator|perlop/Range Operators>; and was extended again in Perl 5.28 to
673cover L<special-cased whitespace splitting|perlfunc/split>.
674
675=head2 The 'unicode_eval' and 'evalbytes' features
676
677Together, these two features are intended to replace the legacy string
678C<eval> function, which behaves problematically in some instances.  They are
679available starting with Perl 5.16, and are enabled by default by a
680S<C<use 5.16>> or higher declaration.
681
682C<unicode_eval> changes the behavior of plain string C<eval> to work more
683consistently, especially in the Unicode world.  Certain (mis)behaviors
684couldn't be changed without breaking some things that had come to rely on
685them, so the feature can be enabled and disabled.  Details are at
686L<perlfunc/Under the "unicode_eval" feature>.
687
688C<evalbytes> is like string C<eval>, but it treats its argument as a byte
689string. Details are at L<perlfunc/evalbytes EXPR>.  Without a
690S<C<use feature 'evalbytes'>> nor a S<C<use v5.16>> (or higher) declaration in
691the current scope, you can still access it by instead writing
692C<CORE::evalbytes>.
693
694=head2 The 'current_sub' feature
695
696This provides the C<__SUB__> token that returns a reference to the current
697subroutine or C<undef> outside of a subroutine.
698
699This feature is available starting with Perl 5.16.
700
701=head2 The 'array_base' feature
702
703This feature supported the legacy C<$[> variable.  See L<perlvar/$[>.
704It was on by default but disabled under C<use v5.16> (see
705L</IMPLICIT LOADING>, below) and unavailable since perl 5.30.
706
707This feature is available under this name starting with Perl 5.16.  In
708previous versions, it was simply on all the time, and this pragma knew
709nothing about it.
710
711=head2 The 'fc' feature
712
713C<use feature 'fc'> tells the compiler to enable the C<fc> function,
714which implements Unicode casefolding.
715
716See L<perlfunc/fc> for details.
717
718This feature is available from Perl 5.16 onwards.
719
720=head2 The 'lexical_subs' feature
721
722In Perl versions prior to 5.26, this feature enabled
723declaration of subroutines via C<my sub foo>, C<state sub foo>
724and C<our sub foo> syntax.  See L<perlsub/Lexical Subroutines> for details.
725
726This feature is available from Perl 5.18 onwards.  From Perl 5.18 to 5.24,
727it was classed as experimental, and Perl emitted a warning for its
728usage, except when explicitly disabled:
729
730  no warnings "experimental::lexical_subs";
731
732As of Perl 5.26, use of this feature no longer triggers a warning, though
733the C<experimental::lexical_subs> warning category still exists (for
734compatibility with code that disables it).  In addition, this syntax is
735not only no longer experimental, but it is enabled for all Perl code,
736regardless of what feature declarations are in scope.
737
738=head2 The 'postderef' and 'postderef_qq' features
739
740The 'postderef_qq' feature extends the applicability of L<postfix
741dereference syntax|perlref/Postfix Dereference Syntax> so that
742postfix array dereference, postfix scalar dereference, and
743postfix array highest index access are available in double-quotish interpolations.
744For example, it makes the following two statements equivalent:
745
746  my $s = "[@{ $h->{a} }]";
747  my $s = "[$h->{a}->@*]";
748
749This feature is available from Perl 5.20 onwards. In Perl 5.20 and 5.22, it
750was classed as experimental, and Perl emitted a warning for its
751usage, except when explicitly disabled:
752
753  no warnings "experimental::postderef";
754
755As of Perl 5.24, use of this feature no longer triggers a warning, though
756the C<experimental::postderef> warning category still exists (for
757compatibility with code that disables it).
758
759The 'postderef' feature was used in Perl 5.20 and Perl 5.22 to enable
760postfix dereference syntax outside double-quotish interpolations. In those
761versions, using it triggered the C<experimental::postderef> warning in the
762same way as the 'postderef_qq' feature did. As of Perl 5.24, this syntax is
763not only no longer experimental, but it is enabled for all Perl code,
764regardless of what feature declarations are in scope.
765
766=head2 The 'signatures' feature
767
768This enables syntax for declaring subroutine arguments as lexical variables.
769For example, for this subroutine:
770
771    sub foo ($left, $right) {
772        return $left + $right;
773    }
774
775Calling C<foo(3, 7)> will assign C<3> into C<$left> and C<7> into C<$right>.
776
777See L<perlsub/Signatures> for details.
778
779This feature is available from Perl 5.20 onwards. From Perl 5.20 to 5.34,
780it was classed as experimental, and Perl emitted a warning for its usage,
781except when explicitly disabled:
782
783  no warnings "experimental::signatures";
784
785As of Perl 5.36, use of this feature no longer triggers a warning, though the
786C<experimental::signatures> warning category still exists (for compatibility
787with code that disables it). This feature is now considered stable, and is
788enabled automatically by C<use v5.36> (or higher).
789
790=head2 The 'refaliasing' feature
791
792B<WARNING>: This feature is still experimental and the implementation may
793change or be removed in future versions of Perl.  For this reason, Perl will
794warn when you use the feature, unless you have explicitly disabled the warning:
795
796    no warnings "experimental::refaliasing";
797
798This enables aliasing via assignment to references:
799
800    \$a = \$b; # $a and $b now point to the same scalar
801    \@a = \@b; #                     to the same array
802    \%a = \%b;
803    \&a = \&b;
804    foreach \%hash (@array_of_hash_refs) {
805        ...
806    }
807
808See L<perlref/Assigning to References> for details.
809
810This feature is available from Perl 5.22 onwards.
811
812=head2 The 'bitwise' feature
813
814This makes the four standard bitwise operators (C<& | ^ ~>) treat their
815operands consistently as numbers, and introduces four new dotted operators
816(C<&. |. ^. ~.>) that treat their operands consistently as strings.  The
817same applies to the assignment variants (C<&= |= ^= &.= |.= ^.=>).
818
819See L<perlop/Bitwise String Operators> for details.
820
821This feature is available from Perl 5.22 onwards.  Starting in Perl 5.28,
822C<use v5.28> will enable the feature.  Before 5.28, it was still
823experimental and would emit a warning in the "experimental::bitwise"
824category.
825
826=head2 The 'declared_refs' feature
827
828B<WARNING>: This feature is still experimental and the implementation may
829change or be removed in future versions of Perl.  For this reason, Perl will
830warn when you use the feature, unless you have explicitly disabled the warning:
831
832    no warnings "experimental::declared_refs";
833
834This allows a reference to a variable to be declared with C<my>, C<state>,
835or C<our>, or localized with C<local>.  It is intended mainly for use in
836conjunction with the "refaliasing" feature.  See L<perlref/Declaring a
837Reference to a Variable> for examples.
838
839This feature is available from Perl 5.26 onwards.
840
841=head2 The 'isa' feature
842
843This allows the use of the C<isa> infix operator, which tests whether the
844scalar given by the left operand is an object of the class given by the
845right operand. See L<perlop/Class Instance Operator> for more details.
846
847This feature is available from Perl 5.32 onwards.  From Perl 5.32 to 5.34,
848it was classed as experimental, and Perl emitted a warning for its usage,
849except when explicitly disabled:
850
851    no warnings "experimental::isa";
852
853As of Perl 5.36, use of this feature no longer triggers a warning (though the
854C<experimental::isa> warning category still exists for compatibility with
855code that disables it). This feature is now considered stable, and is enabled
856automatically by C<use v5.36> (or higher).
857
858=head2 The 'indirect' feature
859
860This feature allows the use of L<indirect object
861syntax|perlobj/Indirect Object Syntax> for method calls, e.g.  C<new
862Foo 1, 2;>. It is enabled by default, but can be turned off to
863disallow indirect object syntax.
864
865This feature is available under this name from Perl 5.32 onwards. In
866previous versions, it was simply on all the time.  To disallow (or
867warn on) indirect object syntax on older Perls, see the L<indirect>
868CPAN module.
869
870=head2 The 'multidimensional' feature
871
872This feature enables multidimensional array emulation, a perl 4 (or
873earlier) feature that was used to emulate multidimensional arrays with
874hashes.  This works by converting code like C<< $foo{$x, $y} >> into
875C<< $foo{join($;, $x, $y)} >>.  It is enabled by default, but can be
876turned off to disable multidimensional array emulation.
877
878When this feature is disabled the syntax that is normally replaced
879will report a compilation error.
880
881This feature is available under this name from Perl 5.34 onwards. In
882previous versions, it was simply on all the time.
883
884You can use the L<multidimensional> module on CPAN to disable
885multidimensional array emulation for older versions of Perl.
886
887=head2 The 'bareword_filehandles' feature
888
889This feature enables bareword filehandles for builtin functions
890operations, a generally discouraged practice.  It is enabled by
891default, but can be turned off to disable bareword filehandles, except
892for the exceptions listed below.
893
894The perl built-in filehandles C<STDIN>, C<STDOUT>, C<STDERR>, C<DATA>,
895C<ARGV>, C<ARGVOUT> and the special C<_> are always enabled.
896
897This feature is available under this name from Perl 5.34 onwards.  In
898previous versions it was simply on all the time.
899
900You can use the L<bareword::filehandles> module on CPAN to disable
901bareword filehandles for older versions of perl.
902
903=head2 The 'try' feature
904
905B<WARNING>: This feature is still partly experimental, and the implementation
906may change or be removed in future versions of Perl.
907
908This feature enables the C<try> and C<catch> syntax, which allows exception
909handling, where exceptions thrown from the body of the block introduced with
910C<try> are caught by executing the body of the C<catch> block.
911
912This feature is available starting in Perl 5.34. Before Perl 5.40 it was
913classed as experimental, and Perl emitted a warning for its usage, except when
914explicitly disabled:
915
916    no warnings "experimental::try";
917
918As of Perl 5.40, use of this feature without a C<finally> block no longer
919triggers a warning.  The optional C<finally> block is still considered
920experimental and emits a warning, except when explicitly disabled as above.
921
922For more information, see L<perlsyn/"Try Catch Exception Handling">.
923
924=head2 The 'defer' feature
925
926B<WARNING>: This feature is still experimental and the implementation may
927change or be removed in future versions of Perl.  For this reason, Perl will
928warn when you use the feature, unless you have explicitly disabled the warning:
929
930    no warnings "experimental::defer";
931
932This feature enables the C<defer> block syntax, which allows a block of code
933to be deferred until when the flow of control leaves the block which contained
934it. For more details, see L<perlsyn/defer>.
935
936This feature is available starting in Perl 5.36.
937
938=head2 The 'extra_paired_delimiters' feature
939
940B<WARNING>: This feature is still experimental and the implementation may
941change or be removed in future versions of Perl.  For this reason, Perl will
942warn when you use the feature, unless you have explicitly disabled the warning:
943
944    no warnings "experimental::extra_paired_delimiters";
945
946This feature enables the use of more paired string delimiters than the
947traditional four, S<C<< <  > >>>, S<C<( )>>, S<C<{ }>>, and S<C<[ ]>>.  When
948this feature is on, for example, you can say S<C<qrE<171>patE<187>>>.
949
950As with any usage of non-ASCII delimiters in a UTF-8-encoded source file, you
951will want to ensure the parser will decode the source code from UTF-8 bytes
952with a declaration such as C<use utf8>.
953
954This feature is available starting in Perl 5.36.
955
956For a full list of the available characters, see
957L<perlop/List of Extra Paired Delimiters>.
958
959=head2 The 'module_true' feature
960
961This feature removes the need to return a true value at the end of a module
962loaded with C<require> or C<use>. Any errors during compilation will cause
963failures, but reaching the end of the module when this feature is in effect
964will prevent C<perl> from throwing an exception that the module "did not return
965a true value".
966
967=head2 The 'class' feature
968
969B<WARNING>: This feature is still experimental and the implementation may
970change or be removed in future versions of Perl.  For this reason, Perl will
971warn when you use the feature, unless you have explicitly disabled the warning:
972
973    no warnings "experimental::class";
974
975This feature enables the C<class> block syntax and other associated keywords
976which implement the "new" object system, previously codenamed "Corinna".
977
978=head1 FEATURE BUNDLES
979
980It's possible to load multiple features together, using
981a I<feature bundle>.  The name of a feature bundle is prefixed with
982a colon, to distinguish it from an actual feature.
983
984  use feature ":5.10";
985
986The following feature bundles are available:
987
988  bundle    features included
989  --------- -----------------
990PODTURES
991The C<:default> bundle represents the feature set that is enabled before
992any C<use feature> or C<no feature> declaration.
993
994Specifying sub-versions such as the C<0> in C<5.14.0> in feature bundles has
995no effect.  Feature bundles are guaranteed to be the same for all sub-versions.
996
997  use feature ":5.14.0";    # same as ":5.14"
998  use feature ":5.14.1";    # same as ":5.14"
999
1000You can also do:
1001
1002  use feature ":all";
1003
1004or
1005
1006  no feature ":all";
1007
1008but the first may enable features in a later version of Perl that
1009change the meaning of your code, and the second may disable mechanisms
1010that are part of Perl's current behavior that have been turned into
1011features, just as C<indirect> and C<bareword_filehandles> were.
1012
1013=head1 IMPLICIT LOADING
1014
1015Instead of loading feature bundles by name, it is easier to let Perl do
1016implicit loading of a feature bundle for you.
1017
1018There are two ways to load the C<feature> pragma implicitly:
1019
1020=over 4
1021
1022=item *
1023
1024By using the C<-E> switch on the Perl command-line instead of C<-e>.
1025That will enable the feature bundle for that version of Perl in the
1026main compilation unit (that is, the one-liner that follows C<-E>).
1027
1028=item *
1029
1030By explicitly requiring a minimum Perl version number for your program, with
1031the C<use VERSION> construct.  That is,
1032
1033    use v5.36.0;
1034
1035will do an implicit
1036
1037    no feature ':all';
1038    use feature ':5.36';
1039
1040and so on.  Note how the trailing sub-version
1041is automatically stripped from the
1042version.
1043
1044But to avoid portability warnings (see L<perlfunc/use>), you may prefer:
1045
1046    use 5.036;
1047
1048with the same effect.
1049
1050If the required version is older than Perl 5.10, the ":default" feature
1051bundle is automatically loaded instead.
1052
1053Unlike C<use feature ":5.12">, saying C<use v5.12> (or any higher version)
1054also does the equivalent of C<use strict>; see L<perlfunc/use> for details.
1055
1056=back
1057
1058=head1 CHECKING FEATURES
1059
1060C<feature> provides some simple APIs to check which features are enabled.
1061
1062These functions cannot be imported and must be called by their fully
1063qualified names.  If you don't otherwise need to set a feature you will
1064need to ensure C<feature> is loaded with:
1065
1066  use feature ();
1067
1068=over
1069
1070=item feature_enabled($feature)
1071
1072=item feature_enabled($feature, $depth)
1073
1074  package MyStandardEnforcer;
1075  use feature ();
1076  use Carp "croak";
1077  sub import {
1078    croak "disable indirect!" if feature::feature_enabled("indirect");
1079  }
1080
1081Test whether a named feature is enabled at a given level in the call
1082stack, returning a true value if it is.  C<$depth> defaults to 1,
1083which checks the scope that called the scope calling
1084feature::feature_enabled().
1085
1086croaks for an unknown feature name.
1087
1088=item features_enabled()
1089
1090=item features_enabled($depth)
1091
1092  package ReportEnabledFeatures;
1093  use feature "say";
1094  sub import {
1095    say STDERR join " ", feature::features_enabled();
1096  }
1097
1098Returns a list of the features enabled at a given level in the call
1099stack.  C<$depth> defaults to 1, which checks the scope that called
1100the scope calling feature::features_enabled().
1101
1102=item feature_bundle()
1103
1104=item feature_bundle($depth)
1105
1106Returns the feature bundle, if any, selected at a given level in the
1107call stack.  C<$depth> defaults to 1, which checks the scope that called
1108the scope calling feature::feature_bundle().
1109
1110Returns an undefined value if no feature bundle is selected in the
1111scope.
1112
1113The bundle name returned will be for the earliest bundle matching the
1114selected bundle, so:
1115
1116  use feature ();
1117  use v5.12;
1118  BEGIN { print feature::feature_bundle(0); }
1119
1120will print C<5.11>.
1121
1122This returns internal state, at this point C<use v5.12;> sets the
1123feature bundle, but C< use feature ":5.12"; > does not set the feature
1124bundle.  This may change in a future release of perl.
1125
1126=back
1127
1128=cut
1129
1130sub import {
1131    shift;
1132
1133    if (!@_) {
1134        croak("No features specified");
1135    }
1136
1137    __common(1, @_);
1138}
1139
1140sub unimport {
1141    shift;
1142
1143    # A bare C<no feature> should reset to the default bundle
1144    if (!@_) {
1145	$^H &= ~($hint_uni8bit|$hint_mask);
1146	return;
1147    }
1148
1149    __common(0, @_);
1150}
1151
1152
1153sub __common {
1154    my $import = shift;
1155    my $bundle_number = $^H & $hint_mask;
1156    my $features = $bundle_number != $hint_mask
1157      && $feature_bundle{$hint_bundles[$bundle_number >> $hint_shift]};
1158    if ($features) {
1159	# Features are enabled implicitly via bundle hints.
1160	# Delete any keys that may be left over from last time.
1161	delete @^H{ values(%feature) };
1162	$^H |= $hint_mask;
1163	for (@$features) {
1164	    $^H{$feature{$_}} = 1;
1165	    $^H |= $hint_uni8bit if $_ eq 'unicode_strings';
1166	}
1167    }
1168    while (@_) {
1169        my $name = shift;
1170        if (substr($name, 0, 1) eq ":") {
1171            my $v = substr($name, 1);
1172            if (!exists $feature_bundle{$v}) {
1173                $v =~ s/^([0-9]+)\.([0-9]+).[0-9]+$/$1.$2/;
1174                if (!exists $feature_bundle{$v}) {
1175                    unknown_feature_bundle(substr($name, 1));
1176                }
1177            }
1178            unshift @_, @{$feature_bundle{$v}};
1179            next;
1180        }
1181        if (!exists $feature{$name}) {
1182            if (exists $noops{$name}) {
1183                next;
1184            }
1185            if (!$import && exists $removed{$name}) {
1186                next;
1187            }
1188            unknown_feature($name);
1189        }
1190	if ($import) {
1191	    $^H{$feature{$name}} = 1;
1192	    $^H |= $hint_uni8bit if $name eq 'unicode_strings';
1193	} else {
1194            delete $^H{$feature{$name}};
1195            $^H &= ~ $hint_uni8bit if $name eq 'unicode_strings';
1196        }
1197    }
1198}
1199
1200sub unknown_feature {
1201    my $feature = shift;
1202    croak(sprintf('Feature "%s" is not supported by Perl %vd',
1203            $feature, $^V));
1204}
1205
1206sub unknown_feature_bundle {
1207    my $feature = shift;
1208    croak(sprintf('Feature bundle "%s" is not supported by Perl %vd',
1209            $feature, $^V));
1210}
1211
1212sub croak {
1213    require Carp;
1214    Carp::croak(@_);
1215}
1216
1217sub features_enabled {
1218    my ($depth) = @_;
1219
1220    $depth //= 1;
1221    my @frame = caller($depth+1)
1222      or return;
1223    my ($hints, $hinthash) = @frame[8, 10];
1224
1225    my $bundle_number = $hints & $hint_mask;
1226    if ($bundle_number != $hint_mask) {
1227        return $feature_bundle{$hint_bundles[$bundle_number >> $hint_shift]}->@*;
1228    }
1229    else {
1230        my @features;
1231        for my $feature (sort keys %feature) {
1232            if ($hinthash->{$feature{$feature}}) {
1233                push @features, $feature;
1234            }
1235        }
1236        return @features;
1237    }
1238}
1239
1240sub feature_enabled {
1241    my ($feature, $depth) = @_;
1242
1243    $depth //= 1;
1244    my @frame = caller($depth+1)
1245      or return;
1246    my ($hints, $hinthash) = @frame[8, 10];
1247
1248    my $hint_feature = $feature{$feature}
1249      or croak "Unknown feature $feature";
1250    my $bundle_number = $hints & $hint_mask;
1251    if ($bundle_number != $hint_mask) {
1252        my $bundle = $hint_bundles[$bundle_number >> $hint_shift];
1253        for my $bundle_feature ($feature_bundle{$bundle}->@*) {
1254            return 1 if $bundle_feature eq $feature;
1255        }
1256        return 0;
1257    }
1258    else {
1259        return $hinthash->{$hint_feature} // 0;
1260    }
1261}
1262
1263sub feature_bundle {
1264    my $depth = shift;
1265
1266    $depth //= 1;
1267    my @frame = caller($depth+1)
1268      or return;
1269    my $bundle_number = $frame[8] & $hint_mask;
1270    if ($bundle_number != $hint_mask) {
1271        return $hint_bundles[$bundle_number >> $hint_shift];
1272    }
1273    else {
1274        return undef;
1275    }
1276}
1277
12781;
1279