File: Use.pm

package info (click to toggle)
libmodule-extract-use-perl 1.054-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 200 kB
  • sloc: perl: 584; makefile: 2
file content (357 lines) | stat: -rw-r--r-- 7,239 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
use v5.10;

package Module::Extract::Use;
use strict;

use warnings;
no warnings;

our $VERSION = '1.054';

=encoding utf8

=head1 NAME

Module::Extract::Use - Discover the modules a module explicitly uses

=head1 SYNOPSIS

	use Module::Extract::Use;

	my $extor = Module::Extract::Use->new;

	my @modules = $extor->get_modules( $file );
	if( $extor->error ) { ... }

	my $details = $extor->get_modules_with_details( $file );
	foreach my $detail ( @$details ) {
		printf "%s %s imports %s\n",
			$detail->module, $detail->version,
			join ' ', @{ $detail->imports }
		}

=head1 DESCRIPTION

Extract the names of the modules used in a file using a static
analysis. Since this module does not run code, it cannot find dynamic
uses of modules, such as C<eval "require $class">. It only reports modules
that the file loads directly or are in the import lists for L<parent>
or L<base>.

The module can handle the conventional inclusion of modules with either
C<use> or C<require> as the statement:

	use Foo;
	require Foo;

	use Foo 1.23;
	use Foo qw(this that);

It now finds C<require> as an expression, which is useful to lazily
load a module once (and may be faster):

	sub do_something {
		state $rc = require Foo;
		...
		}

Additionally, it finds module names used with C<parent> and C<base>,
either of which establish an inheritance relationship:

	use parent qw(Foo);
	use base qw(Foo);

In the case of namespaces found in C<base> or C<parent>, the value of
the C<direct> method is false. In all other cases, it is true. You
can then skip those namespaces:

	my $details = $extor->get_modules_with_details( $file );
	foreach my $detail ( @$details ) {
		next unless $detail->direct;

		...
		}

This module does not discover runtime machinations to load something,
such as string evals:

	eval "use Foo";

	my $bar = 'Bar';
	eval "use $bar";

If you want that, you might consider L<Module::ExtractUse> (a confusingly
similar name).

=cut

=over 4

=item new

Makes an object. The object doesn't do anything just yet, but you need
it to call the methods.

=cut

sub new {
	my $class = shift;

	my $self = bless {}, $class;

	$self->init;

	$self;
	}

=item init

Set up the object. You shouldn't need to call this yourself.

=cut

sub init {
	$_[0]->_clear_error;
	}

=item get_modules( FILE )

Returns a list of namespaces explicity use-d in FILE. Returns the
empty list if the file does not exist or if it can't parse the file.

Each used namespace is only in the list even if it is used multiple
times in the file. The order of the list does not correspond to
anything so don't use the order to infer anything.

=cut

sub get_modules {
	my( $self, $file ) = @_;

	$self->_clear_error;

	my $details = $self->get_modules_with_details( $file );

	my @modules = map { $_->module } @$details;

	@modules;
	}

=item get_modules_with_details( FILE )

Returns a list of hash references, one reference for each namespace
explicitly use-d in FILE. Each reference has keys for:

	namespace - the namespace, always defined
	version   - defined if a module version was specified
	imports   - an array reference to the import list
	pragma    - true if the module thinks this namespace is a pragma
	direct    - false if the module name came from parent or base

Each used namespace is only in the list even if it is used multiple
times in the file. The order of the list does not correspond to
anything so don't use the order to infer anything.

=cut

sub get_modules_with_details {
	my( $self, $file ) = @_;

	$self->_clear_error;

	my $modules = $self->_get_ppi_for_file( $file );
	return [] unless defined $modules;

	$modules;
	}

