maint: restructure to use Dist::Zilla
[bioperl-live.git] / lib / Bio / Root / RootI.pm
blobcae801114d78a0116680a51859caba39ef295e35
1 package Bio::Root::RootI;
2 use strict;
3 use Carp 'confess','carp';
5 =head1 SYNOPSIS
7 # any bioperl or bioperl compliant object is a RootI
8 # compliant object
10 $obj->throw("This is an exception");
12 eval {
13 $obj->throw("This is catching an exception");
16 if( $@ ) {
17 print "Caught exception";
18 } else {
19 print "no exception";
22 # Using throw_not_implemented() within a RootI-based interface module:
24 package Foo;
25 use base qw(Bio::Root::RootI);
27 sub foo {
28 my $self = shift;
29 $self->throw_not_implemented;
33 =head1 DESCRIPTION
35 This is just a set of methods which do not assume B<anything> about the object
36 they are on. The methods provide the ability to throw exceptions with nice
37 stack traces.
39 This is what should be inherited by all Bioperl compliant interfaces, even
40 if they are exotic XS/CORBA/Other perl systems.
42 =head2 Using throw_not_implemented()
44 The method L<throw_not_implemented()|throw_not_implemented> should be
45 called by all methods within interface modules that extend RootI so
46 that if an implementation fails to override them, an exception will be
47 thrown.
49 For example, say there is an interface module called C<FooI> that
50 provides a method called C<foo()>. Since this method is considered
51 abstract within FooI and should be implemented by any module claiming to
52 implement C<FooI>, the C<FooI::foo()> method should consist of the
53 following:
55 sub foo {
56 my $self = shift;
57 $self->throw_not_implemented;
60 So, if an implementer of C<FooI> forgets to implement C<foo()>
61 and a user of the implementation calls C<foo()>, a
62 L<Bio::Exception::NotImplemented> exception will result.
64 Unfortunately, failure to implement a method can only be determined at
65 run time (i.e., you can't verify that an implementation is complete by
66 running C<perl -wc> on it). So it should be standard practice for a test
67 of an implementation to check each method and verify that it doesn't
68 throw a L<Bio::Exception::NotImplemented>.
70 =head1 AUTHOR Steve Chervitz
72 Ewan Birney, Lincoln Stein, Steve Chervitz, Sendu Bala, Jason Stajich
74 =cut
76 use vars qw($DEBUG $ID $VERBOSITY);
77 BEGIN {
78 $ID = 'Bio::Root::RootI';
79 $DEBUG = 0;
80 $VERBOSITY = 0;
83 =head2 new
85 =cut
87 sub new {
88 my $class = shift;
89 my @args = @_;
90 unless ( $ENV{'BIOPERLDEBUG'} ) {
91 carp("Use of new in Bio::Root::RootI is deprecated. Please use Bio::Root::Root instead");
93 eval "require Bio::Root::Root";
94 return Bio::Root::Root->new(@args);
97 # for backwards compatibility
98 sub _initialize {
99 my($self,@args) = @_;
100 return 1;
104 =head2 throw
106 Title : throw
107 Usage : $obj->throw("throwing exception message")
108 Function: Throws an exception, which, if not caught with an eval brace
109 will provide a nice stack trace to STDERR with the message
110 Returns : nothing
111 Args : A string giving a descriptive error message
114 =cut
116 sub throw{
117 my ($self,$string) = @_;
119 my $std = $self->stack_trace_dump();
121 my $out = "\n-------------------- EXCEPTION --------------------\n"
122 . "MSG: " . $string . "\n"
123 . $std."-------------------------------------------\n";
124 die $out;
127 =head2 warn
129 Title : warn
130 Usage : $object->warn("Warning message");
131 Function: Places a warning. What happens now is down to the
132 verbosity of the object (value of $obj->verbose)
133 verbosity 0 or not set => small warning
134 verbosity -1 => no warning
135 verbosity 1 => warning with stack trace
136 verbosity 2 => converts warnings into throw
137 Returns : n/a
138 Args : string (the warning message)
140 =cut
142 sub warn {
143 my ($self,$string) = @_;
145 my $verbose = $self->verbose;
147 my $header = "\n--------------------- WARNING ---------------------\nMSG: ";
148 my $footer = "---------------------------------------------------\n";
150 if ($verbose >= 2) {
151 $self->throw($string);
153 elsif ($verbose <= -1) {
154 return;
156 elsif ($verbose == 1) {
157 CORE::warn $header, $string, "\n", $self->stack_trace_dump, $footer;
158 return;
161 CORE::warn $header, $string, "\n", $footer;
164 =head2 deprecated
166 Title : deprecated
167 Usage : $obj->deprecated("Method X is deprecated");
168 $obj->deprecated("Method X is deprecated", 1.007);
169 $obj->deprecated(-message => "Method X is deprecated");
170 $obj->deprecated(-message => "Method X is deprecated",
171 -version => 1.007);
172 Function: Prints a message about deprecation unless verbose is < 0
173 (which means be quiet)
174 Returns : none
175 Args : Message string to print to STDERR
176 Version of BioPerl where use of the method results in an exception
177 Notes : The method can be called two ways, either by positional arguments:
179 $obj->deprecated('This module is deprecated', 1.006);
181 or by named arguments:
183 $obj->deprecated(
184 -message => 'use of the method foo() is deprecated, use bar() instead',
185 -version => 1.006 # throw if $VERSION is >= this version
188 or timed to go off at a certain point:
190 $obj->deprecated(
191 -message => 'use of the method foo() is deprecated, use bar() instead',
192 -warn_version => 1.006 # warn if $VERSION is >= this version
193 -throw_version => 1.007 # throw if $VERSION is >= this version
196 Using the last two named argument versions is suggested and will
197 likely be the only supported way of calling this method in the future
198 Yes, we see the irony of deprecating that particular usage of
199 deprecated().
201 The main difference between usage of the two named argument versions
202 is that by designating a 'warn_version' one indicates the
203 functionality is officially deprecated beginning in a future version
204 of BioPerl (so warnings are issued only after that point), whereas
205 setting either 'version' or 'throw_version' (synonyms) converts the
206 deprecation warning to an exception.
208 For proper comparisons one must use a version in lines with the
209 current versioning scheme for Perl and BioPerl, (i.e. where 1.006000
210 indicates v1.6.0, 5.010000 for v5.10.0, etc.).
212 =cut
214 sub deprecated{
215 my ($self) = shift;
217 my $class = ref $self || $self;
218 my $class_version = do {
219 no strict 'refs';
220 ${"${class}::VERSION"}
223 if( $class_version && $class_version =~ /set by/ ) {
224 $class_version = 0.0001;
227 my ($msg, $version, $warn_version, $throw_version) =
228 $self->_rearrange([qw(MESSAGE VERSION WARN_VERSION THROW_VERSION)], @_);
230 $throw_version ||= $version;
231 $warn_version ||= $class_version;
233 $throw_version =~ s/_//g;
234 $warn_version =~ s/_//g;
236 for my $v ( $warn_version, $throw_version) {
237 no warnings 'numeric';
238 $self->throw("Version must be numerical, such as 1.006000 for v1.6.0, not $v")
239 unless !defined $v || $v + 0 == $v;
242 # below default insinuates we're deprecating a method and not a full module
243 # but it's the most common use case
244 $msg ||= "Use of ".(caller(1))[3]."() is deprecated.";
246 if( $throw_version && $class_version && $class_version >= $throw_version ) {
247 $self->throw($msg)
249 elsif( $warn_version && $class_version && $class_version >= $warn_version ) {
251 $msg .= "\nTo be removed in $throw_version." if $throw_version;
253 # passing this on to warn() should deal properly with verbosity issues
254 $self->warn($msg);
258 =head2 stack_trace_dump
260 Title : stack_trace_dump
261 Usage :
262 Function:
263 Example :
264 Returns :
265 Args :
268 =cut
270 sub stack_trace_dump{
271 my ($self) = @_;
273 my @stack = $self->stack_trace();
275 shift @stack;
276 shift @stack;
277 shift @stack;
279 my $out;
280 my ($module,$function,$file,$position);
283 foreach my $stack ( @stack) {
284 ($module,$file,$position,$function) = @{$stack};
285 $out .= "STACK $function $file:$position\n";
288 return $out;
292 =head2 stack_trace
294 Title : stack_trace
295 Usage : @stack_array_ref= $self->stack_trace
296 Function: gives an array to a reference of arrays with stack trace info
297 each coming from the caller(stack_number) call
298 Returns : array containing a reference of arrays
299 Args : none
302 =cut
304 sub stack_trace{
305 my ($self) = @_;
307 my $i = 0;
308 my @out = ();
309 my $prev = [];
310 while( my @call = caller($i++)) {
311 # major annoyance that caller puts caller context as
312 # function name. Hence some monkeying around...
313 $prev->[3] = $call[3];
314 push(@out,$prev);
315 $prev = \@call;
317 $prev->[3] = 'toplevel';
318 push(@out,$prev);
319 return @out;
323 =head2 _rearrange
325 Usage : $object->_rearrange( array_ref, list_of_arguments)
326 Purpose : Rearranges named parameters to requested order.
327 Example : $self->_rearrange([qw(SEQUENCE ID DESC)],@param);
328 : Where @param = (-sequence => $s,
329 : -desc => $d,
330 : -id => $i);
331 Returns : @params - an array of parameters in the requested order.
332 : The above example would return ($s, $i, $d).
333 : Unspecified parameters will return undef. For example, if
334 : @param = (-sequence => $s);
335 : the above _rearrange call would return ($s, undef, undef)
336 Argument : $order : a reference to an array which describes the desired
337 : order of the named parameters.
338 : @param : an array of parameters, either as a list (in
339 : which case the function simply returns the list),
340 : or as an associative array with hyphenated tags
341 : (in which case the function sorts the values
342 : according to @{$order} and returns that new array.)
343 : The tags can be upper, lower, or mixed case
344 : but they must start with a hyphen (at least the
345 : first one should be hyphenated.)
346 Source : This function was taken from CGI.pm, written by Dr. Lincoln
347 : Stein, and adapted for use in Bio::Seq by Richard Resnick and
348 : then adapted for use in Bio::Root::Object.pm by Steve Chervitz,
349 : then migrated into Bio::Root::RootI.pm by Ewan Birney.
350 Comments :
351 : Uppercase tags are the norm,
352 : (SAC)
353 : This method may not be appropriate for method calls that are
354 : within in an inner loop if efficiency is a concern.
356 : Parameters can be specified using any of these formats:
357 : @param = (-name=>'me', -color=>'blue');
358 : @param = (-NAME=>'me', -COLOR=>'blue');
359 : @param = (-Name=>'me', -Color=>'blue');
360 : @param = ('me', 'blue');
361 : A leading hyphenated argument is used by this function to
362 : indicate that named parameters are being used.
363 : Therefore, the ('me', 'blue') list will be returned as-is.
365 : Note that Perl will confuse unquoted, hyphenated tags as
366 : function calls if there is a function of the same name
367 : in the current namespace:
368 : -name => 'foo' is interpreted as -&name => 'foo'
370 : For ultimate safety, put single quotes around the tag:
371 : ('-name'=>'me', '-color' =>'blue');
372 : This can be a bit cumbersome and I find not as readable
373 : as using all uppercase, which is also fairly safe:
374 : (-NAME=>'me', -COLOR =>'blue');
376 : Personal note (SAC): I have found all uppercase tags to
377 : be more manageable: it involves less single-quoting,
378 : the key names stand out better, and there are no method naming
379 : conflicts.
380 : The drawbacks are that it's not as easy to type as lowercase,
381 : and lots of uppercase can be hard to read.
383 : Regardless of the style, it greatly helps to line
384 : the parameters up vertically for long/complex lists.
386 : Note that if @param is a single string that happens to start with
387 : a dash, it will be treated as a hash key and probably fail to
388 : match anything in the array_ref, so not be returned as normally
389 : happens when @param is a simple list and not an associative array.
391 =cut
393 sub _rearrange {
394 my ($self, $order, @args) = @_;
396 return @args unless $args[0] && $args[0] =~ /^\-/;
398 push @args, undef unless $#args % 2;
400 my %param;
401 for( my $i = 0; $i < @args; $i += 2 ) {
402 (my $key = $args[$i]) =~ tr/a-z\055/A-Z/d; #deletes all dashes!
403 $param{$key} = $args[$i+1];
405 return @param{map uc, @$order};
408 =head2 _set_from_args
410 Usage : $object->_set_from_args(\%args, -methods => \@methods)
411 Purpose : Takes a hash of user-supplied args whose keys match method names,
412 : and calls the method supplying it the corresponding value.
413 Example : $self->_set_from_args(\%args, -methods => [qw(sequence id desc)]);
414 : Where %args = (-sequence => $s,
415 : -description => $d,
416 : -ID => $i);
418 : the above _set_from_args calls the following methods:
419 : $self->sequence($s);
420 : $self->id($i);
421 : ( $self->description($i) is not called because 'description' wasn't
422 : one of the given methods )
423 Argument : \%args | \@args : a hash ref or associative array ref of arguments
424 : where keys are any-case strings corresponding to
425 : method names but optionally prefixed with
426 : hyphens, and values are the values the method
427 : should be supplied. If keys contain internal
428 : hyphens (eg. to separate multi-word args) they
429 : are converted to underscores, since method names
430 : cannot contain dashes.
431 : -methods => [] : (optional) only call methods with names in this
432 : array ref. Can instead supply a hash ref where
433 : keys are method names (of real existing methods
434 : unless -create is in effect) and values are array
435 : refs of synonyms to allow access to the method
436 : using synonyms. If there is only one synonym it
437 : can be supplied as a string instead of a single-
438 : element array ref
439 : -force => bool : (optional, default 0) call methods that don't
440 : seem to exist, ie. let AUTOLOAD handle them
441 : -create => bool : (optional, default 0) when a method doesn't
442 : exist, create it as a simple getter/setter
443 : (combined with -methods it would create all the
444 : supplied methods that didn't exist, even if not
445 : mentioned in the supplied %args)
446 : -code => '' | {}: (optional) when creating methods use the supplied
447 : code (a string which will be evaulated as a sub).
448 : The default code is a simple get/setter.
449 : Alternatively you can supply a hash ref where
450 : the keys are method names and the values are
451 : code strings. The variable '$method' will be
452 : available at evaluation time, so can be used in
453 : your code strings. Beware that the strict pragma
454 : will be in effect.
455 : -case_sensitive => bool : require case sensitivity on the part of
456 : user (ie. a() and A() are two different
457 : methods and the user must be careful
458 : which they use).
459 Comments :
460 : The \%args argument will usually be the args received during new()
461 : from the user. The user is allowed to get the case wrong, include
462 : 0 or more than one hyphens as a prefix, and to include hyphens as
463 : multi-word arg separators: '--an-arg' => 1, -an_arg => 1 and
464 : An_Arg => 1 are all equivalent, calling an_arg(1). However, in
465 : documentation users should only be told to use the standard form
466 : -an_arg to avoid confusion. A possible exception to this is a
467 : wrapper module where '--an-arg' is what the user is used to
468 : supplying to the program being wrapped.
470 : Another issue with wrapper modules is that there may be an
471 : argument that has meaning both to Bioperl and to the program, eg.
472 : -verbose. The recommended way of dealing with this is to leave
473 : -verbose to set the Bioperl verbosity whilst requesting users use
474 : an invented -program_verbose (or similar) to set the program
475 : verbosity. This can be resolved back with
476 : Bio::Tools::Run::WrapperBase's _setparams() method and code along
477 : the lines of:
478 : my %methods = map { $_ => $_ } @LIST_OF_ALL_ALLOWED_PROGRAM_ARGS
479 : delete $methods{'verbose'};
480 : $methods{'program_verbose'} = 'verbose';
481 : my $param_string = $self->_setparams(-methods => \%methods);
482 : system("$exe $param_string");
484 =cut
486 sub _set_from_args {
487 my ($self, $args, @own_args) = @_;
488 $self->throw("a hash/array ref of arguments must be supplied") unless ref($args);
490 my ($methods, $force, $create, $code, $case);
491 if (@own_args) {
492 ($methods, $force, $create, $code, $case) =
493 $self->_rearrange([qw(METHODS
494 FORCE
495 CREATE
496 CODE
497 CASE_SENSITIVE)], @own_args);
499 my $default_code = 'my $self = shift;
500 if (@_) { $self->{\'_\'.$method} = shift }
501 return $self->{\'_\'.$method};';
503 my %method_names = ();
504 my %syns = ();
505 if ($methods) {
506 my @names;
507 if (ref($methods) eq 'HASH') {
508 @names = keys %{$methods};
509 %syns = %{$methods};
511 else {
512 @names = @{$methods};
513 %syns = map { $_ => $_ } @names;
515 %method_names = map { $case ? $_ : lc($_) => $_ } @names;
518 # deal with hyphens
519 my %orig_args = ref($args) eq 'HASH' ? %{$args} : @{$args};
520 my %args;
521 while (my ($method, $value) = each %orig_args) {
522 $method =~ s/^-+//;
523 $method =~ s/-/_/g;
524 $args{$method} = $value;
527 # create non-existing methods on request
528 if ($create) {
529 unless ($methods) {
530 %syns = map { $_ => $case ? $_ : lc($_) } keys %args;
533 foreach my $method (keys %syns) {
534 $self->can($method) && next;
536 my $string = $code || $default_code;
537 if (ref($code) && ref($code) eq 'HASH') {
538 $string = $code->{$method} || $default_code;
541 my $sub = eval "sub { $string }";
542 $self->throw("Compilation error for $method : $@") if $@;
544 no strict 'refs';
545 *{ref($self).'::'.$method} = $sub;
549 # create synonyms of existing methods
550 while (my ($method, $syn_ref) = each %syns) {
551 my $method_ref = $self->can($method) || next;
553 foreach my $syn (@{ ref($syn_ref) ? $syn_ref : [$syn_ref] }) {
554 next if $syn eq $method;
555 $method_names{$case ? $syn : lc($syn)} = $syn;
556 next if $self->can($syn);
557 no strict 'refs';
558 *{ref($self).'::'.$syn} = $method_ref;
562 # set values for methods
563 while (my ($method, $value) = each %args) {
564 $method = $method_names{$case ? $method : lc($method)} || ($methods ? next : $method);
565 $self->can($method) || next unless $force;
566 $self->$method($value);
571 =head2 _rearrange_old
573 =cut
575 #----------------'
576 sub _rearrange_old {
577 #----------------
578 my($self,$order,@param) = @_;
580 # JGRG -- This is wrong, because we don't want
581 # to assign empty string to anything, and this
582 # code is actually returning an array 1 less
583 # than the length of @param:
585 ## If there are no parameters, we simply wish to return
586 ## an empty array which is the size of the @{$order} array.
587 #return ('') x $#{$order} unless @param;
589 # ...all we need to do is return an empty array:
590 # return unless @param;
592 # If we've got parameters, we need to check to see whether
593 # they are named or simply listed. If they are listed, we
594 # can just return them.
596 # The mod test fixes bug where a single string parameter beginning with '-' gets lost.
597 # This tends to happen in error messages such as: $obj->throw("-id not defined")
598 return @param unless (defined($param[0]) && $param[0]=~/^-/o && ($#param % 2));
600 # Tester
601 # print "\n_rearrange() named parameters:\n";
602 # my $i; for ($i=0;$i<@param;$i+=2) { printf "%20s => %s\n", $param[$i],$param[$i+1]; }; <STDIN>;
604 # Now we've got to do some work on the named parameters.
605 # The next few lines strip out the '-' characters which
606 # preceed the keys, and capitalizes them.
607 for (my $i=0;$i<@param;$i+=2) {
608 $param[$i]=~s/^\-//;
609 $param[$i]=~tr/a-z/A-Z/;
612 # Now we'll convert the @params variable into an associative array.
613 # local($^W) = 0; # prevent "odd number of elements" warning with -w.
614 my(%param) = @param;
616 # my(@return_array);
618 # What we intend to do is loop through the @{$order} variable,
619 # and for each value, we use that as a key into our associative
620 # array, pushing the value at that key onto our return array.
621 # my($key);
623 #foreach (@{$order}) {
624 # my($value) = $param{$key};
625 # delete $param{$key};
626 #push(@return_array,$param{$_});
629 return @param{@{$order}};
631 # print "\n_rearrange() after processing:\n";
632 # my $i; for ($i=0;$i<@return_array;$i++) { printf "%20s => %s\n", ${$order}[$i], $return_array[$i]; } <STDIN>;
634 # return @return_array;
637 =head2 _register_for_cleanup
639 Title : _register_for_cleanup
640 Usage : -- internal --
641 Function: Register a method to be called at DESTROY time. This is useful
642 and sometimes essential in the case of multiple inheritance for
643 classes coming second in the sequence of inheritance.
644 Returns :
645 Args : a code reference
647 The code reference will be invoked with the object as the first
648 argument, as per a method. You may register an unlimited number of
649 cleanup methods.
651 =cut
653 sub _register_for_cleanup {
654 my ($self,$method) = @_;
655 $self->throw_not_implemented();
658 =head2 _unregister_for_cleanup
660 Title : _unregister_for_cleanup
661 Usage : -- internal --
662 Function: Remove a method that has previously been registered to be called
663 at DESTROY time. If called with a method to be called at DESTROY time.
664 Has no effect if the code reference has not previously been registered.
665 Returns : nothing
666 Args : a code reference
668 =cut
670 sub _unregister_for_cleanup {
671 my ($self,$method) = @_;
672 $self->throw_not_implemented();
675 =head2 _cleanup_methods
677 Title : _cleanup_methods
678 Usage : -- internal --
679 Function: Return current list of registered cleanup methods.
680 Returns : list of coderefs
681 Args : none
683 =cut
685 sub _cleanup_methods {
686 my $self = shift;
687 unless ( $ENV{'BIOPERLDEBUG'} || $self->verbose > 0 ) {
688 carp("Use of Bio::Root::RootI is deprecated. Please use Bio::Root::Root instead");
690 return;
693 =head2 throw_not_implemented
695 Purpose : Throws a Bio::Root::NotImplemented exception.
696 Intended for use in the method definitions of
697 abstract interface modules where methods are defined
698 but are intended to be overridden by subclasses.
699 Usage : $object->throw_not_implemented();
700 Example : sub method_foo {
701 $self = shift;
702 $self->throw_not_implemented();
704 Returns : n/a
705 Args : n/a
706 Throws : A Bio::Root::NotImplemented exception.
707 The message of the exception contains
708 - the name of the method
709 - the name of the interface
710 - the name of the implementing class
712 If this object has a throw() method, $self->throw will be used.
713 If the object doesn't have a throw() method,
714 Carp::confess() will be used.
717 =cut
721 sub throw_not_implemented {
722 my $self = shift;
724 # Bio::Root::Root::throw() knows how to check for Error.pm and will
725 # throw an Error-derived object of the specified class (Bio::Root::NotImplemented),
726 # which is defined in Bio::Root::Exception.
727 # If Error.pm is not available, the name of the class is just included in the
728 # error message.
730 my $message = $self->_not_implemented_msg;
732 if ( $self->can('throw') ) {
733 my @args;
734 if ( $self->isa('Bio::Root::Root') ) {
735 # Use Root::throw() hash-based arguments instead of RootI::throw()
736 # single string argument whenever possible
737 @args = ( -text => $message, -class => 'Bio::Root::NotImplemented' );
738 } else {
739 @args = ( $message );
741 $self->throw(@args);
743 } else {
744 confess $message;
749 =head2 warn_not_implemented
751 Purpose : Generates a warning that a method has not been implemented.
752 Intended for use in the method definitions of
753 abstract interface modules where methods are defined
754 but are intended to be overridden by subclasses.
755 Generally, throw_not_implemented() should be used,
756 but warn_not_implemented() may be used if the method isn't
757 considered essential and convenient no-op behavior can be
758 provided within the interface.
759 Usage : $object->warn_not_implemented( method-name-string );
760 Example : $self->warn_not_implemented( "get_foobar" );
761 Returns : Calls $self->warn on this object, if available.
762 If the object doesn't have a warn() method,
763 Carp::carp() will be used.
764 Args : n/a
767 =cut
771 sub warn_not_implemented {
772 my $self = shift;
773 my $message = $self->_not_implemented_msg;
774 if( $self->can('warn') ) {
775 $self->warn( $message );
776 }else {
777 carp $message ;
781 =head2 _not_implemented_msg
783 Unify 'not implemented' message. -Juguang
784 =cut
786 sub _not_implemented_msg {
787 my $self = shift;
788 my $package = ref $self;
789 my $meth = (caller(2))[3];
790 my $msg =<<EOD_NOT_IMP;
791 Abstract method \"$meth\" is not implemented by package $package.
792 This is not your fault - author of $package should be blamed!
793 EOD_NOT_IMP
794 return $msg;