#!/usr/bin/perl -n

BEGIN {
    $USES = $ARGV[0] eq "-uses" and shift;

    @exclude_calls = qw(chomp chop chr crypt hex index lc lcfirst length oct ord pack reverse rindex sprintf substr uc ucfirst pos quotemeta split study abs atan2 cos exp hex int log oct rand sin sqrt srand pop push shift splice unshift grep join map reverse sort unpack delete each exists keys values binmode close closedir dbmclose dbmopen die eof fileno flock format getc print printf read readdir rewinddir seek seekdir select syscall sysread sysseek syswrite tell telldir truncate warn write pack read syscall sysread syswrite unpack vec chdir chmod chown chroot fcntl glob ioctl link lstat mkdir open opendir readlink rename rmdir stat symlink umask unlink utime caller continue die do dump eval exit goto last next redo return sub wantarray caller import local my package use defined dump eval formline local my reset scalar undef wantarray alarm exec fork getpgrp getppid getpriority kill pipe setpgrp setpriority sleep system times wait waitpid do import no package require use bless dbmclose dbmopen package ref tie tied untie use accept bind connect getpeername getsockname getsockopt listen recv send setsockopt shutdown socket socketpair msgctl msgget msgrcv msgsnd semctl semget semop shmctl shmget shmread shmwrite endgrent endhostent endnetent endpwent getgrent getgrgid getgrnam getlogin getpwent getpwnam getpwuid setgrent setpwent endprotoent endservent gethostbyaddr gethostbyname gethostent getnetbyaddr getnetbyname getnetent getprotobyname getprotobynumber getprotoent getservbyname getservbyport getservent sethostent setnetent setprotoent setservent gmtime localtime time times abs bless chomp chr exists formline glob import lc lcfirst map my no prototype qx qw readline readpipe ref sysopen tie tied uc ucfirst untie use qq Dumper);
    @exclude_calls{@exclude_calls} = undef;

    @exclude_uses = qw(diagnostics strict vars lib Config Socket CORE Gtk Data::Dumper Net::FTP Gtk::XmHTML Newt Newt::Component Newt::Grid DynaLoader IO::Socket);
    while ($ARGV[0] =~ /-exclude(.*)/) {
	push @exclude_uses, $1;
	shift;
    }
    @exclude_uses{@exclude_uses} = undef;

    $package = 'main';
}

chop;
/^\s*#/ and next;

if (/^\s*require\s+([\w:]+);/) {
    add_use($1);
} elsif (my ($r) = /^\s*require (.*)/) {
    $r =~ /'(.*)'/ or err("<<$_>> should be formatted like <<require 'PACKAGE.pm'>>", info());
    $r =~ m|'([^/]*)\.pm'| and add_use($1);
    next;
}


