1 ######################################################################
8 Sepia::Xref - Generates cross reference database for use by Perl programs.
12 use Sepia::Xref qw(rebuild defs callers);
16 printf "%s:%d: sub %s\::foo() defined\n", @{$_}[0..2];
20 printf "%s:%d: sub foo() called by %s\::%s().\n", @{$_}[0..3];
25 C<Sepia::Xref> is intended as a programmatic interface to the
26 information supplied by L<B::Xref>. It is intended to be a component
27 for interactive Perl development, with other packages providing a
28 friendly interface to the raw information it extracts. C<B::Xref>
29 could be seen as an example of this sort of user-level tool, if it
30 weren't for the fact that this module was created later, and stole
38 use B
qw(peekop class comppadlist main_start svref_2object walksymtable
39 OPpLVAL_INTRO SVf_POK OPpOUR_INTRO OPf_MOD OPpDEREF_HV OPpDEREF_AV
41 # use Sepia '_apropos_re';
43 *_apropos_re
= *Sepia
::_apropos_re
;
51 A map of subs to call locations and callers
55 A map of subs to subs called.
59 A map of global/package variables to uses.
63 A map of global/package variables to definitions (usually empty, since
64 it only picks up local (...) declarations.
76 our @ISA = qw(Exporter);
77 my @most = qw(redefined forget rebuild callers callees
79 mod_subs mod_files mod_decls mod_apropos
80 apropos var_apropos file_apropos);
81 our @EXPORT_OK = (@most,
82 qw(xref_definitions xref_object xref_main
83 %call %callby %var_use %var_def));
86 (':all' => \@EXPORT_OK,
89 ######################################################################
90 ## Xref state variables:
92 sub UNKNOWN { ["?", "?", "?"] }
94 my @pad; # lexicals in current pad
95 # as ["(lexical)", type, name]
97 our %done; # keyed by $$op: set when each $op is done
98 my $top = UNKNOWN; # shadows top element of stack as
99 # [pack, type, name] (pack can be "(lexical)")
100 our $file; # shadows current filename
101 my $line; # shadows current line number
102 our $subname; # shadows current sub name
103 our @todo = (); # List of CVs that need processing
104 my $lastclass; # last bareword seen after entersub.
110 $res =~ s/%//g; # XXX: work around EPL's misuse of (message)
111 print STDERR "@_" if $DEBUG =~ /$type/;
114 my %code = (intro => "i", used => "",
115 subdef => "s", subused => "&",
116 formdef => "f", meth => "->");
119 =item C<guess_module_file($pack, $ofile)>
121 XXX: it turns out that rooting around trying to figure out the file
122 ourselves is more reliable than what we grab from the op. Are we
127 sub guess_module_file {
128 my ($pack, $ofile) = @_;
131 # XXX: is this why we get the bogus defs?
132 return undef if $ofile =~ /Exporter\.pm$/;
133 # Try for standard translation in %INC:
134 (my $fn = $pack) =~ s/::/\//g;
135 if (exists $INC{"$fn.pm"}) {
136 return $INC{"$fn.pm"};
139 # Try what they told us:
141 return $ofile if -f $ofile;
143 # Try "parent" packages:
144 while ($fn =~ s|/?[^/]+$|| && !$file) {
145 $file ||= $INC{"$fn.pm"};
148 if ($file && $file !~ /^\//) {
149 $file = abs_path($file);
152 if (!$file || !-f $file) {
158 # XXX: should weed through the code below so it only generates decent
159 # package names, but this will fix it for now.
162 if (!defined $p || $p eq '?' || $p eq '(method)') {
171 # Turn a possibly-qualified name into a package and basename.
175 if (/^(.*)::(.+)$/) {
178 ($p, $s) = ('main', $_);
180 undef $s if $s eq '?';
185 my ($var, $event) = @_;
186 my ($pack, $type, $name) = @$var;
187 $pack = realpack($pack);
188 dprint 'loud', "Processing $event: @$var ($subname)";
190 if ($event eq "used" || $event eq 'set') {
192 } elsif ($event eq "subused") {
194 } elsif ($event eq "meth") {
198 $type =~ s/(.)\*$/$1/g;
199 $file = guess_module_file($pack, $file);
201 if (($type eq '&' || $type eq '->') && $subname ne '(definitions)') {
202 # Handle caller/callee relations
203 my ($spack, $sname) = split_name($subname);
205 $call{$name}{$pack}{$subname} = 1;
207 $callby{$sname}{$spack}{"$pack\::$name"} = 1;
208 } elsif ($type eq 's' || $subname eq '(definitions)') {
210 } elsif ($name !~ /^[\x00-\x1f^] | ^\d+$ | ^[\W_]$
211 | ^(?:ENV|INC|STD(?:IN|OUT|ERR)|SIG)$ /x
212 && realpack($pack)) {
213 # Variables, but ignore specials and lexicals
214 my ($spack, $sname) = split_name($subname);
215 if ($event eq 'intro') {
216 $var_def{$name}{$pack} =
222 } elsif ($event eq 'used' || $event eq 'set') {
223 push @{$var_use{$name}{$pack}},
228 assign => ($event eq 'set'),
231 dprint 'ignore', "Ignoring var event $event";
234 dprint 'ignore', "Ignoring $type event $event";
240 my ($namelistav, $vallistav, @namelist, $ix);
243 return if class($padlist) eq "SPECIAL";
244 ($namelistav,$vallistav) = $padlist->ARRAY;
245 @namelist = $namelistav->ARRAY;
246 for ($ix = 1; $ix < @namelist; $ix++) {
247 my $namesv = $namelist[$ix];
248 next if class($namesv) eq "SPECIAL";
249 my ($type, $name) = $namesv->PV =~ /^(.)([^\0]*)(\0.*)?$/;
250 $pad[$ix] = [undef, $type, $name];
252 if ($Config{useithreads}) {
254 @vallist = $vallistav->ARRAY;
255 for ($ix = 1; $ix < @vallist; $ix++) {
256 my $valsv = $vallist[$ix];
257 next unless class($valsv) eq "GV";
258 # these pad GVs don't have corresponding names, so same @pad
259 # array can be used without collisions
260 $pad[$ix] = [$valsv->STASH->NAME, "*", $valsv->NAME];
263 @padval = $vallistav->ARRAY;
269 for ($op = $start; $$op; $op = $op->next) {
270 last if $done{$$op}++;
271 my $opname = $op->name;
272 if ($opname =~ /^(or|and|mapwhile|grepwhile|range|cond_expr)$/) {
274 } elsif ($opname eq "match" || $opname eq "subst") {
275 xref($op->pmreplstart);
276 } elsif ($opname eq "substcont") {
277 xref($op->other->pmreplstart);
280 } elsif ($opname eq "enterloop") {
284 } elsif ($opname eq "subst") {
285 xref($op->pmreplstart);
288 # print STDERR $opname;
289 my $ppname = "pp_$opname";
290 &$ppname($op) if defined(&$ppname);
297 my $pack = $cv->GV->STASH->NAME;
298 local $subname = ($pack eq "main" ? "" : "$pack\::") . $cv->GV->NAME;
299 load_pad($cv->PADLIST);
305 local (@todo, %done);
306 my $cv = svref_2object($cvref);
308 dprint 'todo', "todo = (@todo)";
310 process([$gv->STASH->NAME, '&', $gv->NAME], 'subdef');
315 load_pad(comppadlist);
318 xref_cv(shift @todo);
325 if (($class = $op->next)->name eq 'const') {
327 my ($classname, $methname);
328 # constant could be in the pad (under useithreads)
329 if (class($sv) ne "SPECIAL" && $sv->FLAGS & SVf_POK) {
330 $classname = $sv->PV;
332 my $pv = $padval[$class->targ];
333 if (class($pv) =~ /^PV/ && class($sv) eq 'SPECIAL'
334 ## bareword flag -- should use this?
335 # && ($op->private & 64)
337 $classname = $pv->PV;
340 $lastclass = $classname;
347 die "pp_nextstate: $file" if $file =~ /::/;
354 if ($op->private & (OPpLVAL_INTRO | OPpOUR_INTRO)) {
356 } elsif ($op->flags & OPf_MOD
357 && !($op->private & (OPpDEREF_HV | OPpDEREF_AV))) {
366 $top = $pad[$op->targ];
367 # process($top, $op->private & OPpLVAL_INTRO ? "intro" : "used");
370 sub pp_padav { pp_padsv(@_) }
371 sub pp_padhv { pp_padsv(@_) }
374 my ($op, $var, $as) = @_;
375 $var->[1] = $as . $var->[1];
376 process($var, use_type $op);
379 sub pp_rv2cv { deref(shift, $top, "&"); }
380 sub pp_rv2hv { deref(shift, $top, "%"); }
381 sub pp_rv2sv { deref(shift, $top, "\$"); }
382 sub pp_rv2av { deref(shift, $top, "\@"); }
383 sub pp_rv2gv { deref(shift, $top, "*"); }
388 if ($Config{useithreads}) {
389 $top = $pad[$op->padix];
390 $top = UNKNOWN unless $top;
395 $top = [$gv->STASH->NAME, '$', $gv->SAFENAME];
397 process($top, use_type $op);
403 if ($Config{useithreads}) {
404 $top = $pad[$op->padix];
405 $top = UNKNOWN unless $top;
410 $top = [$gv->STASH->NAME, "*", $gv->SAFENAME];
412 process($top, use_type $op);
417 $top = [$lastclass || "(method)", "->".$top->[1], $top->[2]];
418 dprint 'method', "pp_method($top->[1])";
422 sub pp_method_named {
426 my $pviv = $padval[$op->targ];
427 if ($pviv && class($pviv) =~ /^PV/) {
428 my $name = $pviv->PV;
429 dprint 'method_named', $op->targ.": $name";
430 undef $top->[2] if $top->[2] eq '?';
431 $top = [$lastclass || "(method)", '->', $name];
434 warn "method_named: wtf: sizeof padval = ".@padval;
440 if ($top->[1] =~ /^(?:m$|->)/) {
441 dprint 'method', "call to (@$top) from $subname";
442 process($top, "meth");
444 process($top, "subused");
451 # Stuff for cross referencing definitions of variables and subs
458 # XXX: sometimes the "file" is a module. Why?
461 #return if $done{$$cv}++;
462 process([$gv->STASH->NAME, "&", $gv->NAME], "subdef");
465 my $form = $gv->FORM;
467 return if $done{$$form}++;
468 process([$gv->STASH->NAME, "", $gv->NAME], "formdef");
472 sub xref_definitions {
473 my ($pack, %exclude);
474 $subname = "(definitions)";
475 foreach $pack (qw(B O AutoLoader DynaLoader XSLoader Config DB VMS
476 strict vars FileHandle Exporter Carp PerlIO::Layer
477 attributes utf8 warnings)) {
478 $exclude{$pack."::"} = 1;
480 no strict
qw(vars refs);
481 walksymtable
(\
%{"main::"}, "xref", sub { !defined($exclude{$_[0]}) });
490 Rebuild the Xref database.
495 %call = (); %callby = ();
496 %var_def = (); %var_use = ();
497 local (@todo, %done);
504 my ($h, $K, $V, $pack) = @_;
505 dprint
'unmention', "Unmentioning $K => $V";
506 while (my ($k, $v) = each %$h) {
507 while (my ($k2, $v2) = each %$v) {
508 if (ref $v2 eq 'ARRAY') {
510 $_->{$K} ne $V || !$pack || $pack ne $_->{package}
512 delete $v->{$k2} unless @
{$v->{$k2}};
514 delete $v->{$k2} if $k2 eq $V;
517 delete $h->{$k} unless keys %{$h->{$k}};
522 my ($h, $sub, $pack) = @_;
523 dprint
'unmention', "Unmentioning $pack\::$sub";
525 delete $h->{$sub}{$pack};
526 delete $h->{$sub} unless keys %{$h->{$sub}};
532 =item C<forget($func [, $mod])>
534 Forget that C<$func> was defined.
539 my ($obj, $pack) = @_;
540 unmention_sub \
%callby, @_;
541 unmention \
%call, 'sub', @_;
542 unmention \
%var_use, 'sub', @_;
543 unmention \
%var_def, 'sub', @_;
546 =item C<redefined($func [, $pack])>
548 Recompute xref info for C<$func>, or C<$pack::$func> if C<$pack> given.
556 my ($sub, $pack) = @_;
558 $sub = $pack eq 'main' ?
$sub : "$pack\::$sub";
559 local $subname = '(definitions)';
564 ######################################################################
565 # Apropos and definition-finding:
568 my ($l, $mod, $sub) = @_;
571 @r = keys %{$l->{$mod}};
574 @h{keys %$_} = 1 for values %$l;
578 return wantarray ?
@r : \
@r;
581 =item C<callers($func)>
583 List callers of C<$func>.
589 if ($f =~ /^(.*)::([^:]+)$/) {
593 return _ret_list
$call{$f}, @_;
596 =item C<callees($func)>
598 List callees of C<$func>.
604 if ($f =~ /^(.*::)([^:]+)$/) {
608 _ret_list
$callby{$f}, @_;
611 =item C<var_defs($var)>
613 Find locations where C<$var> is defined.
620 return _ret_list
$var_def{$v}, @_;
623 =item C<var_uses($var)>
625 Find locations where C<$var> is used.
632 return _ret_list
$var_use{$v}, @_;
635 =item C<var_assigns($var)>
637 Find locations where C<$var> is assigned to.
643 if ($v =~ /^(.*)::(.+)$/) {
647 return _ret_list
[ grep $_->{assign
},
648 $pack ? @
{$var_use{$v}{$pack}}
649 : map @
$_, values %{$var_use{$v}} ], $pack;
652 =item C<mod_files($mod)>
654 Find file for module C<$mod>.
660 # return sort keys %{$module_files{$m}}
661 # if exists $module_files{$m};
665 =item C<file_modules($file)>
667 List the modules defined in file C<$file>.
673 # return sort keys %{$file_modules{$f}}
674 # if exists $file_modules{$f};
679 my ($h, $re, $mod) = @_;
682 $re = _apropos_re
($re);
683 sort grep /$re/, keys %$h;
689 $mod = _apropos_re
($mod);
693 for (keys %{$h->{$_}}) {
694 $r{"$_\::$sn"} = 1 if /$mod/;
699 return wantarray ?
@r : \
@r;
702 =item C<var_apropos($expr)>
704 Find variables matching C<$expr>.
709 _apropos \
%var_use, @_;
720 Nothing by default, but all sub and variable described above can be
721 imported. C<Sepia::Xref> also defines the tags C<:most> for the
722 above-listed functions, and C<:all> for those and the variables as
727 See L<B::Xref>. Also, we currently ignore module names when looking
728 up a sub by name. Finally, there is some evil in the way we guess
729 file and line numbers, both of which should be done more cleanly and
734 L<B::Xref>, from which C<Sepia::Xref> is heavily derivative.
738 L<B::Xref> by Malcolm Beattie, m(angl|odifi)ed by Sean O'Rourke