load dependent plugins earlier, so we can detect compile errors sooner (RT#88563)
[p5sagit/Devel-REPL.git] / lib / Devel / REPL / Plugin / CompletionDriver / Methods.pm
1 use strict;
2 use warnings;
3 package Devel::REPL::Plugin::CompletionDriver::Methods;
4 use Devel::REPL::Plugin;
5 use Devel::REPL::Plugin::Completion;    # die early if cannot load
6 use namespace::autoclean;
7
8 sub BEFORE_PLUGIN {
9     my $self = shift;
10     for (qw/Completion FindVariable/) {
11         $self->load_plugin($_);
12     }
13 }
14
15 around complete => sub {
16   my $orig = shift;
17   my ($self, $text, $document) = @_;
18
19   my $last = $self->last_ppi_element($document);
20   my $incomplete = '';
21
22   # handle an incomplete method name, and back up to the ->
23   if ($last->isa('PPI::Token::Word')) {
24       my $previous = $last->sprevious_sibling
25         or return $orig->(@_);
26       $previous->isa('PPI::Token::Operator') && $previous->content eq '->'
27         or return $orig->(@_);
28       $incomplete = $last->content;
29       $last = $previous;
30   }
31
32   # require a -> here
33   return $orig->(@_)
34     unless $last->isa('PPI::Token::Operator')
35         && $last->content eq '->';
36
37   # ..which is preceded by a word (class name)
38   my $previous = $last->sprevious_sibling
39     or return $orig->(@_);
40   $previous->isa('PPI::Token::Word') || $previous->isa('PPI::Token::Symbol')
41     or return $orig->(@_);
42   my $class;
43
44   # we have a variable, need to look up its class
45   if ($previous->isa('PPI::Token::Symbol')) {
46     my $object_ref = $self->find_variable($previous->content)
47       or return $orig->(@_);
48     $class = blessed($$object_ref)
49       or return $orig->(@_);
50   }
51   else  {
52     $class = $previous->content;
53   }
54
55   # now we have $class->$incomplete
56
57   my $metaclass = Class::MOP::Class->initialize($class);
58
59   my $re = qr/^\Q$incomplete/;
60
61   return $orig->(@_),
62          grep { $_ =~ $re }
63          map  { $_->name }
64          $metaclass->get_all_methods;
65 };
66
67 1;
68
69 __END__
70
71 =head1 NAME
72
73 Devel::REPL::Plugin::CompletionDriver::Methods - Complete class or object method names
74
75 =head1 AUTHOR
76
77 Shawn M Moore, C<< <sartak at gmail dot com> >>
78
79 =cut
80