1 package Bio
::Root
::RootI
;
3 use Carp
'confess','carp';
7 # any bioperl or bioperl compliant object is a RootI
10 $obj->throw("This is an exception");
13 $obj->throw("This is catching an exception");
17 print "Caught exception";
22 # Using throw_not_implemented() within a RootI-based interface module:
25 use base qw(Bio::Root::RootI);
29 $self->throw_not_implemented;
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
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
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
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
76 use vars
qw($DEBUG $ID $VERBOSITY);
78 $ID = 'Bio::Root::RootI';
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
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
111 Args : A string giving a descriptive error message
117 my ($self,$string) = @_;
119 my $std = $self->stack_trace_dump();
121 my $out = "\n-------------------- EXCEPTION --------------------\n"
122 . "MSG: " . $string . "\n"
123 . $std."-------------------------------------------\n";
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
138 Args : string (the warning message)
143 my ($self,$string) = @_;
145 my $verbose = $self->verbose;
147 my $header = "\n--------------------- WARNING ---------------------\nMSG: ";
148 my $footer = "---------------------------------------------------\n";
151 $self->throw($string);
153 elsif ($verbose <= -1) {
156 elsif ($verbose == 1) {
157 CORE::warn $header, $string, "\n", $self->stack_trace_dump, $footer;
161 CORE::warn $header, $string, "\n", $footer;
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",
172 Function: Prints a message about deprecation unless verbose is < 0
173 (which means be quiet)
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:
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:
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
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.).
217 my $class = ref $self || $self;
218 my $class_version = do {
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 ) {
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
258 =head2 stack_trace_dump
260 Title : stack_trace_dump
270 sub stack_trace_dump
{
273 my @stack = $self->stack_trace();
280 my ($module,$function,$file,$position);
283 foreach my $stack ( @stack) {
284 ($module,$file,$position,$function) = @
{$stack};
285 $out .= "STACK $function $file:$position\n";
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
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];
317 $prev->[3] = 'toplevel';
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,
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.
351 : Uppercase tags are the norm,
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
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.
394 my ($self, $order, @args) = @_;
396 return @args unless $args[0] && $args[0] =~ /^\-/;
398 push @args, undef unless $#args % 2;
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,
418 : the above _set_from_args calls the following methods:
419 : $self->sequence($s);
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-
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
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
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
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");
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);
492 ($methods, $force, $create, $code, $case) =
493 $self->_rearrange([qw(METHODS
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 = ();
507 if (ref($methods) eq 'HASH') {
508 @names = keys %{$methods};
512 @names = @
{$methods};
513 %syns = map { $_ => $_ } @names;
515 %method_names = map { $case ?
$_ : lc($_) => $_ } @names;
519 my %orig_args = ref($args) eq 'HASH' ?
%{$args} : @
{$args};
521 while (my ($method, $value) = each %orig_args) {
524 $args{$method} = $value;
527 # create non-existing methods on request
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 $@
;
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);
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
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));
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) {
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.
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.
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.
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
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.
666 Args : a code reference
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
685 sub _cleanup_methods
{
687 unless ( $ENV{'BIOPERLDEBUG'} || $self->verbose > 0 ) {
688 carp
("Use of Bio::Root::RootI is deprecated. Please use Bio::Root::Root instead");
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 {
702 $self->throw_not_implemented();
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.
721 sub throw_not_implemented
{
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
730 my $message = $self->_not_implemented_msg;
732 if ( $self->can('throw') ) {
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' );
739 @args = ( $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.
771 sub warn_not_implemented
{
773 my $message = $self->_not_implemented_msg;
774 if( $self->can('warn') ) {
775 $self->warn( $message );
781 =head2 _not_implemented_msg
783 Unify 'not implemented' message. -Juguang
786 sub _not_implemented_msg
{
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!