8bca63519695a601e017d6dc6cef559bce10fa94
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / _Util.pm
1 package # hide from PAUSE
2   DBIx::Class::_Util;
3
4 use DBIx::Class::StartupCheck;  # load es early as we can, usually a noop
5
6 use warnings;
7 use strict;
8
9 # For the love of everything that is crab-like: DO NOT reach into this
10 # The entire thing is really fragile and should not be screwed with
11 # unless absolutely and unavoidably necessary
12 our $__describe_class_query_cache;
13
14 BEGIN {
15   package # hide from pause
16     DBIx::Class::_ENV_;
17
18   use Config;
19
20   use constant {
21     PERL_VERSION => "$]",
22     OS_NAME => "$^O",
23   };
24
25   use constant {
26
27     # but of course
28     BROKEN_FORK => (OS_NAME eq 'MSWin32') ? 1 : 0,
29
30     BROKEN_GOTO => ( PERL_VERSION < 5.008003 ) ? 1 : 0,
31
32     # perl -MScalar::Util=weaken -e 'weaken( $hash{key} = \"value" )'
33     BROKEN_WEAK_SCALARREF_VALUES => ( PERL_VERSION < 5.008003 ) ? 1 : 0,
34
35     HAS_ITHREADS => $Config{useithreads} ? 1 : 0,
36
37     UNSTABLE_DOLLARAT => ( PERL_VERSION < 5.013002 ) ? 1 : 0,
38
39     ( map
40       #
41       # the "DBIC_" prefix below is crucial - this is what makes CI pick up
42       # all envvars without further adjusting its scripts
43       # DO NOT CHANGE to the more logical { $_ => !!( $ENV{"DBIC_$_"} ) }
44       #
45       { substr($_, 5) => !!( $ENV{$_} ) }
46       qw(
47         DBIC_SHUFFLE_UNORDERED_RESULTSETS
48         DBIC_ASSERT_NO_INTERNAL_WANTARRAY
49         DBIC_ASSERT_NO_INTERNAL_INDIRECT_CALLS
50         DBIC_STRESSTEST_UTF8_UPGRADE_GENERATED_COLLAPSER_SOURCE
51         DBIC_STRESSTEST_COLUMN_INFO_UNAWARE_STORAGE
52       )
53     ),
54
55     IV_SIZE => $Config{ivsize},
56   };
57
58   if ( PERL_VERSION < 5.009_005) {
59     require MRO::Compat;
60     constant->import( OLD_MRO => 1 );
61
62     #
63     # Yes, I know this is a rather PHP-ish name, but please first read
64     # https://metacpan.org/source/BOBTFISH/MRO-Compat-0.12/lib/MRO/Compat.pm#L363-368
65     #
66     # Even if we are using Class::C3::XS it still won't work, as doing
67     #   defined( *{ "SubClass::"->{$_} }{CODE} )
68     # will set pkg_gen to the same value for SubClass and *ALL PARENTS*
69     #
70     *DBIx::Class::_Util::get_real_pkg_gen = sub ($) {
71       require Digest::MD5;
72       require Math::BigInt;
73
74       my $cur_class;
75       no strict 'refs';
76
77       # the non-assign-unless-there-is-a-hash is deliberate
78       ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_[0]}{gen} ||= (
79         Math::BigInt->new( '0x' . ( Digest::MD5::md5_hex( join "\0", map {
80
81           ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_}{methlist} ||= (
82
83             $cur_class = $_
84
85               and
86
87             # RV to be hashed up and turned into a number
88             join "\0", (
89               $cur_class,
90               map
91                 {(
92                   # stringification should be sufficient, ignore names/refaddr entirely
93                   $_,
94                   do {
95                     my @attrs;
96                     local $@;
97                     local $SIG{__DIE__} if $SIG{__DIE__};
98                     # attributes::get may throw on blessed-false crefs :/
99                     eval { @attrs = attributes::get( $_ ); 1 }
100                       or warn "Unable to determine attributes of coderef $_ due to the following error: $@";
101                     @attrs;
102                   },
103                 )}
104                 map
105                   {(
106                     # skip dummy C::C3 helper crefs
107                     ! ( ( $Class::C3::MRO{$cur_class} || {} )->{methods}{$_} )
108                       and
109                     (
110                       ref(\ "${cur_class}::"->{$_} ) ne 'GLOB'
111                         or
112                       defined( *{ "${cur_class}::"->{$_} }{CODE} )
113                     )
114                   )
115                     ? ( \&{"${cur_class}::$_"} )
116                     : ()
117                   }
118                   keys %{ "${cur_class}::" }
119             )
120           )
121         } (
122
123           @{
124             ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_[0]}{linear_isa}
125               ||=
126             mro::get_linear_isa($_[0])
127           },
128
129           ((
130             ( $__describe_class_query_cache->{'!internal!'} || {} )->{$_[0]}{is_universal}
131               ||=
132             mro::is_universal($_[0])
133           ) ? () : @{
134             ( $__describe_class_query_cache->{'!internal!'} || {} )->{UNIVERSAL}{linear_isa}
135               ||=
136             mro::get_linear_isa("UNIVERSAL")
137           } ),
138
139         ) ) ) )
140       );
141     };
142   }
143   else {
144     require mro;
145     constant->import( OLD_MRO => 0 );
146     *DBIx::Class::_Util::get_real_pkg_gen = \&mro::get_pkg_gen;
147   }
148
149   # Both of these are no longer used for anything. However bring
150   # them back after they were purged in 08a8d8f1, as there appear
151   # to be outfits with *COPY PASTED* pieces of lib/DBIx/Class/Storage/*
152   # in their production codebases. There is no point in breaking these
153   # if whatever they used actually continues to work
154   my $sigh = sub {
155     DBIx::Class::_Util::emit_loud_diag(
156       skip_frames => 1,
157       msg => "The @{[ (caller(1))[3] ]} constant is no more - adjust your code"
158     );
159
160     0;
161   };
162   sub DBICTEST () { &$sigh }
163   sub PEEPEENESS () { &$sigh }
164 }
165
166 use constant SPURIOUS_VERSION_CHECK_WARNINGS => ( DBIx::Class::_ENV_::PERL_VERSION < 5.010 ? 1 : 0);
167
168 # FIXME - this is not supposed to be here
169 # Carp::Skip to the rescue soon
170 use DBIx::Class::Carp '^DBIx::Class|^DBICTest';
171
172 use B ();
173 use Carp 'croak';
174 use Storable 'nfreeze';
175 use Scalar::Util qw(weaken blessed reftype refaddr);
176 use Sub::Quote qw(qsub);
177 use Sub::Name ();
178 use attributes ();
179
180 # Already correctly prototyped: perlbrew exec perl -MStorable -e 'warn prototype \&Storable::dclone'
181 BEGIN { *deep_clone = \&Storable::dclone }
182
183 use base 'Exporter';
184 our @EXPORT_OK = qw(
185   sigwarn_silencer modver_gt_or_eq modver_gt_or_eq_and_lt
186   fail_on_internal_wantarray fail_on_internal_call
187   refdesc refcount hrefaddr set_subname describe_class_methods
188   scope_guard detected_reinvoked_destructor emit_loud_diag
189   true false
190   is_exception dbic_internal_try visit_namespaces
191   quote_sub qsub perlstring serialize deep_clone dump_value uniq
192   parent_dir mkdir_p
193   UNRESOLVABLE_CONDITION
194 );
195
196 use constant UNRESOLVABLE_CONDITION => \ '1 = 0';
197
198 # Override forcing no_defer, and adding naming consistency checks
199 our %refs_closed_over_by_quote_sub_installed_crefs;
200 sub quote_sub {
201   Carp::confess( "Anonymous quoting not supported by the DBIC quote_sub override - supply a sub name" ) if
202     @_ < 2
203       or
204     ! defined $_[1]
205       or
206     length ref $_[1]
207   ;
208
209   Carp::confess( "The DBIC quote_sub override expects sub name '$_[0]' to be fully qualified" )
210     unless (my $stash) = $_[0] =~ /^(.+)::/;
211
212   Carp::confess(
213     "The DBIC sub_quote override does not support 'no_install'"
214   ) if (
215     $_[3]
216       and
217     $_[3]->{no_install}
218   );
219
220   Carp::confess(
221     'The DBIC quote_sub override expects the namespace-part of sub name '
222   . "'$_[0]' to match the supplied package argument '$_[3]->{package}'"
223   ) if (
224     $_[3]
225       and
226     defined $_[3]->{package}
227       and
228     $stash ne $_[3]->{package}
229   );
230
231   my @caller = caller(0);
232   my $sq_opts = {
233     package => $caller[0],
234     hints => $caller[8],
235     warning_bits => $caller[9],
236     hintshash => $caller[10],
237     %{ $_[3] || {} },
238
239     # explicitly forced for everything
240     no_defer => 1,
241   };
242
243   weaken (
244     # just use a growing counter, no need to perform neither compaction
245     # nor any special ithread-level handling
246     $refs_closed_over_by_quote_sub_installed_crefs
247      { scalar keys %refs_closed_over_by_quote_sub_installed_crefs }
248       = $_
249   ) for grep {
250     length ref $_
251       and
252     (
253       ! DBIx::Class::_ENV_::BROKEN_WEAK_SCALARREF_VALUES
254         or
255       ref $_ ne 'SCALAR'
256     )
257   } values %{ $_[2] || {} };
258
259   Sub::Quote::quote_sub( $_[0], $_[1], $_[2]||{}, $sq_opts );
260 }
261
262 sub sigwarn_silencer ($) {
263   my $pattern = shift;
264
265   croak "Expecting a regexp" if ref $pattern ne 'Regexp';
266
267   my $orig_sig_warn = $SIG{__WARN__} || sub { CORE::warn(@_) };
268
269   return sub { &$orig_sig_warn unless $_[0] =~ $pattern };
270 }
271
272 sub perlstring ($) { q{"}. quotemeta( shift ). q{"} };
273
274 sub hrefaddr ($) { sprintf '0x%x', &refaddr||0 }
275
276 sub refdesc ($) {
277   croak "Expecting a reference" if ! length ref $_[0];
278
279   # be careful not to trigger stringification,
280   # reuse @_ as a scratch-pad
281   sprintf '%s%s(0x%x)',
282     ( defined( $_[1] = blessed $_[0]) ? "$_[1]=" : '' ),
283     reftype $_[0],
284     refaddr($_[0]),
285   ;
286 }
287
288 sub refcount ($) {
289   croak "Expecting a reference" if ! length ref $_[0];
290
291   # No tempvars - must operate on $_[0], otherwise the pad
292   # will count as an extra ref
293   B::svref_2object($_[0])->REFCNT;
294 }
295
296 sub visit_namespaces {
297   my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
298
299   my $visited_count = 1;
300
301   # A package and a namespace are subtly different things
302   $args->{package} ||= 'main';
303   $args->{package} = 'main' if $args->{package} =~ /^ :: (?: main )? $/x;
304   $args->{package} =~ s/^:://;
305
306   if ( $args->{action}->($args->{package}) ) {
307     my $ns =
308       ( ($args->{package} eq 'main') ? '' :  $args->{package} )
309         .
310       '::'
311     ;
312
313     $visited_count += visit_namespaces( %$args, package => $_ ) for
314       grep
315         # this happens sometimes on %:: traversal
316         { $_ ne '::main' }
317         map
318           { $_ =~ /^(.+?)::$/ ? "$ns$1" : () }
319           do { no strict 'refs'; keys %$ns }
320     ;
321   }
322
323   $visited_count;
324 }
325
326 # FIXME In another life switch this to a polyfill like the one in namespace::clean
327 sub set_subname ($$) {
328
329   # fully qualify name
330   splice @_, 0, 1, caller(0) . "::$_[0]"
331     if $_[0] !~ /::|'/;
332
333   &Sub::Name::subname;
334 }
335
336 sub serialize ($) {
337   local $Storable::canonical = 1;
338   nfreeze($_[0]);
339 }
340
341 sub uniq {
342   my( %seen, $seen_undef, $numeric_preserving_copy );
343   grep { not (
344     defined $_
345       ? $seen{ $numeric_preserving_copy = $_ }++
346       : $seen_undef++
347   ) } @_;
348 }
349
350 my $dd_obj;
351 sub dump_value ($) {
352   local $Data::Dumper::Indent = 1
353     unless defined $Data::Dumper::Indent;
354
355   my $dump_str = (
356     $dd_obj
357       ||=
358     do {
359       require Data::Dumper;
360       my $d = Data::Dumper->new([])
361         ->Purity(0)
362         ->Pad('')
363         ->Useqq(1)
364         ->Terse(1)
365         ->Freezer('')
366         ->Quotekeys(0)
367         ->Bless('bless')
368         ->Pair(' => ')
369         ->Sortkeys(1)
370         ->Deparse(1)
371       ;
372
373       $d->Sparseseen(1) if modver_gt_or_eq (
374         'Data::Dumper', '2.136'
375       );
376
377       $d;
378     }
379   )->Values([$_[0]])->Dump;
380
381   $dd_obj->Reset->Values([]);
382
383   $dump_str;
384 }
385
386 my $seen_loud_screams;
387 sub emit_loud_diag {
388   my $args = { ref $_[0] eq 'HASH' ? %{$_[0]} : @_ };
389
390   unless ( defined $args->{msg} and length $args->{msg} ) {
391     emit_loud_diag(
392       msg => "No 'msg' value supplied to emit_loud_diag()"
393     );
394     exit 70;
395   }
396
397   my $msg = "\n$0: $args->{msg}";
398
399   # when we die - we usually want to keep doing it
400   $args->{emit_dups} = !!$args->{confess}
401     unless exists $args->{emit_dups};
402
403   local $Carp::CarpLevel =
404     ( $args->{skip_frames} || 0 )
405       +
406     $Carp::CarpLevel
407       +
408     # hide our own frame
409     1
410   ;
411
412   my $longmess = Carp::longmess();
413
414   # different object references will thwart deduplication without this
415   ( my $key = "${msg}\n${longmess}" ) =~ s/\b0x[0-9a-f]+\b/0x.../gi;
416
417   return $seen_loud_screams->{$key} if
418     $seen_loud_screams->{$key}++
419       and
420     ! $args->{emit_dups}
421   ;
422
423   $msg .= $longmess
424     unless $msg =~ /\n\z/;
425
426   print STDERR "$msg\n"
427     or
428   print STDOUT "\n!!!STDERR ISN'T WRITABLE!!!:$msg\n";
429
430   return $seen_loud_screams->{$key}
431     unless $args->{confess};
432
433   # increment *again*, because... Carp.
434   $Carp::CarpLevel++;
435
436   # not $msg - Carp will reapply the longmess on its own
437   Carp::confess($args->{msg});
438 }
439
440
441 ###
442 ### This is *NOT* boolean.pm - deliberately not using a singleton
443 ###
444 {
445   package # hide from pause
446     DBIx::Class::_Util::_Bool;
447   use overload
448     bool => sub { ${$_[0]} },
449     fallback => 1,
450   ;
451 }
452 sub true () { my $x = 1; bless \$x, "DBIx::Class::_Util::_Bool" }
453 sub false () { my $x = 0; bless \$x, "DBIx::Class::_Util::_Bool" }
454
455 sub scope_guard (&) {
456   croak 'Calling scope_guard() in void context makes no sense'
457     if ! defined wantarray;
458
459   # no direct blessing of coderefs - DESTROY is buggy on those
460   bless [ $_[0] ], 'DBIx::Class::_Util::ScopeGuard';
461 }
462 {
463   package #
464     DBIx::Class::_Util::ScopeGuard;
465
466   sub DESTROY {
467     &DBIx::Class::_Util::detected_reinvoked_destructor;
468
469     local $@ if DBIx::Class::_ENV_::UNSTABLE_DOLLARAT;
470
471     eval {
472       $_[0]->[0]->();
473       1;
474     }
475       or
476     DBIx::Class::_Util::emit_loud_diag(
477       emit_dups => 1,
478       msg => "Execution of scope guard $_[0] resulted in the non-trappable exception:\n\n$@\n "
479     );
480   }
481 }
482
483
484 sub is_exception ($) {
485   my $e = $_[0];
486
487   # FIXME
488   # this is not strictly correct - an eval setting $@ to undef
489   # is *not* the same as an eval setting $@ to ''
490   # but for the sake of simplicity assume the following for
491   # the time being
492   return 0 unless defined $e;
493
494   my ($not_blank, $suberror);
495   {
496     local $SIG{__DIE__} if $SIG{__DIE__};
497     local $@;
498     eval {
499       # The ne() here is deliberate - a plain length($e), or worse "$e" ne
500       # will entirely obviate the need for the encolsing eval{}, as the
501       # condition we guard against is a missing fallback overload
502       $not_blank = ( $e ne '' );
503       1;
504     } or $suberror = $@;
505   }
506
507   if (defined $suberror) {
508     if (length (my $class = blessed($e) )) {
509       carp_unique( sprintf(
510         'External exception class %s implements partial (broken) overloading '
511       . 'preventing its instances from being used in simple ($x eq $y) '
512       . 'comparisons. Given Perl\'s "globally cooperative" exception '
513       . 'handling this type of brokenness is extremely dangerous on '
514       . 'exception objects, as it may (and often does) result in silent '
515       . '"exception substitution". DBIx::Class tries to work around this '
516       . 'as much as possible, but other parts of your software stack may '
517       . 'not be even aware of this. Please submit a bugreport against the '
518       . 'distribution containing %s and in the meantime apply a fix similar '
519       . 'to the one shown at %s, in order to ensure your exception handling '
520       . 'is saner application-wide. What follows is the actual error text '
521       . "as generated by Perl itself:\n\n%s\n ",
522         $class,
523         $class,
524         'http://v.gd/DBIC_overload_tempfix/',
525         $suberror,
526       ));
527
528       # workaround, keeps spice flowing
529       $not_blank = !!( length $e );
530     }
531     else {
532       # not blessed yet failed the 'ne'... this makes 0 sense...
533       # just throw further
534       die $suberror
535     }
536   }
537   elsif (
538     # a ref evaluating to '' is definitively a "null object"
539     ( not $not_blank )
540       and
541     length( my $class = ref $e )
542   ) {
543     carp_unique(
544       "Objects of external exception class '$class' stringify to '' (the "
545     . 'empty string), implementing the so called null-object-pattern. '
546     . 'Given Perl\'s "globally cooperative" exception handling using this '
547     . 'class of exceptions is extremely dangerous, as it may (and often '
548     . 'does) result in silent discarding of errors. DBIx::Class tries to '
549     . 'work around this as much as possible, but other parts of your '
550     . 'software stack may not be even aware of the problem. Please submit '
551     . "a bugreport against the distribution containing '$class'",
552     );
553
554     $not_blank = 1;
555   }
556
557   return $not_blank;
558 }
559
560 {
561   my $callstack_state;
562
563   # Recreate the logic of try(), while reusing the catch()/finally() as-is
564   #
565   # FIXME: We need to move away from Try::Tiny entirely (way too heavy and
566   # yes, shows up ON TOP of profiles) but this is a batle for another maint
567   sub dbic_internal_try (&;@) {
568
569     my $try_cref = shift;
570     my $catch_cref = undef;  # apparently this is a thing... https://rt.perl.org/Public/Bug/Display.html?id=119311
571
572     for my $arg (@_) {
573
574       if( ref($arg) eq 'Try::Tiny::Catch' ) {
575
576         croak 'dbic_internal_try() may not be followed by multiple catch() blocks'
577           if $catch_cref;
578
579         $catch_cref = $$arg;
580       }
581       elsif ( ref($arg) eq 'Try::Tiny::Finally' ) {
582         croak 'dbic_internal_try() does not support finally{}';
583       }
584       else {
585         croak(
586           'dbic_internal_try() encountered an unexpected argument '
587         . "'@{[ defined $arg ? $arg : 'UNDEF' ]}' - perhaps "
588         . 'a missing semi-colon before or ' # trailing space important
589         );
590       }
591     }
592
593     my $wantarray = wantarray;
594     my $preexisting_exception = $@;
595
596     my @ret;
597     my $all_good = eval {
598       $@ = $preexisting_exception;
599
600       local $callstack_state->{in_internal_try} = 1
601         unless $callstack_state->{in_internal_try};
602
603       # always unset - someone may have snuck it in
604       local $SIG{__DIE__} if $SIG{__DIE__};
605
606       if( $wantarray ) {
607         @ret = $try_cref->();
608       }
609       elsif( defined $wantarray ) {
610         $ret[0] = $try_cref->();
611       }
612       else {
613         $try_cref->();
614       }
615
616       1;
617     };
618
619     my $exception = $@;
620     $@ = $preexisting_exception;
621
622     if ( $all_good ) {
623       return $wantarray ? @ret : $ret[0]
624     }
625     elsif ( $catch_cref ) {
626       for ( $exception ) {
627         return $catch_cref->($exception);
628       }
629     }
630
631     return;
632   }
633
634   sub in_internal_try { !! $callstack_state->{in_internal_try} }
635 }
636
637 {
638   my $destruction_registry = {};
639
640   sub DBIx::Class::__Util_iThreads_handler__::CLONE {
641     %$destruction_registry = map {
642       (defined $_)
643         ? ( refaddr($_) => $_ )
644         : ()
645     } values %$destruction_registry;
646
647     weaken($_) for values %$destruction_registry;
648
649     # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
650     # collected before leaving this scope. Depending on the code above, this
651     # may very well be just a preventive measure guarding future modifications
652     undef;
653   }
654
655   # This is almost invariably invoked from within DESTROY
656   # throwing exceptions won't work
657   sub detected_reinvoked_destructor {
658
659     # quick "garbage collection" pass - prevents the registry
660     # from slowly growing with a bunch of undef-valued keys
661     defined $destruction_registry->{$_} or delete $destruction_registry->{$_}
662       for keys %$destruction_registry;
663
664     if (! length ref $_[0]) {
665       emit_loud_diag(
666         emit_dups => 1,
667         msg => (caller(0))[3] . '() expects a blessed reference'
668       );
669       return undef; # don't know wtf to do
670     }
671     elsif (! defined $destruction_registry->{ my $addr = refaddr($_[0]) } ) {
672       weaken( $destruction_registry->{$addr} = $_[0] );
673       return 0;
674     }
675     else {
676       emit_loud_diag( msg => sprintf (
677         'Preventing *MULTIPLE* DESTROY() invocations on %s - an *EXTREMELY '
678       . 'DANGEROUS* condition which is *ALMOST CERTAINLY GLOBAL* within your '
679       . 'application, affecting *ALL* classes without active protection against '
680       . 'this. Diagnose and fix the root cause ASAP!!!%s',
681       refdesc $_[0],
682         ( ( $INC{'Devel/StackTrace.pm'} and ! do { local $@; eval { Devel::StackTrace->VERSION(2) } } )
683           ? " (likely culprit Devel::StackTrace\@@{[ Devel::StackTrace->VERSION ]} found in %INC, http://is.gd/D_ST_refcap)"
684           : ''
685         )
686       ));
687
688       return 1;
689     }
690   }
691 }
692
693 my $module_name_rx = qr/ \A [A-Z_a-z] [0-9A-Z_a-z]* (?: :: [0-9A-Z_a-z]+ )* \z /x;
694 my $ver_rx =         qr/ \A [0-9]+ (?: \. [0-9]+ )* (?: \_ [0-9]+ )*        \z /x;
695
696 sub modver_gt_or_eq ($$) {
697   my ($mod, $ver) = @_;
698
699   croak "Nonsensical module name supplied"
700     if ! defined $mod or $mod !~ $module_name_rx;
701
702   croak "Nonsensical minimum version supplied"
703     if ! defined $ver or $ver !~ $ver_rx;
704
705   no strict 'refs';
706   my $ver_cache = ${"${mod}::__DBIC_MODULE_VERSION_CHECKS__"} ||= ( $mod->VERSION
707     ? {}
708     : croak "$mod does not seem to provide a version (perhaps it never loaded)"
709   );
710
711   ! defined $ver_cache->{$ver}
712     and
713   $ver_cache->{$ver} = do {
714
715     local $SIG{__WARN__} = sigwarn_silencer( qr/\Qisn't numeric in subroutine entry/ )
716       if SPURIOUS_VERSION_CHECK_WARNINGS;
717
718     local $SIG{__DIE__} if $SIG{__DIE__};
719     local $@;
720     eval { $mod->VERSION($ver) } ? 1 : 0;
721   };
722
723   $ver_cache->{$ver};
724 }
725
726 sub modver_gt_or_eq_and_lt ($$$) {
727   my ($mod, $v_ge, $v_lt) = @_;
728
729   croak "Nonsensical maximum version supplied"
730     if ! defined $v_lt or $v_lt !~ $ver_rx;
731
732   return (
733     modver_gt_or_eq($mod, $v_ge)
734       and
735     ! modver_gt_or_eq($mod, $v_lt)
736   ) ? 1 : 0;
737 }
738
739 {
740
741   sub describe_class_methods {
742     my $args = (
743       ref $_[0] eq 'HASH'                 ? $_[0]
744     : ( @_ == 1 and ! length ref $_[0] )  ? { class => $_[0] }
745     :                                       { @_ }
746     );
747
748     my ($class, $requested_mro) = @{$args}{qw( class use_mro )};
749
750     croak "Expecting a class name either as the sole argument or a 'class' option"
751       if not defined $class or $class !~ $module_name_rx;
752
753     $requested_mro ||= mro::get_mro($class);
754
755     # mro::set_mro() does not bump pkg_gen - WHAT THE FUCK?!
756     my $query_cache_key = "$class|$requested_mro";
757
758     my $internal_cache_key =
759       ( mro::get_mro($class) eq $requested_mro )
760         ? $class
761         : $query_cache_key
762     ;
763
764     # use a cache on old MRO, since while we are recursing in this function
765     # nothing can possibly change (the speedup is immense)
766     # (yes, people could be tie()ing the stash and adding methods on access
767     # but there is a limit to how much crazy can be supported here)
768     #
769     # we use the cache for linear_isa lookups on new MRO as well - it adds
770     # a *tiny* speedup, and simplifies the code a lot
771     #
772     local $__describe_class_query_cache->{'!internal!'} = {}
773       unless $__describe_class_query_cache->{'!internal!'};
774
775     my $my_gen = 0;
776
777     $my_gen += get_real_pkg_gen($_) for ( my @full_ISA = (
778
779       @{
780         $__describe_class_query_cache->{'!internal!'}{$internal_cache_key}{linear_isa}
781           ||=
782         mro::get_linear_isa($class, $requested_mro)
783       },
784
785       ((
786         $__describe_class_query_cache->{'!internal!'}{$class}{is_universal}
787           ||=
788         mro::is_universal($class)
789       ) ? () : @{
790         $__describe_class_query_cache->{'!internal!'}{UNIVERSAL}{linear_isa}
791           ||=
792         mro::get_linear_isa("UNIVERSAL")
793       }),
794
795     ));
796
797     my $slot = $__describe_class_query_cache->{$query_cache_key} ||= {};
798
799     unless ( ($slot->{cumulative_gen}||0) == $my_gen ) {
800
801       # reset
802       %$slot = (
803         class => $class,
804         isa => { map { $_ => 1 } @full_ISA },
805         linear_isa => [
806           @{ $__describe_class_query_cache->{'!internal!'}{$internal_cache_key}{linear_isa} }
807             [ 1 .. $#{$__describe_class_query_cache->{'!internal!'}{$internal_cache_key}{linear_isa}} ]
808         ],
809         mro => {
810           type => $requested_mro,
811           is_c3 => ( ($requested_mro eq 'c3') ? 1 : 0 ),
812         },
813         cumulative_gen => $my_gen,
814       );
815
816       # remove ourselves from ISA
817       shift @full_ISA;
818
819       # ensure the cache is populated for the parents, code below can then
820       # efficiently operate over the query_cache directly
821       describe_class_methods($_) for reverse @full_ISA;
822
823       no strict 'refs';
824
825       # combine full ISA-order inherited and local method list into a
826       # "shadowing stack"
827
828       (
829         unshift @{ $slot->{methods}{$_->{name}} }, $_
830
831           and
832
833         (
834           $_->{via_class} ne $class
835             or
836           $slot->{methods_defined_in_class}{$_->{name}} = $_
837         )
838
839           and
840
841         @{ $slot->{methods}{$_->{name}} } > 1
842
843           and
844
845         $slot->{methods_with_supers}{$_->{name}} = $slot->{methods}{$_->{name}}
846
847       ) for (
848
849         # what describe_class_methods for @full_ISA produced above
850         ( map { values %{
851           $__describe_class_query_cache->{$_}{methods_defined_in_class} || {}
852         } } map { "$_|" . mro::get_mro($_) } reverse @full_ISA ),
853
854         # our own non-cleaned subs + their attributes
855         ( map {
856           (
857             # need to account for dummy helper crefs under OLD_MRO
858             (
859               ! DBIx::Class::_ENV_::OLD_MRO
860                 or
861               ! ( ( $Class::C3::MRO{$class} || {} )->{methods}{$_} )
862             )
863               and
864             # these 2 OR-ed checks are sufficient for 5.10+
865             (
866               ref(\ "${class}::"->{$_} ) ne 'GLOB'
867                 or
868               defined( *{ "${class}::"->{$_} }{CODE} )
869             )
870           ) ? {
871               via_class => $class,
872               name => $_,
873               attributes => { map { $_ => 1 } do {
874                 my @attrs;
875                 local $@;
876                 local $SIG{__DIE__} if $SIG{__DIE__};
877                 # attributes::get may throw on blessed-false crefs :/
878                 eval { @attrs = attributes::get( \&{"${class}::${_}"} ); 1 }
879                   or warn "Unable to determine attributes of the \\&${class}::$_ method due to following error: $@";
880                 @attrs;
881               } },
882             }
883             : ()
884         } keys %{"${class}::"} )
885       );
886
887
888       # recalculate the pkg_gen on newer perls under Taint mode,
889       # because of shit like:
890       # perl -T -Mmro -e 'package Foo; sub bar {}; defined( *{ "Foo::"->{bar}}{CODE} ) and warn mro::get_pkg_gen("Foo") for (1,2,3)'
891       #
892       if (
893         ! DBIx::Class::_ENV_::OLD_MRO
894           and
895         ${^TAINT}
896       ) {
897
898         $slot->{cumulative_gen} = 0;
899         $slot->{cumulative_gen} += get_real_pkg_gen($_)
900           for $class, @full_ISA;
901       }
902     }
903
904     # RV
905     +{ %$slot };
906   }
907 }
908
909
910 #
911 # Why not just use some higher-level module or at least File::Spec here?
912 # Because:
913 # 1)  This is a *very* rarely used function, and the deptree is large
914 #     enough already as it is
915 #
916 # 2)  (more importantly) Our tooling is utter shit in this area. There
917 #     is no comprehensive support for UNC paths in PathTools and there
918 #     are also various small bugs in representation across different
919 #     path-manipulation CPAN offerings.
920 #
921 # Since this routine is strictly used for logical path processing (it
922 # *must* be able to work with not-yet-existing paths), use this seemingly
923 # simple but I *think* complete implementation to feed to other consumers
924 #
925 # If bugs are ever uncovered in this routine, *YOU ARE URGED TO RESIST*
926 # the impulse to bring in an external dependency. During runtime there
927 # is exactly one spot that could potentially maybe once in a blue moon
928 # use this function. Keep it lean.
929 #
930 sub parent_dir ($) {
931   ( $_[0] =~ m{  [\/\\]  ( \.{0,2} ) ( [\/\\]* ) \z }x )
932     ? (
933       $_[0]
934         .
935       ( ( length($1) and ! length($2) ) ? '/' : '' )
936         .
937       '../'
938     )
939     : (
940       require File::Spec
941         and
942       File::Spec->catpath (
943         ( File::Spec->splitpath( "$_[0]" ) )[0,1],
944         '/',
945       )
946     )
947   ;
948 }
949
950 sub mkdir_p ($) {
951   require File::Path;
952   # do not ask for a recent version, use 1.x API calls
953   File::Path::mkpath([ "$_[0]" ]);  # File::Path does not like objects
954 }
955
956
957 {
958   my $list_ctx_ok_stack_marker;
959
960   sub fail_on_internal_wantarray () {
961     return if $list_ctx_ok_stack_marker;
962
963     if (! defined wantarray) {
964       croak('fail_on_internal_wantarray() needs a tempvar to save the stack marker guard');
965     }
966
967     my $cf = 1;
968     while ( ( (CORE::caller($cf+1))[3] || '' ) =~ / :: (?:
969
970       # these are public API parts that alter behavior on wantarray
971       search | search_related | slice | search_literal
972
973         |
974
975       # these are explicitly prefixed, since we only recognize them as valid
976       # escapes when they come from the guts of CDBICompat
977       CDBICompat .*? :: (?: search_where | retrieve_from_sql | retrieve_all )
978
979     ) $/x ) {
980       $cf++;
981     }
982
983     my ($fr, $want, $argdesc);
984     {
985       package DB;
986       $fr = [ CORE::caller($cf) ];
987       $want = ( CORE::caller($cf-1) )[5];
988       $argdesc = ref $DB::args[0]
989         ? DBIx::Class::_Util::refdesc($DB::args[0])
990         : 'non '
991       ;
992     };
993
994     if (
995       $want and $fr->[0] =~ /^(?:DBIx::Class|DBICx::)/
996     ) {
997       DBIx::Class::Exception->throw( sprintf (
998         "Improper use of %s instance in list context at %s line %d\n\n    Stacktrace starts",
999         $argdesc, @{$fr}[1,2]
1000       ), 'with_stacktrace');
1001     }
1002
1003     weaken( $list_ctx_ok_stack_marker = my $mark = [] );
1004
1005     $mark;
1006   }
1007 }
1008
1009 sub fail_on_internal_call {
1010   my ($fr, $argdesc);
1011   {
1012     package DB;
1013     $fr = [ CORE::caller(1) ];
1014     $argdesc = ref $DB::args[0]
1015       ? DBIx::Class::_Util::refdesc($DB::args[0])
1016       : ( $DB::args[0] . '' )
1017     ;
1018   };
1019
1020   my @fr2;
1021   # need to make allowance for a proxy-yet-direct call
1022   my $check_fr = (
1023     $fr->[0] eq 'DBIx::Class::ResultSourceProxy'
1024       and
1025     @fr2 = (CORE::caller(2))
1026       and
1027     (
1028       ( $fr->[3] =~ /([^:])+$/ )[0]
1029         eq
1030       ( $fr2[3] =~ /([^:])+$/ )[0]
1031     )
1032   )
1033     ? \@fr2
1034     : $fr
1035   ;
1036
1037   if (
1038     $argdesc
1039       and
1040     $check_fr->[0] =~ /^(?:DBIx::Class|DBICx::)/
1041       and
1042     $check_fr->[1] !~ /\b(?:CDBICompat|ResultSetProxy)\b/  # no point touching there
1043   ) {
1044     DBIx::Class::Exception->throw( sprintf (
1045       "Illegal internal call of indirect proxy-method %s() with argument '%s': examine the last lines of the proxy method deparse below to determine what to call directly instead at %s on line %d\n\n%s\n\n    Stacktrace starts",
1046       $fr->[3], $argdesc, @{$fr}[1,2], ( $fr->[6] || do {
1047         require B::Deparse;
1048         no strict 'refs';
1049         B::Deparse->new->coderef2text(\&{$fr->[3]})
1050       }),
1051     ), 'with_stacktrace');
1052   }
1053 }
1054
1055 1;