s/"[^"]*"//g;  #"
s/'[^']*'//g;  #'
s/\bm\b(.)(.*?)\1//g; # m// operator
s|\(/.*?/|(|g; # m// operator

s/#.*//;

/^\s*package ([\w:]+)/ and ($package = $1), $path{$package} ||= './';


if (/\@EXPORT = qw\((.*)\)/) {
    @{$export{$package}}{split ' ', $1} = undef;
    #$export_info{$package} = info();
}

if (/%EXPORT_TAGS = \(/ .. /^\);$/) {
    /\s+(\w+)\s+.*?qw\((.*)\)/;
    @{$export_tags{$package}->{$1}}{split ' ', $2} = undef;
    $export_tags_info{$package}->{$1} = info();
}

while (/(^|[^\$@\w:>]) # first a char
        ((\w|:)*\w)      # function name
        (?=\()         # a open parenthesis (zero-width lookahead)
    /gx) { add_call($2) unless /$2\(s\)/ } # special case xxxx(s) excluded cuz' of strings containing it
while (/&([\w:]+)/g) { add_call($1); }

#while (/\$(\w+)/g) { add_usevar($1); }
#
#if (/\bmy\b\s*\(?([^=;)]*)/) {
#    map {
#	 s/[ \$@%]//g;
#	 $defvar{$package}->{$_} = 1;
#    } split ',', $1;
#}

/^use\s+([\w:]+);/ and add_use($1);
if (my ($p, $v) = /^use\s(\w+)\s+(.*)/) {
    $v =~ /^qw\((.*?)\)/ ? add_use($p, $1) : err("<<$_>> should be written <<use $p qw(:A :B ...)>>", info());
}
/^\s*sub\s+(\w+)/ and $sub{$package}->{$1} = 1;


$. = 0 if eof;
$package = 'main' if eof;


sub add_call {
    $_[0] =~ /^\d/ and return;
    exists $exclude_calls{$_[0]} and return;
    $call{$package}->{$_[0]} = 1;
    $call_info{$package}->{$_[0]} = info()
}

sub add_use {
    my ($p, $op) = @_;
    exists $exclude_uses{$p} and return;

    print "$p\n" if $USES;

    @{$use{$package}->{$p}} = split ' ', $op;
    $use_info{$package}->{$p} = info();

    $path{$p} and return;
    my ($path, $f) = "$p.pm" =~ /(.*::)?(.*)/;
    $path =~ s|::|/|g;
    
    $path{$p} = updirs($path{$package}, (($package =~ tr/://) / 2)) . $path;
    if (-e "$path{$p}$f") {
	 push @ARGV, "$path{$p}$f";
	 #err("added package $p", info());
    } else {
	 err("can't find package $p", info());
    }
}

#sub add_usevar {
#    length $_[0] <= 3 and return;
#    $usevar{$package}->{$_[0]} = 1;
#    $usevar_info{$package}->{$_[0]} = info();
#}

sub info { +{ file => $ARGV, line => $. } }

sub updirs {
    my ($p, $i) = @_;
    for (; $i && $p =~ s|[^/]+/^||; $i--) {}
    for (; $i ; $i--) { $p .= "../"; }
    $p;
}

sub err {
    my ($m, $i) = @_;

    $ERR = 1;

    if ($i) {
	 print STDERR "$i->{file}:$i->{line}: $m\n";
    } else {
	 print STDERR "$m\n";
    }
}

END {
    $export_tags{common}->{common}->{'_'} = 1; # hack!!!
    while (my ($package, $v) = each %use) {
	while (my ($k, $s) = each %$v) {
	    @$s and defined($export_tags{$k}) || err("package $k does not export tags");
	    foreach (@$s) {
		s/\"//g;
		s/^:// or err("<<use $k qw($s ...)>>  should be  <<use $k qw(:$s ...)>>", $use_info{$package}->{$k});

		exists $export_tags{$k}->{$_} or err("package $k does not export tag $_", $use_info{$package}->{$k});
	    }
	}
    }

#    while (my ($package, $vars) = each %usevar) {
#	 my @l = grep { ! $defvar{$package}->{$_} } keys %$vars;
#	 @l and print "$package: uses vars (", join(' ', @l), ")";
#    }

    while (my ($package, $calls) = each %call) {
	here: foreach my $f (keys %$calls) {

	    if ($f =~ /(.*)::(.*)/) {
		exists $exclude_uses{$1} and next;
		exists $use{$package}->{$1} or err("you must <<use $1>> for function $f", $call_info{$package}->{$f});
		$sub{$1}->{$2} and next;
	    } else {
		$sub{$package}->{$f} and next; # defined in own package
	    
		foreach my $k (keys %{$use{$package}}) {
		    exists $export{$k}->{$f} and next here; # ok, exported by $k

		    foreach (@{$use{$package}->{$k}}) {
			exists $export_tags{$k}->{$_}->{$f} and next here; # ok, exported by $k in tag $_
		    }
		}
	    }
	    err("$f undefined", $call_info{$package}->{$f});
	}
    }
    $ERR and exit $ERR;
}
