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
178 Notes : This is deprecated. Use Carp::carp to warn about a
179 deprecated method. Just remove the method when it comes to
180 error. If you really want to throw an error insyead of
181 removing, use Carp::croak.
183 The irony of deprecating deprecated() is not lost on us.
184 We hope you also find it more funny that frustrating.
191 carp "deprecated() is deprecated. Just use Carp::carp to warn.";
193 my ($msg, $version, $warn_version, $throw_version) =
194 $self->_rearrange([qw(MESSAGE VERSION WARN_VERSION THROW_VERSION)], @_);
195 # below default insinuates we're deprecating a method and not a full module
196 # but it's the most common use case
197 $msg ||= "Use of ".(caller(1))[3]."() is deprecated.";
199 ## Never documented, but if there is no version information, just
201 if (! defined($version) && ! defined($warn_version)
202 && ! defined($throw_version)) {
207 my $class = ref $self || $self;
208 my $class_version = do {
210 ${"${class}::VERSION"}
213 if( $class_version && $class_version =~ /set by/ ) {
214 $class_version = 0.0001;
217 $throw_version ||= $version;
218 $warn_version ||= $class_version;
220 $throw_version =~ s/_//g;
221 $warn_version =~ s/_//g;
223 for my $v ( $warn_version, $throw_version) {
224 no warnings
'numeric';
225 $self->throw("Version must be numerical, such as 1.006000 for v1.6.0, not $v")
226 unless !defined $v || $v + 0 == $v;
229 if( $throw_version && $class_version && $class_version >= $throw_version ) {
232 elsif( $warn_version && $class_version && $class_version >= $warn_version ) {
234 $msg .= "\nTo be removed in $throw_version." if $throw_version;
236 # passing this on to warn() should deal properly with verbosity issues
241 =head2 stack_trace_dump
243 Title : stack_trace_dump
253 sub stack_trace_dump
{
256 my @stack = $self->stack_trace();
263 my ($module,$function,$file,$position);
266 foreach my $stack ( @stack) {
267 ($module,$file,$position,$function) = @
{$stack};
268 $out .= "STACK $function $file:$position\n";
278 Usage : @stack_array_ref= $self->stack_trace
279 Function: gives an array to a reference of arrays with stack trace info
280 each coming from the caller(stack_number) call
281 Returns : array containing a reference of arrays
293 while( my @call = caller($i++)) {
294 # major annoyance that caller puts caller context as
295 # function name. Hence some monkeying around...
296 $prev->[3] = $call[3];
300 $prev->[3] = 'toplevel';
308 Usage : $object->_rearrange( array_ref, list_of_arguments)
309 Purpose : Rearranges named parameters to requested order.
310 Example : $self->_rearrange([qw(SEQUENCE ID DESC)],@param);
311 : Where @param = (-sequence => $s,
314 Returns : @params - an array of parameters in the requested order.
315 : The above example would return ($s, $i, $d).
316 : Unspecified parameters will return undef. For example, if
317 : @param = (-sequence => $s);
318 : the above _rearrange call would return ($s, undef, undef)
319 Argument : $order : a reference to an array which describes the desired
320 : order of the named parameters.
321 : @param : an array of parameters, either as a list (in
322 : which case the function simply returns the list),
323 : or as an associative array with hyphenated tags
324 : (in which case the function sorts the values
325 : according to @{$order} and returns that new array.)
326 : The tags can be upper, lower, or mixed case
327 : but they must start with a hyphen (at least the
328 : first one should be hyphenated.)
329 Source : This function was taken from CGI.pm, written by Dr. Lincoln
330 : Stein, and adapted for use in Bio::Seq by Richard Resnick and
331 : then adapted for use in Bio::Root::Object.pm by Steve Chervitz,
332 : then migrated into Bio::Root::RootI.pm by Ewan Birney.
334 : Uppercase tags are the norm,
336 : This method may not be appropriate for method calls that are
337 : within in an inner loop if efficiency is a concern.
339 : Parameters can be specified using any of these formats:
340 : @param = (-name=>'me', -color=>'blue');
341 : @param = (-NAME=>'me', -COLOR=>'blue');
342 : @param = (-Name=>'me', -Color=>'blue');
343 : @param = ('me', 'blue');
344 : A leading hyphenated argument is used by this function to
345 : indicate that named parameters are being used.
346 : Therefore, the ('me', 'blue') list will be returned as-is.
348 : Note that Perl will confuse unquoted, hyphenated tags as
349 : function calls if there is a function of the same name
350 : in the current namespace:
351 : -name => 'foo' is interpreted as -&name => 'foo'
353 : For ultimate safety, put single quotes around the tag:
354 : ('-name'=>'me', '-color' =>'blue');
355 : This can be a bit cumbersome and I find not as readable
356 : as using all uppercase, which is also fairly safe:
357 : (-NAME=>'me', -COLOR =>'blue');
359 : Personal note (SAC): I have found all uppercase tags to
360 : be more manageable: it involves less single-quoting,
361 : the key names stand out better, and there are no method naming
363 : The drawbacks are that it's not as easy to type as lowercase,
364 : and lots of uppercase can be hard to read.
366 : Regardless of the style, it greatly helps to line
367 : the parameters up vertically for long/complex lists.
369 : Note that if @param is a single string that happens to start with
370 : a dash, it will be treated as a hash key and probably fail to
371 : match anything in the array_ref, so not be returned as normally
372 : happens when @param is a simple list and not an associative array.
377 my ($self, $order, @args) = @_;
379 return @args unless $args[0] && $args[0] =~ /^\-/;
381 push @args, undef unless $#args % 2;
384 for( my $i = 0; $i < @args; $i += 2 ) {
385 (my $key = $args[$i]) =~ tr/a-z\055/A-Z/d; #deletes all dashes!
386 $param{$key} = $args[$i+1];
388 return @param{map uc, @
$order};
391 =head2 _set_from_args
393 Usage : $object->_set_from_args(\%args, -methods => \@methods)
394 Purpose : Takes a hash of user-supplied args whose keys match method names,
395 : and calls the method supplying it the corresponding value.
396 Example : $self->_set_from_args(\%args, -methods => [qw(sequence id desc)]);
397 : Where %args = (-sequence => $s,
398 : -description => $d,
401 : the above _set_from_args calls the following methods:
402 : $self->sequence($s);
404 : ( $self->description($i) is not called because 'description' wasn't
405 : one of the given methods )
406 Argument : \%args | \@args : a hash ref or associative array ref of arguments
407 : where keys are any-case strings corresponding to
408 : method names but optionally prefixed with
409 : hyphens, and values are the values the method
410 : should be supplied. If keys contain internal
411 : hyphens (eg. to separate multi-word args) they
412 : are converted to underscores, since method names
413 : cannot contain dashes.
414 : -methods => [] : (optional) only call methods with names in this
415 : array ref. Can instead supply a hash ref where
416 : keys are method names (of real existing methods
417 : unless -create is in effect) and values are array
418 : refs of synonyms to allow access to the method
419 : using synonyms. If there is only one synonym it
420 : can be supplied as a string instead of a single-
422 : -force => bool : (optional, default 0) call methods that don't
423 : seem to exist, ie. let AUTOLOAD handle them
424 : -create => bool : (optional, default 0) when a method doesn't
425 : exist, create it as a simple getter/setter
426 : (combined with -methods it would create all the
427 : supplied methods that didn't exist, even if not
428 : mentioned in the supplied %args)
429 : -code => '' | {}: (optional) when creating methods use the supplied
430 : code (a string which will be evaulated as a sub).
431 : The default code is a simple get/setter.
432 : Alternatively you can supply a hash ref where
433 : the keys are method names and the values are
434 : code strings. The variable '$method' will be
435 : available at evaluation time, so can be used in
436 : your code strings. Beware that the strict pragma
438 : -case_sensitive => bool : require case sensitivity on the part of
439 : user (ie. a() and A() are two different
440 : methods and the user must be careful
443 : The \%args argument will usually be the args received during new()
444 : from the user. The user is allowed to get the case wrong, include
445 : 0 or more than one hyphens as a prefix, and to include hyphens as
446 : multi-word arg separators: '--an-arg' => 1, -an_arg => 1 and
447 : An_Arg => 1 are all equivalent, calling an_arg(1). However, in
448 : documentation users should only be told to use the standard form
449 : -an_arg to avoid confusion. A possible exception to this is a
450 : wrapper module where '--an-arg' is what the user is used to
451 : supplying to the program being wrapped.
453 : Another issue with wrapper modules is that there may be an
454 : argument that has meaning both to Bioperl and to the program, eg.
455 : -verbose. The recommended way of dealing with this is to leave
456 : -verbose to set the Bioperl verbosity whilst requesting users use
457 : an invented -program_verbose (or similar) to set the program
458 : verbosity. This can be resolved back with
459 : Bio::Tools::Run::WrapperBase's _setparams() method and code along
461 : my %methods = map { $_ => $_ } @LIST_OF_ALL_ALLOWED_PROGRAM_ARGS
462 : delete $methods{'verbose'};
463 : $methods{'program_verbose'} = 'verbose';
464 : my $param_string = $self->_setparams(-methods => \%methods);
465 : system("$exe $param_string");
470 my ($self, $args, @own_args) = @_;
471 $self->throw("a hash/array ref of arguments must be supplied") unless ref($args);
473 my ($methods, $force, $create, $code, $case);
475 ($methods, $force, $create, $code, $case) =
476 $self->_rearrange([qw(METHODS
480 CASE_SENSITIVE)], @own_args);
482 my $default_code = 'my $self = shift;
483 if (@_) { $self->{\'_\'.$method} = shift }
484 return $self->{\'_\'.$method};';
486 my %method_names = ();
490 if (ref($methods) eq 'HASH') {
491 @names = keys %{$methods};
495 @names = @
{$methods};
496 %syns = map { $_ => $_ } @names;
498 %method_names = map { $case ?
$_ : lc($_) => $_ } @names;
502 my %orig_args = ref($args) eq 'HASH' ?
%{$args} : @
{$args};
504 while (my ($method, $value) = each %orig_args) {
507 $args{$method} = $value;
510 # create non-existing methods on request
513 %syns = map { $_ => $case ?
$_ : lc($_) } keys %args;
516 foreach my $method (keys %syns) {
517 $self->can($method) && next;
519 my $string = $code || $default_code;
520 if (ref($code) && ref($code) eq 'HASH') {
521 $string = $code->{$method} || $default_code;
524 my $sub = eval "sub { $string }";
525 $self->throw("Compilation error for $method : $@") if $@
;
528 *{ref($self).'::'.$method} = $sub;
532 # create synonyms of existing methods
533 while (my ($method, $syn_ref) = each %syns) {
534 my $method_ref = $self->can($method) || next;
536 foreach my $syn (@
{ ref($syn_ref) ?
$syn_ref : [$syn_ref] }) {
537 next if $syn eq $method;
538 $method_names{$case ?
$syn : lc($syn)} = $syn;
539 next if $self->can($syn);
541 *{ref($self).'::'.$syn} = $method_ref;
545 # set values for methods
546 while (my ($method, $value) = each %args) {
547 $method = $method_names{$case ?
$method : lc($method)} || ($methods ?
next : $method);
548 $self->can($method) || next unless $force;
549 $self->$method($value);
554 =head2 _rearrange_old
561 my($self,$order,@param) = @_;
563 # JGRG -- This is wrong, because we don't want
564 # to assign empty string to anything, and this
565 # code is actually returning an array 1 less
566 # than the length of @param:
568 ## If there are no parameters, we simply wish to return
569 ## an empty array which is the size of the @{$order} array.
570 #return ('') x $#{$order} unless @param;
572 # ...all we need to do is return an empty array:
573 # return unless @param;
575 # If we've got parameters, we need to check to see whether
576 # they are named or simply listed. If they are listed, we
577 # can just return them.
579 # The mod test fixes bug where a single string parameter beginning with '-' gets lost.
580 # This tends to happen in error messages such as: $obj->throw("-id not defined")
581 return @param unless (defined($param[0]) && $param[0]=~/^-/o && ($#param % 2));
584 # print "\n_rearrange() named parameters:\n";
585 # my $i; for ($i=0;$i<@param;$i+=2) { printf "%20s => %s\n", $param[$i],$param[$i+1]; }; <STDIN>;
587 # Now we've got to do some work on the named parameters.
588 # The next few lines strip out the '-' characters which
589 # preceed the keys, and capitalizes them.
590 for (my $i=0;$i<@param;$i+=2) {
592 $param[$i]=~tr/a-z/A-Z/;
595 # Now we'll convert the @params variable into an associative array.
596 # local($^W) = 0; # prevent "odd number of elements" warning with -w.
601 # What we intend to do is loop through the @{$order} variable,
602 # and for each value, we use that as a key into our associative
603 # array, pushing the value at that key onto our return array.
606 #foreach (@{$order}) {
607 # my($value) = $param{$key};
608 # delete $param{$key};
609 #push(@return_array,$param{$_});
612 return @param{@
{$order}};
614 # print "\n_rearrange() after processing:\n";
615 # my $i; for ($i=0;$i<@return_array;$i++) { printf "%20s => %s\n", ${$order}[$i], $return_array[$i]; } <STDIN>;
617 # return @return_array;
620 =head2 _register_for_cleanup
622 Title : _register_for_cleanup
623 Usage : -- internal --
624 Function: Register a method to be called at DESTROY time. This is useful
625 and sometimes essential in the case of multiple inheritance for
626 classes coming second in the sequence of inheritance.
628 Args : a code reference
630 The code reference will be invoked with the object as the first
631 argument, as per a method. You may register an unlimited number of
636 sub _register_for_cleanup
{
637 my ($self,$method) = @_;
638 $self->throw_not_implemented();
641 =head2 _unregister_for_cleanup
643 Title : _unregister_for_cleanup
644 Usage : -- internal --
645 Function: Remove a method that has previously been registered to be called
646 at DESTROY time. If called with a method to be called at DESTROY time.
647 Has no effect if the code reference has not previously been registered.
649 Args : a code reference
653 sub _unregister_for_cleanup
{
654 my ($self,$method) = @_;
655 $self->throw_not_implemented();
658 =head2 _cleanup_methods
660 Title : _cleanup_methods
661 Usage : -- internal --
662 Function: Return current list of registered cleanup methods.
663 Returns : list of coderefs
668 sub _cleanup_methods
{
670 unless ( $ENV{'BIOPERLDEBUG'} || $self->verbose > 0 ) {
671 carp
("Use of Bio::Root::RootI is deprecated. Please use Bio::Root::Root instead");
676 =head2 throw_not_implemented
678 Purpose : Throws a Bio::Root::NotImplemented exception.
679 Intended for use in the method definitions of
680 abstract interface modules where methods are defined
681 but are intended to be overridden by subclasses.
682 Usage : $object->throw_not_implemented();
683 Example : sub method_foo {
685 $self->throw_not_implemented();
689 Throws : A Bio::Root::NotImplemented exception.
690 The message of the exception contains
691 - the name of the method
692 - the name of the interface
693 - the name of the implementing class
695 If this object has a throw() method, $self->throw will be used.
696 If the object doesn't have a throw() method,
697 Carp::confess() will be used.
704 sub throw_not_implemented
{
707 # Bio::Root::Root::throw() knows how to check for Error.pm and will
708 # throw an Error-derived object of the specified class (Bio::Root::NotImplemented),
709 # which is defined in Bio::Root::Exception.
710 # If Error.pm is not available, the name of the class is just included in the
713 my $message = $self->_not_implemented_msg;
715 if ( $self->can('throw') ) {
717 if ( $self->isa('Bio::Root::Root') ) {
718 # Use Root::throw() hash-based arguments instead of RootI::throw()
719 # single string argument whenever possible
720 @args = ( -text
=> $message, -class => 'Bio::Root::NotImplemented' );
722 @args = ( $message );
732 =head2 warn_not_implemented
734 Purpose : Generates a warning that a method has not been implemented.
735 Intended for use in the method definitions of
736 abstract interface modules where methods are defined
737 but are intended to be overridden by subclasses.
738 Generally, throw_not_implemented() should be used,
739 but warn_not_implemented() may be used if the method isn't
740 considered essential and convenient no-op behavior can be
741 provided within the interface.
742 Usage : $object->warn_not_implemented( method-name-string );
743 Example : $self->warn_not_implemented( "get_foobar" );
744 Returns : Calls $self->warn on this object, if available.
745 If the object doesn't have a warn() method,
746 Carp::carp() will be used.
754 sub warn_not_implemented
{
756 my $message = $self->_not_implemented_msg;
757 if( $self->can('warn') ) {
758 $self->warn( $message );
764 =head2 _not_implemented_msg
766 Unify 'not implemented' message. -Juguang
769 sub _not_implemented_msg
{
771 my $package = ref $self;
772 my $meth = (caller(2))[3];
773 my $msg =<<EOD_NOT_IMP;
774 Abstract method \"$meth\" is not implemented by package $package.
775 This is not your fault - author of $package should be blamed!