| 1 | package Sub::Abstract; | ||
| 2 | |||
| 3 | # Minimum Perl version: 5.8 (Attribute::Handlers became core in 5.8) | ||
| 4 | use 5.008; | ||
| 5 | use strict; | ||
| 6 | use warnings; | ||
| 7 | use autodie qw(:all); | ||
| 8 | |||
| 9 | use Attribute::Handlers; | ||
| 10 | use Carp qw(croak); | ||
| 11 | use Readonly; | ||
| 12 | use Params::Validate::Strict 0.33 qw(validate_strict); | ||
| 13 | use Return::Set qw(set_return); | ||
| 14 | |||
| 15 | =head1 NAME | ||
| 16 | |||
| 17 | Sub::Abstract - Abstract (virtual) methods for plain-Perl OO | ||
| 18 | |||
| 19 | =head1 VERSION | ||
| 20 | |||
| 21 | Version 0.01 | ||
| 22 | |||
| 23 | =cut | ||
| 24 | |||
| 25 | our $VERSION = '0.01'; | ||
| 26 | |||
| 27 | # --------------------------------------------------------------------------- | ||
| 28 | # Constants | ||
| 29 | # --------------------------------------------------------------------------- | ||
| 30 | |||
| 31 | # Self-referential constant: the canonical name of this package. | ||
| 32 | Readonly::Scalar my $SELF => __PACKAGE__; | ||
| 33 | |||
| 34 | # Validation schema for a single Perl sub name passed to import(). | ||
| 35 | Readonly::Scalar my $SUB_NAME_SCHEMA => { | ||
| 36 | name => { | ||
| 37 | type => 'string', | ||
| 38 | regex => qr/\A[_a-zA-Z]\w*\z/, | ||
| 39 | } | ||
| 40 | }; | ||
| 41 | |||
| 42 | # --------------------------------------------------------------------------- | ||
| 43 | # Public variables | ||
| 44 | # --------------------------------------------------------------------------- | ||
| 45 | |||
| 46 | our $BYPASS = 0; | ||
| 47 | |||
| 48 | our %config = ( | ||
| 49 | harness_bypass => 1, | ||
| 50 | ); | ||
| 51 | |||
| 52 | # --------------------------------------------------------------------------- | ||
| 53 | # Internal state | ||
| 54 | # --------------------------------------------------------------------------- | ||
| 55 | |||
| 56 | # Pending (owner_pkg, sub_name) pairs to be wrapped at CHECK time. | ||
| 57 | # Populated by import(); consumed and cleared by the CHECK block. | ||
| 58 | my @_pending; | ||
| 59 | |||
| 60 | # Set to 1 once the CHECK block fires so import() can wrap immediately. | ||
| 61 | my $_post_check = 0; | ||
| 62 | |||
| 63 | # ------------------------------------------------------------------- | ||
| 64 | # ATTRIBUTE HANDLER | ||
| 65 | # ------------------------------------------------------------------- | ||
| 66 | |||
| 67 | # Install :Abstract in UNIVERSAL so every package can use it after a | ||
| 68 | # single "use Sub::Abstract", with no per-package setup required. | ||
| 69 | # ATTR(CODE,CHECK) fires at CHECK time, after all subs are compiled. | ||
| 70 | # The stub body on the decorated sub is required so that Attribute::Handlers | ||
| 71 | # has a CODE ref to work with; the handler replaces it unconditionally. | ||
| 72 | sub UNIVERSAL::Abstract :ATTR(CODE,CHECK) { | ||
| 73 | my ($package, $symbol, $referent, $attr, $data, $phase) = @_; | ||
| 74 | my $sub_name = *{$symbol}{NAME}; | ||
| 75 | no warnings 'redefine'; | ||
| 76 | *{$symbol} = _wrap($package, $sub_name); | ||
| 77 | return; | ||
| 78 | } | ||
| 79 | |||
| 80 | # ------------------------------------------------------------------- | ||
| 81 | # PUBLIC INTERFACE | ||
| 82 | # ------------------------------------------------------------------- | ||
| 83 | |||
| 84 | =head1 SYNOPSIS | ||
| 85 | |||
| 86 | package Animal; | ||
| 87 | use Sub::Abstract; | ||
| 88 | |||
| 89 | # Attribute form (stub body required for Attribute::Handlers) | ||
| 90 | sub speak :Abstract { } | ||
| 91 | sub eat :Abstract { } | ||
| 92 | |||
| 93 | # Declarative form (no stub body needed) | ||
| 94 | use Sub::Abstract qw(speak eat); | ||
| 95 | |||
| 96 | package Dog; | ||
| 97 | our @ISA = ('Animal'); | ||
| 98 | sub speak { 'Woof' } # satisfies the contract; wrapper never fires | ||
| 99 | # forgot eat -- runtime croak when called | ||
| 100 | |||
| 101 | =head1 DESCRIPTION | ||
| 102 | |||
| 103 | Enforces abstract (virtual) method contracts for plain-Perl OO without | ||
| 104 | requiring Moose or Moo. A subroutine decorated with C<:Abstract> (or | ||
| 105 | named in C<use Sub::Abstract qw(...)>) is replaced at C<CHECK> time with | ||
| 106 | a wrapper that C<Carp::croak>s whenever it is reached. | ||
| 107 | |||
| 108 | Perl's MRO ensures the wrapper is only reached when no subclass in the | ||
| 109 | call chain has provided an implementation: if C<Dog::speak> exists, the | ||
| 110 | wrapper installed in C<Animal::speak> is never called. | ||
| 111 | |||
| 112 | This module is only meaningful for plain-Perl OO or packages that do not | ||
| 113 | use a full object framework. Moo and Moose handle abstract/required | ||
| 114 | methods in their own object systems. | ||
| 115 | |||
| 116 | =head2 Two usage forms | ||
| 117 | |||
| 118 | =over 4 | ||
| 119 | |||
| 120 | =item Attribute form (preferred) | ||
| 121 | |||
| 122 | sub speak :Abstract { } | ||
| 123 | |||
| 124 | The C<:Abstract> attribute is registered in C<UNIVERSAL> via | ||
| 125 | L<Attribute::Handlers> when C<Sub::Abstract> is loaded, so every package | ||
| 126 | has access to it without further C<use> or inheritance. A stub body | ||
| 127 | (even an empty one) is required because C<Attribute::Handlers> needs a | ||
| 128 | C<CODE> ref. The stub is replaced at C<CHECK> time. | ||
| 129 | |||
| 130 | =item Declarative form | ||
| 131 | |||
| 132 | use Sub::Abstract qw(speak eat); | ||
| 133 | |||
| 134 | Each named method is installed as an abstract-croak wrapper at C<CHECK> | ||
| 135 | time (or immediately if the module is loaded past C<CHECK>). No stub body | ||
| 136 | is needed. | ||
| 137 | |||
| 138 | =back | ||
| 139 | |||
| 140 | =head2 Bypass for testing | ||
| 141 | |||
| 142 | Either condition alone (OR logic) suppresses the croak: | ||
| 143 | |||
| 144 | =over 4 | ||
| 145 | |||
| 146 | =item * C<$Sub::Abstract::BYPASS> set to a true value. Use C<local> in tests. | ||
| 147 | |||
| 148 | =item * C<$ENV{HARNESS_ACTIVE}> set (the convention used by L<Test::Harness>/prove). | ||
| 149 | |||
| 150 | =back | ||
| 151 | |||
| 152 | The C<HARNESS_ACTIVE> bypass can be disabled: | ||
| 153 | |||
| 154 | $Sub::Abstract::config{harness_bypass} = 0; | ||
| 155 | |||
| 156 | =head2 Error message format | ||
| 157 | |||
| 158 | speak() is an abstract method of Animal and must be implemented by Dog | ||
| 159 | |||
| 160 | =head1 PUBLIC INTERFACE | ||
| 161 | |||
| 162 | =head2 import | ||
| 163 | |||
| 164 | use Sub::Abstract; # attribute form -- no arguments | ||
| 165 | use Sub::Abstract qw(speak eat); # declarative form | ||
| 166 | |||
| 167 | =head3 Purpose | ||
| 168 | |||
| 169 | With B<no arguments>: makes the C<:Abstract> attribute globally available. | ||
| 170 | |||
| 171 | With B<one or more method names>: installs abstract-croak wrappers for | ||
| 172 | those methods in the calling package at C<CHECK> time (or immediately if | ||
| 173 | C<CHECK> has already fired). | ||
| 174 | |||
| 175 | =head3 Arguments | ||
| 176 | |||
| 177 | =over 4 | ||
| 178 | |||
| 179 | =item C<@methods> (optional) | ||
| 180 | |||
| 181 | Zero or more Perl sub names, each matching C</\A[_a-zA-Z]\w*\z/>. | ||
| 182 | |||
| 183 | =back | ||
| 184 | |||
| 185 | =head3 Returns | ||
| 186 | |||
| 187 | The class name (C<'Sub::Abstract'>) as a plain string. | ||
| 188 | |||
| 189 | =head3 MESSAGES | ||
| 190 | |||
| 191 | Message Meaning | ||
| 192 | --------------------------------------------------- ----------------------------------------------- | ||
| 193 | "Sub::Abstract->import: 'NAME' is not a valid A name failed the identifier regex. | ||
| 194 | Perl identifier" | ||
| 195 | |||
| 196 | =cut | ||
| 197 | |||
| 198 | sub import { | ||
| 199 | my ($class, @subs) = @_; | ||
| 200 | |||
| 201 | # No sub names: the :Abstract attribute is always available via UNIVERSAL. | ||
| 202 | return set_return($class, { type => 'string' }) unless @subs; | ||
| 203 | |||
| 204 | # Validate every name before touching the stash (fail-fast, all-or-nothing). | ||
| 205 | for my $sub_name (@subs) { | ||
| 206 | my $check = (defined $sub_name && !ref $sub_name) ? $sub_name : q{}; | ||
| 207 | eval { | ||
| 208 | validate_strict( | ||
| 209 | schema => $SUB_NAME_SCHEMA, | ||
| 210 | input => { name => $check }, | ||
| 211 | ); | ||
| 212 | }; | ||
| 213 | croak "$SELF->import: '$check' is not a valid Perl identifier" if $@; | ||
| 214 | } | ||
| 215 | |||
| 216 | # Schedule or immediately apply wrapping depending on compile phase. | ||
| 217 | my $owner_pkg = caller; | ||
| 218 | if ($_post_check) { | ||
| 219 | _process_one($owner_pkg, $_) for @subs; | ||
| 220 | } else { | ||
| 221 | push @_pending, [ $owner_pkg, $_ ] for @subs; | ||
| 222 | } | ||
| 223 | |||
| 224 | return set_return($class, { type => 'string' }); | ||
| 225 | } | ||
| 226 | |||
| 227 | # ------------------------------------------------------------------- | ||
| 228 | # CHECK-TIME PROCESSING | ||
| 229 | # ------------------------------------------------------------------- | ||
| 230 | |||
| 231 | # Process all declarative wraps queued during import(). | ||
| 232 | # After this fires, $_post_check=1 so future import() calls wrap immediately. | ||
| 233 | CHECK { | ||
| 234 | $_post_check = 1; | ||
| 235 | _process_one(@$_) for @_pending; | ||
| 236 | @_pending = (); | ||
| 237 | } | ||
| 238 | |||
| 239 | # ------------------------------------------------------------------- | ||
| 240 | # PRIVATE SUBROUTINES | ||
| 241 | # ------------------------------------------------------------------- | ||
| 242 | |||
| 243 | # _process_one | ||
| 244 | # Purpose : Install an abstract-croak wrapper for a named method in a package. | ||
| 245 | # Entry : $owner_pkg -- the package that declares the abstract method | ||
| 246 | # $sub_name -- the unqualified method name to wrap | ||
| 247 | # Exit status : Returns normally; the stash entry is replaced with a wrapper. | ||
| 248 | # Side effects : Modifies the package stash for $owner_pkg. | ||
| 249 | # Notes : Unlike Sub::Private/_process_one, no pre-existence check is done: | ||
| 250 | # the declarative form is the normal case where no body exists yet. | ||
| 251 | sub _process_one { | ||
| 252 | my ($owner_pkg, $sub_name) = @_; | ||
| 253 | |||
| 254 | _assert_private_caller('_process_one') | ||
| 255 | unless $BYPASS || ($config{harness_bypass} && $ENV{HARNESS_ACTIVE}); | ||
| 256 | |||
| 257 | no strict 'refs'; | ||
| 258 | no warnings 'redefine'; | ||
| 259 | *{"${owner_pkg}::${sub_name}"} = _wrap($owner_pkg, $sub_name); | ||
| 260 | return; | ||
| 261 | } | ||
| 262 | |||
| 263 | # _wrap | ||
| 264 | # Purpose : Build an abstract-enforcement wrapper closure. | ||
| 265 | # Entry : $owner_pkg -- the package that declares the abstract method | ||
| 266 | # $sub_name -- the unqualified method name (for error messages) | ||
| 267 | # Exit status : Returns a new coderef that croaks with a descriptive message | ||
| 268 | # naming the invocant class, unless a bypass is active. | ||
| 269 | # Notes : Unlike Sub::Private/_wrap there is no $code argument and no | ||
| 270 | # goto: the wrapper never delegates because calling an abstract | ||
| 271 | # method is always an error. ref($_[0])||$_[0] extracts the | ||
| 272 | # invocant so the error names the concrete class (e.g. Dog), | ||
| 273 | # not the abstract base (Animal). | ||
| 274 | sub _wrap { | ||
| 275 | my ($owner_pkg, $sub_name) = @_; | ||
| 276 | |||
| 277 | _assert_private_caller('_wrap') | ||
| 278 | unless $BYPASS || ($config{harness_bypass} && $ENV{HARNESS_ACTIVE}); | ||
| 279 | |||
| 280 | return sub { | ||
| 281 | return if $BYPASS; | ||
| 282 | return if $config{harness_bypass} && $ENV{HARNESS_ACTIVE}; | ||
| 283 | my $invocant = ref($_[0]) || $_[0] // '<undef>'; | ||
| 284 | croak "${sub_name}() is an abstract method of ${owner_pkg}" | ||
| 285 | . " and must be implemented by ${invocant}"; | ||
| 286 | }; | ||
| 287 | } | ||
| 288 | |||
| 289 | # _assert_private_caller | ||
| 290 | # Purpose : Croak if a guarded private method was called from outside | ||
| 291 | # Sub::Abstract. | ||
| 292 | # Entry : $method_name -- the guarded method name (for error messages) | ||
| 293 | # Exit status : Returns normally if caller(1) is Sub::Abstract; croaks otherwise. | ||
| 294 | sub _assert_private_caller { | ||
| 295 | my ($method_name) = @_; | ||
| 296 | my $caller = (caller(1))[0] // q{}; | ||
| 297 | return if $caller eq $SELF; | ||
| 298 | croak "${method_name}() is a private method of $SELF" | ||
| 299 | . " and cannot be called from ${caller}"; | ||
| 300 | } | ||
| 301 | |||
| 302 | 1; | ||
| 303 | |||
| 304 | __END__ |