sub _get_ppi_for_file {
	my( $self, $file ) = @_;

	unless( -e $file ) {
		$self->_set_error( ref( $self ) . ": File [$file] does not exist!" );
		return;
		}

	require PPI;

	my $Document = eval { PPI::Document->new( $file ) };
	unless( $Document ) {
		$self->_set_error( ref( $self ) . ": Could not parse file [$file]" );
		return;
		}

	# this handles the
	#   use Foo;
	#   use Bar;
	my $regular_modules = $self->_regular_load( $Document );

	# this handles
	#   use parent qw(...)
	my $isa_modules      = $self->_isa_load( $regular_modules );

	# this handles
	#   my $rc = require Foo;
	my $expression_loads = $self->_expression_load( $Document );

	my @modules = map { @$_ }
		$regular_modules,
		$isa_modules,
		$expression_loads
		;

	return \@modules;
	}

sub _regular_load {
	my( $self, $Document ) = @_;

	my $modules = $Document->find(
		sub {
			$_[1]->isa( 'PPI::Statement::Include' )
			}
		);

	return [] unless $modules;

	my %Seen;
	my @modules =
		grep { ! $Seen{ $_->{module} }++ && $_->{module} }
		map  {
			my $hash = bless {
				direct  => 1,
				content => $_->content,
				pragma  => $_->pragma,
				module  => $_->module,
				imports => [ $self->_list_contents( $_->arguments ) ],
				version => eval{ $_->module_version->literal || ( undef ) },
				}, 'Module::Extract::Use::Item';
			} @$modules;

	\@modules;
	}

sub _isa_load {
	my( $self, $modules ) = @_;
	my @isa_modules =
		map {
			my $m = $_;
			map {
				bless {
					content => $m->content,
					pragma  => '',
					direct  => 0,
					module  => $_,
					imports => [],
					version => undef,
					}, 'Module::Extract::Use::Item';
				} @{ $m->imports };
			}
		grep { $_->module eq 'parent' or $_->module eq 'base' }
		@$modules;

	\@isa_modules;
	}

sub _expression_load {
	my( $self, $Document ) = @_;

	my $in_statements = $Document->find(
		sub {
			my $sib;
			$_[1]->isa( 'PPI::Token::Word' ) &&
			$_[1]->content eq 'require' &&
			( $sib = $_[1]->snext_sibling() ) &&
			$sib->isa( 'PPI::Token::Word' )
			}
		);

	return [] unless $in_statements;

	my @modules =
		map {
			bless {
				content => $_->parent->content,
				pragma  => undef,
				direct  => 1,
				module  => $_->snext_sibling->content,
				imports => [],
				version => undef,
				}, 'Module::Extract::Use::Item';
			}
		@$in_statements;

	\@modules;
	}

BEGIN {
package Module::Extract::Use::Item;

sub direct  { $_[0]->{direct}  }
sub content { $_[0]->{content} }
sub pragma  { $_[0]->{pragma}  }
sub module  { $_[0]->{module}  }
sub imports { $_[0]->{imports} }
sub version { $_[0]->{version} }
}

sub _list_contents {
	my( $self, $node ) = @_;

	eval {
		if( ! defined $node ) {
			return;
			}
		elsif( $node->isa( 'PPI::Token::QuoteLike::Words' ) ) {
			( $node->literal )
			}
		elsif( $node->isa( 'PPI::Structure::List' ) ) {
			my $nodes = $node->find( sub{ $_[1]->isa( 'PPI::Token::Quote' ) } );
			map { $_->string } @$nodes;
			}
		elsif( $node->isa( 'PPI::Token::Quote' ) ) {
			( $node->string );
			}
	};

	}

=item error

Return the error from the last call to C<get_modules>.

=cut

sub _set_error   { $_[0]->{error} = $_[1]; }

sub _clear_error { $_[0]->{error} = '' }

sub error        { $_[0]->{error} }

=back

=head1 TO DO

=head1 SEE ALSO

L<Module::ScanDeps>, L<Module::Extract>

=head1 SOURCE AVAILABILITY

The source code is in Github:

	https://github.com/briandfoy/module-extract-use

=head1 AUTHOR

brian d foy, C<< <briandfoy@pobox.com> >>

=head1 COPYRIGHT AND LICENSE

Copyright © 2008-2025, brian d foy C<< <briandfoy@pobox.com> >>. All rights reserved.

This project is under the Artistic License 2.0.

=cut

1;