PPI/Document.pm

filter: Statementstmt 90.9% 232 / 255 Branchbran 70.3% 83 / 118 Conditioncond 62.9% 17 / 27 MC/DCmcdc 29.4% 5 / 17 Subroutinesub 88.8% 40 / 45 Podpod 80.0% 16 / 20 totaltotal 81.5% 393 / 482 CC 74 SCAR 23.7
CC
74
Cov
83%
new
26.0
serialize
25.7
_logical_line_and_file
9.0
CRAP 10.7
« PPI/Document/Normalized.pm ↑ Summary PPI/Token/Pod.pm »
1 package PPI::Document;
2  
3 =pod
4  
5 =head1 NAME
6  
7 PPI::Document - Object representation of a Perl document
8  
9 =head1 INHERITANCE
10  
11 PPI::Document
12 isa PPI::Node
13 isa PPI::Element
14  
15 =head1 SYNOPSIS
16  
17 use PPI;
18
19 # Load a document from a file
20 my $Document = PPI::Document->new('My/Module.pm');
21
22 # Strip out comments
23 $Document->prune('PPI::Token::Comment');
24
25 # Find all the named subroutines
26 my $sub_nodes = $Document->find(
27 sub { $_[1]->isa('PPI::Statement::Sub') and $_[1]->name }
28 );
29 my @sub_names = map { $_->name } @$sub_nodes;
30
31 # Save the file
32 $Document->save('My/Module.pm.stripped');
33  
34 =head1 DESCRIPTION
35  
36 The C<PPI::Document> class represents a single Perl "document". A
37 C<PPI::Document> object acts as a root L<PPI::Node>, with some
38 additional methods for loading and saving, and working with
39 the line/column locations of Elements within a file.
40  
41 The exemption to its L<PPI::Node>-like behavior this is that a
42 C<PPI::Document> object can NEVER have a parent node, and is always
43 the root node in a tree.
44  
45 =head2 Storable Support
46  
47 C<PPI::Document> implements the necessary C<STORABLE_freeze> and
48 C<STORABLE_thaw> hooks to provide native support for L<Storable>,
49 if you have it installed.
50  
51 However if you want to clone a Document, you are highly recommended
52 to use the C<$Document-E<gt>clone> method rather than Storable's
53 C<dclone> function (although C<dclone> should still work).
54  
55 =head1 METHODS
56  
57 Most of the things you are likely to want to do with a Document are
58 probably going to involve the methods from L<PPI::Node> class, of which
59 this is a subclass.
60  
61 The methods listed here are the remaining few methods that are truly
62 Document-specific.
63  
64 =cut
65  
66 63 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
67 63 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
68 63 ▶use List::Util 1.33 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
69 63 ▶use Params::Util 1.00 qw{_SCALAR0 _ARRAY0 _INSTANCE};
Subroutine BEGIN: called CC=1 SCAR=0.0
70 63 ▶use Digest::MD5 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
71 63 ▶use PPI::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
72 63 ▶use PPI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
73 63 ▶use PPI::Node ();
Subroutine BEGIN: called CC=1 SCAR=0.0
74  
75 63 ▶use overload 'bool' => \&PPI::Util::TRUE;
Subroutine BEGIN: called CC=1 SCAR=0.0
76 63 ▶use overload '""' => 'content';
Subroutine BEGIN: called CC=1 SCAR=0.0
77  
78 63 our $VERSION = '1.260'; # VERSION
79  
80 63 our ( $errstr, @ISA ) = ( "", "PPI::Node" );
81  
82 63 ▶use PPI::Document::Fragment ();
Subroutine BEGIN: called CC=1 SCAR=0.0
83  
84 # Document cache
85 63 my $CACHE;
86  
87 # Convenience constants related to constants
88 63 ▶use constant LOCATION_LINE => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
89 63 ▶use constant LOCATION_CHARACTER => 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
90 63 ▶use constant LOCATION_COLUMN => 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
91 63 ▶use constant LOCATION_LOGICAL_LINE => 3;
Subroutine BEGIN: called CC=1 SCAR=0.0
92 63 ▶use constant LOCATION_LOGICAL_FILE => 4;
Subroutine BEGIN: called CC=1 SCAR=0.0
93  
94  
95  
96  
97  
98 #####################################################################
99 # Constructor and Static Methods
100  
101 =pod
102  
103 =head2 new
104  
105 # Simple construction
106 $doc = PPI::Document->new( $filename );
107 $doc = PPI::Document->new( \$source );
108
109 # With the readonly attribute set
110 $doc = PPI::Document->new( $filename,
111 readonly => 1,
112 );
113  
114 The C<new> constructor takes as argument a variety of different sources of
115 Perl code, and creates a single cohesive Perl C<PPI::Document>
116 for it.
117  
118 If passed a file name as a normal string, it will attempt to load the
119 document from the file.
120  
121 If passed a reference to a C<SCALAR>, this is taken to be source code and
122 parsed directly to create the document.
123  
124 If passed zero arguments, a "blank" document will be created that contains
125 no content at all.
126  
127 In all cases, the document is considered to be "anonymous" and not tied back
128 to where it was created from. Specifically, if you create a PPI::Document from
129 a filename, the document will B<not> remember where it was created from.
130  
131 The constructor also takes attribute flags.
132  
133 At this time, the only available attribute is the C<readonly> flag.
134  
135 Setting C<readonly> to true will allow various systems to provide
136 additional optimisations and caching. Note that because C<readonly> is an
137 optimisation flag, it is off by default and you will need to explicitly
138 enable it.
139  
140 Returns a C<PPI::Document> object, or C<undef> if parsing fails.
141 L<PPI::Exception> objects can also be thrown if there are parsing problems.
142  
143 =cut
144  
145 sub new {
146 31854 ▶ local $_; # An extra one, just in case
Subroutine new: called CC=19 SCAR=32.6
Pod documented
147 31854 ▶ my $class = ref $_[0] ? ref shift : shift;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 31854 31854
148  
149 31854 ▶ unless ( @_ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@_) 15928 15926 31854
150 15928 my $self = $class->SUPER::new;
151 15928 $self->{readonly} = ! 1;
152 15928 $self->{tab_width} = 1;
153 15928 return $self;
154 }
155  
156 # Check constructor attributes
157 15926 my $source = shift;
158 15926 my %attr = @_;
159  
160 # Check the data source
161 15926 ▶ if ( ! defined $source ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $source) { } 0 15926 15926
elsif (not ref $source) { } 485 15441 15926
elsif (&_SCALAR0($source)) { } 15438 3 15441
elsif (&_ARRAY0($source)) { } 3 0 3
162 0 $class->_error("An undefined value was passed to PPI::Document::new");
163  
164 } elsif ( ! ref $source ) {
165 # Catch people using the old API
166 485 ▶ if ( $source =~ /(?:\012|\015)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($source =~ /(?:\012|\015)/) 0 485 485
167 0 Carp::croak("API CHANGE: Source code should only be passed to PPI::Document->new as a SCALAR reference");
168 }
169  
170 # Save the filename
171 485 ▶ $attr{filename} ||= $source;
Condition66%2/3
$attr{"filename"} ||= $source
l!l&&r!l&&!r
24830
MC/DC0%0/2
$attr{"filename"} ||= $source
$attr{"filename"} $source
Truth table66%2/3
A ||= B
A= $attr{"filename"}B= $source
ABresult
1X1
011
000
172  
173 # When loading from a filename, use the caching layer if it exists.
174 485 ▶ if ( $CACHE ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($CACHE) { } 3 482 485
175 3 my $file_contents = PPI::Util::_slurp( $source );
176  
177 # Errors returned as plain string
178 3 ▶ return $class->_error($file_contents) if !ref $file_contents;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $file_contents 0 3 3
179  
180 # Retrieve the document from the cache
181 3 my $document = $CACHE->get_document($file_contents);
182 3 ▶ return $class->_setattr( $document, %attr ) if $document;
Branch: 1 branch
BranchTrueFalseTotal
if $document 2 1 3
183  
184 1 $document = PPI::Lexer->lex_source( $$file_contents );
185 1 ▶ if ( $document ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($document) 1 0 1
186 # Save in the cache
187 1 $CACHE->store_document( $document );
188 1 return $class->_setattr( $document, %attr );
189 }
190 } else {
191 482 my $document = PPI::Lexer->lex_file( $source );
192 482 ▶ return $class->_setattr( $document, %attr ) if $document;
Branch: 1 branch
BranchTrueFalseTotal
if $document 482 0 482
193 }
194  
195 } elsif ( _SCALAR0($source) ) {
196 15438 my $document = PPI::Lexer->lex_source( $$source );
197 15438 ▶ return $class->_setattr( $document, %attr ) if $document;
Branch: 1 branch
BranchTrueFalseTotal
if $document 15437 1 15438
198  
199 } elsif ( _ARRAY0($source) ) {
200 3 $source = join '', map { "$_\n" } @$source;
201 3 my $document = PPI::Lexer->lex_source( $source );
202 3 ▶ return $class->_setattr( $document, %attr ) if $document;
Branch: 1 branch
BranchTrueFalseTotal
if $document 3 0 3
203  
204 } else {
205 0 $class->_error("Unknown object or reference was passed to PPI::Document::new");
206 }
207  
208 # Pull and store the error from the lexer
209 1 my $errstr;
210 1 ▶ if ( _INSTANCE($@, 'PPI::Exception') ) {
Branch: 3 branches
BranchTrueFalseTotal
if (&_INSTANCE($@, 'PPI::Exception')) { } 1 0 1
elsif ($@) { } 0 0 0
elsif ('PPI::Lexer'->errstr) { } 0 0 0
211 1 $errstr = $@->message;
212 } elsif ( $@ ) {
213 0 $errstr = $@;
214 0 $errstr =~ s/\sat line\s.+$//;
215 } elsif ( PPI::Lexer->errstr ) {
216 0 $errstr = PPI::Lexer->errstr;
217 } else {
218 0 $errstr = "Unknown error parsing Perl document";
219 }
220 1 PPI::Lexer->_clear;
221 1 $class->_error( $errstr );
222 }
223  
224 sub load {
225 0 ▶ Carp::croak("API CHANGE: File names should now be passed to PPI::Document->new to load a file");
Subroutine load: not called CC=1 SCAR=6.9
Pod undocumented
226 }
227  
228 sub _setattr {
229 15925 ▶ my ($class, $document, %attr) = @_;
Subroutine _setattr: called CC=1 SCAR=0.0
230 15925 $document->{readonly} = !! $attr{readonly};
231 15925 $document->{filename} = $attr{filename};
232 15925 return $document;
233 }
234  
235 =pod
236  
237 =head2 set_cache $cache
238  
239 As of L<PPI> 1.100, C<PPI::Document> supports parser caching.
240  
241 The default cache class L<PPI::Cache> provides a L<Storable>-based
242 caching or the parsed document based on the MD5 hash of the document as
243 a string.
244  
245 The static C<set_cache> method is used to set the cache object for
246 C<PPI::Document> to use when loading documents. It takes as argument
247 a L<PPI::Cache> object (or something that C<isa> the same).
248  
249 If passed C<undef>, this method will stop using the current cache, if any.
250  
251 For more information on caching, see L<PPI::Cache>.
252  
253 Returns true on success, or C<undef> if not passed a valid param.
254  
255 =cut
256  
257 sub set_cache {
258 3 ▶ my $class = ref $_[0] ? ref shift : shift;
Subroutine set_cache: called CC=4 SCAR=14.0
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 3 3
259  
260 3 ▶ if ( defined $_[0] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[0]) { } 2 1 3
261 # Enable the cache
262 2 ▶ my $object = _INSTANCE(shift, 'PPI::Cache') or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $object = &_INSTANCE(shift(), "PPI::Cache") or return undef 0 2 2
263 2 $CACHE = $object;
264 } else {
265 # Disable the cache
266 1 $CACHE = undef;
267 }
268  
269 3 1;
270 }
271  
272 =pod
273  
274 =head2 get_cache
275  
276 If a document cache is currently set, the C<get_cache> method will
277 return it.
278  
279 Returns a L<PPI::Cache> object, or C<undef> if there is no cache
280 currently set for C<PPI::Document>.
281  
282 =cut
283  
284 sub get_cache {
285 7 ▶ $CACHE;
Subroutine get_cache: called CC=1 SCAR=0.0
Pod documented
286 }
287  
288  
289  
290  
291  
292 #####################################################################
293 # PPI::Document Instance Methods
294  
295 =pod
296  
297 =head2 filename
298  
299 The C<filename> accessor returns the name of the file in which the document
300 is stored.
301  
302 =cut
303  
304 sub filename {
305 247 ▶ $_[0]->{filename};
Subroutine filename: called CC=1 SCAR=0.0
Pod documented
306 }
307  
308 =pod
309  
310 =head2 readonly
311  
312 The C<readonly> attribute indicates if the document is intended to be
313 read-only, and will never be modified. This is an advisory flag, that
314 writers of L<PPI>-related systems may or may not use to enable
315 optimisations and caches for your document.
316  
317 Returns true if the document is read-only or false if not.
318  
319 =cut
320  
321 sub readonly {
322 4 ▶ $_[0]->{readonly};
Subroutine readonly: called CC=1 SCAR=0.0
Pod documented
323 }
324  
325 =pod
326  
327 =head2 tab_width [ $width ]
328  
329 In order to handle support for C<location> correctly, C<Documents>
330 need to understand the concept of tabs and tab width. The C<tab_width>
331 method is used to get and set the size of the tab width.
332  
333 At the present time, PPI only supports "naive" (width 1) tabs, but we do
334 plan on supporting arbitrary, default and auto-sensing tab widths later.
335  
336 Returns the tab width as an integer, or C<die>s if you attempt to set the
337 tab width.
338  
339 =cut
340  
341 sub tab_width {
342 55369 ▶ my $self = shift;
Subroutine tab_width: called CC=2 SCAR=6.9
Pod documented
343 55369 ▶ return $self->{tab_width} unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 55367 2 55369
344 2 $self->{tab_width} = shift;
345 }
346  
347 =pod
348  
349 =head2 save
350  
351 $document->save( $file )
352
353 The C<save> method serializes the C<PPI::Document> object and saves the
354 resulting Perl document to a file. Returns C<undef> on failure to open
355 or write to the file.
356  
357 =cut
358  
359 sub save {
360 2 ▶ my $self = shift;
Subroutine save: called CC=4 SCAR=14.3
Pod documented
361 2 local *FILE;
362 2 ▶ open( FILE, '>', $_[0] ) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open FILE, ">", $_[0] or return undef 0 2 2
363 2 binmode FILE;
364 2 ▶ print FILE $self->serialize or return undef;
Branch: 1 branch
BranchTrueFalseTotal
print FILE $self->serialize or return undef 0 2 2
365 2 ▶ close FILE or return undef;
Branch: 1 branch
BranchTrueFalseTotal
close FILE or return undef 0 2 2
366 2 return 1;
367 }
368  
369 =pod
370  
371 =head2 serialize
372  
373 Unlike the C<content> method, which shows only the immediate content
374 within an element, Document objects also have to be able to be written
375 out to a file again.
376  
377 When doing this we need to take into account some additional factors.
378  
379 Primarily, we need to handle here-docs correctly, so that are written
380 to the file in the expected place.
381  
382 The C<serialize> method generates the actual file content for a given
383 Document object. The resulting string can be written straight to a file.
384  
385 Returns the serialized document as a string.
386  
387 =cut
388  
389 sub serialize {
390 6263 ▶ my $self = shift;
Subroutine serialize: called CC=18 SCAR=32.5
Pod documented
391 6263 my @tokens = $self->tokens;
392  
393 # The here-doc content buffer
394 6263 my $heredoc = '';
395  
396 # Start the main loop
397 6263 my $output = '';
398 6263 foreach my $i ( 0 .. $#tokens ) {
399 250701 my $Token = $tokens[$i];
400  
401 # Handle normal tokens
402 250701 ▶ unless ( $Token->isa('PPI::Token::HereDoc') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Token->isa("PPI::Token::HereDoc")) 250519 182 250701
403 250519 my $content = $Token->content;
404  
405 # Handle the trivial cases
406 250519 ▶ unless ( $heredoc ne '' and $content =~ /\n/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($heredoc ne "" and $content =~ /\n/) 250370 149 250519
Condition100%3/3
$heredoc ne "" and $content =~ /\n/
!ll&&!rl&&r
250169201149
MC/DC100%2/2
$heredoc ne "" and $content =~ /\n/
$heredoc ne "" $content =~ /\n/
Truth table100%3/3
A and B
A= $heredoc ne ""B= $content =~ /\n/
ABresult
0X0
100
111
407 250370 $output .= $content;
408 250370 next;
409 }
410  
411 # We have pending here-doc content that needs to be
412 # inserted just after the first newline in the content.
413 149 ▶ if ( $content eq "\n" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content eq "\n") { } 146 3 149
414 # Shortcut the most common case for speed
415 146 $output .= $content . $heredoc;
416 } else {
417 # Slower and more general version
418 3 $content =~ s/\n/\n$heredoc/;
419 3 $output .= $content;
420 }
421  
422 149 $heredoc = '';
423 149 next;
424 }
425  
426 # This token is a HereDoc.
427 # First, add the token content as normal, which in this
428 # case will definitely not contain a newline.
429 182 $output .= $Token->content;
430  
431 # Now add all of the here-doc content to the heredoc buffer.
432 182 foreach my $line ( $Token->heredoc ) {
433 451 $heredoc .= $line;
434 }
435  
436 182 ▶ if ( $Token->{_damaged} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Token->{"_damaged"}) 56 126 182
437 # Special Case:
438 # There are a couple of warning/bug situations
439 # that can occur when a HereDoc content was read in
440 # from the end of a file that we silently allow.
441 #
442 # When writing back out to the file we have to
443 # auto-repair these problems if we aren't going back
444 # on to the end of the file.
445  
446 # When calculating $last_line, ignore the final token if
447 # and only if it has a single newline at the end.
448 56 my $last_index = $#tokens;
449 56 ▶ if ( $tokens[$last_index]->{content} =~ /^[^\n]*\n$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tokens[$last_index]{"content"} =~ /^[^\n]*\n$/) 31 25 56
450 31 $last_index--;
451 }
452  
453 # This is a two part test.
454 # First, are we on the last line of the
455 # content part of the file
456 my $last_line = List::Util::none {
457 53 ▶ $tokens[$_] and $tokens[$_]->{content} =~ /\n/
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$tokens[$_] and $tokens[$_]{"content"} =~ /\n/ 53 0 53
458 56 } (($i + 1) .. $last_index);
459 56 ▶ if ( ! defined $last_line ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $last_line) 0 56 56
460 # Handles the null list case
461 0 $last_line = 1;
462 }
463  
464 # Secondly, are their any more here-docs after us,
465 # (with content or a terminator)
466 my $any_after = List::Util::any {
467 $tokens[$_]->isa('PPI::Token::HereDoc')
468 and (
469 2 scalar(@{$tokens[$_]->{_heredoc}})
470 or
471 defined $tokens[$_]->{_terminator_line}
472 )
473 56 ▶ } (($i + 1) .. $#tokens);
Subroutine __ANON__: called CC=3 SCAR=11.8
Branch: 1 branch
BranchTrueFalseTotal
$tokens[$_]->isa("PPI::Token::HereDoc") and scalar @{$tokens[$_]{"_heredoc"};} || defined $tokens[$_]{"_terminator_line"} 2 82 84
Condition50%3/6
$tokens[$_]->isa('PPI::Token::HereDoc') && (scalar @{$tokens[$_]{'_heredoc'};} || defined $tokens[$_]{'_terminator_line'})
!ll&&!rl&&r
8220
scalar @{$tokens[$_]{"_heredoc"};} or defined $tokens[$_]{"_terminator_line"}
l!l&&r!l&&!r
002
MC/DC0%0/3
$tokens[$_]->isa('PPI::Token::HereDoc') && (scalar @{$tokens[$_]{'_heredoc'};} || defined $tokens[$_]{'_terminator_line'})
$tokens[$_]->isa('PPI::Token::HereDoc') scalar @{$tokens[$_]{"_heredoc"};} defined $tokens[$_]{"_terminator_line"}
Truth table50%2/4
A && B or C
A= $tokens[$_]->isa('PPI::Token::HereDoc')B= scalar @{$tokens[$_]{"_heredoc"};}C= defined $tokens[$_]{"_terminator_line"}
ABCresult
0XX0
1000
11X1
1011
474 56 ▶ if ( ! defined $any_after ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $any_after) 0 56 56
475 # Handles the null list case
476 0 $any_after = '';
477 }
478  
479 # We don't need to repair the last here-doc on the
480 # last line. But we do need to repair anything else.
481 56 ▶ unless ( $last_line and ! $any_after ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($last_line and not $any_after) 0 56 56
Condition33%1/3
$last_line and not $any_after
!ll&&!rl&&r
0056
MC/DC0%0/2
$last_line and not $any_after
$last_line not $any_after
Truth table33%1/3
A and not(B)
A= $last_lineB= not $any_after
ABresult
0X0
100
111
482 # Add a terminating string if it didn't have one
483 0 ▶ unless ( defined $Token->{_terminator_line} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $Token->{"_terminator_line"}) 0 0 0
484 0 $Token->{_terminator_line} = $Token->{_terminator};
485 }
486  
487 # Add a trailing newline to the terminating
488 # string if it didn't have one.
489 0 ▶ unless ( $Token->{_terminator_line} =~ /\n$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Token->{"_terminator_line"} =~ /\n$/) 0 0 0
490 0 $Token->{_terminator_line} .= "\n";
491 }
492 }
493 }
494  
495 # Now add the termination line to the heredoc buffer
496 182 ▶ if ( defined $Token->{_terminator_line} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $Token->{"_terminator_line"}) 133 49 182
497 133 $heredoc .= $Token->{_terminator_line};
498 }
499 }
500  
501 # End of tokens
502  
503 6263 ▶ if ( $heredoc ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($heredoc ne "") 0 6263 6263
504 # If the file doesn't end in a newline, we need to add one
505 # so that the here-doc content starts on the next line.
506 0 ▶ unless ( $output =~ /\n$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($output =~ /\n$/) 0 0 0
507 0 $output .= "\n";
508 }
509  
510 # Now we add the remaining here-doc content
511 # to the end of the file.
512 0 $output .= $heredoc;
513 }
514  
515 6263 $output;
516 }
517  
518 =pod
519  
520 =head2 hex_id
521  
522 The C<hex_id> method generates an unique identifier for the Perl document.
523  
524 This identifier is basically just the serialized document, with
525 Unix-specific newlines, passed through MD5 to produce a hexadecimal string.
526  
527 This identifier is used by a variety of systems (such as L<PPI::Cache>
528 and L<Perl::Metrics>) as a unique key against which to store or cache
529 information about a document (or indeed, to cache the document itself).
530  
531 Returns a 32 character hexadecimal string.
532  
533 =cut
534  
535 sub hex_id {
536 159 ▶ PPI::Util::md5hex($_[0]->serialize);
Subroutine hex_id: called CC=1 SCAR=0.0
Pod documented
537 }
538  
539 =pod
540  
541 =head2 index_locations
542  
543 Within a document, all L<PPI::Element> objects can be considered to have a
544 "location", a line/column position within the document when considered as a
545 file. This position is primarily useful for debugging type activities.
546  
547 The method for finding the position of a single Element is a bit laborious,
548 and very slow if you need to do it a lot. So the C<index_locations> method
549 will index and save the locations of every Element within the Document in
550 advance, making future calls to <PPI::Element::location> virtually free.
551  
552 Please note that this index should always be cleared using C<flush_locations>
553 once you are finished with the locations. If content is added to or removed
554 from the file, these indexed locations will be B<wrong>.
555  
556 =cut
557  
558 sub index_locations {
559 247 ▶ my $self = shift;
Subroutine index_locations: called CC=8 SCAR=21.0
Pod documented
560 247 my @tokens = $self->tokens;
561  
562 # Whenever we hit a heredoc we will need to increment by
563 # the number of lines in it's content section when we
564 # encounter the next token with a newline in it.
565 247 my $heredoc = 0;
566  
567 # Find the first Token without a location
568 247 my ($first, $location) = ();
569 247 foreach ( 0 .. $#tokens ) {
570 246 my $Token = $tokens[$_];
571 246 ▶ next if $Token->{_location};
Branch: 1 branch
BranchTrueFalseTotal
if $Token->{"_location"} 0 246 246
572  
573 # Found the first Token without a location
574 # Calculate the new location if needed.
575 246 ▶ if ($_) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_) { } 0 246 246
576 0 $location =
577 $self->_add_location( $location, $tokens[$_ - 1], \$heredoc );
578 } else {
579 246 ▶ my $logical_file =
Branch: 1 branch
BranchTrueFalseTotal
$self->can('filename') ? : 246 0 246
580 $self->can('filename') ? $self->filename : undef;
581 246 $location = [ 1, 1, 1, 1, $logical_file ];
582 }
583 246 $first = $_;
584 246 last;
585 }
586  
587 # Calculate locations for the rest
588 247 ▶ if ( defined $first ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $first) 246 1 247
589 246 foreach ( $first .. $#tokens ) {
590 65914 my $Token = $tokens[$_];
591 65914 $Token->{_location} = $location;
592 65914 $location = $self->_add_location( $location, $Token, \$heredoc );
593  
594 # Add any here-doc lines to the counter
595 65914 ▶ if ( $Token->isa('PPI::Token::HereDoc') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Token->isa("PPI::Token::HereDoc")) 26 65888 65914
596 26 $heredoc += $Token->heredoc + 1;
597 }
598 }
599 }
600  
601 247 1;
602 }
603  
604 sub _add_location {
605 65914 ▶ my ($self, $start, $Token, $heredoc) = @_;
Subroutine _add_location: called CC=5 SCAR=16.1
606 65914 my $content = $Token->{content};
607  
608 # Does the content contain any newlines
609 65914 my $newlines =()= $content =~ /\n/g;
610 65914 my ($logical_line, $logical_file) =
611 $self->_logical_line_and_file($start, $Token, $newlines);
612  
613 65914 ▶ unless ( $newlines ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($newlines) 55096 10818 65914
614 # Handle the simple case
615 return [
616 55096 $start->[LOCATION_LINE],
617 $start->[LOCATION_CHARACTER] + length($content),
618 $start->[LOCATION_COLUMN]
619 + $self->_visual_length(
620 $content,
621 $start->[LOCATION_COLUMN]
622 ),
623 $logical_line,
624 $logical_file,
625 ];
626 }
627  
628 # This is the more complex case where we hit or
629 # span a newline boundary.
630 10818 my $physical_line = $start->[LOCATION_LINE] + $newlines;
631 10818 my $location = [ $physical_line, 1, 1, $logical_line, $logical_file ];
632 10818 ▶ if ( $heredoc and $$heredoc ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($heredoc and $$heredoc) 23 10795 10818
Condition66%2/3
$heredoc and $$heredoc
!ll&&!rl&&r
01079523
MC/DC50%1/2
$heredoc and $$heredoc
$heredoc $$heredoc
Truth table66%2/3
A and B
A= $heredocB= $$heredoc
ABresult
0X0
100
111
633 23 $location->[LOCATION_LINE] += $$heredoc;
634 23 $location->[LOCATION_LOGICAL_LINE] += $$heredoc;
635 23 $$heredoc = 0;
636 }
637  
638 # Does the token have additional characters
639 # after their last newline.
640 10818 ▶ if ( $content =~ /\n([^\n]+?)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content =~ /\n([^\n]+?)\z/) 270 10548 10818
641 270 $location->[LOCATION_CHARACTER] += length($1);
642 270 $location->[LOCATION_COLUMN] +=
643 $self->_visual_length(
644 $1, $location->[LOCATION_COLUMN],
645 );
646 }
647  
648 10818 $location;
649 }
650  
651 sub _logical_line_and_file {
652 65914 ▶ my ($self, $start, $Token, $newlines) = @_;
Subroutine _logical_line_and_file: called CC=9 SCAR=22.0
653  
654 # Regex taken from perlsyn, with the correction that there's no space
655 # required between the line number and the file name.
656 65914 ▶ if ($start->[LOCATION_CHARACTER] == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($start->[1] == 1) 10574 55340 65914
657 10574 ▶ if ( $Token->isa('PPI::Token::Comment') ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($Token->isa('PPI::Token::Comment')) { } 1754 8820 10574
elsif ($Token->isa('PPI::Token::Pod')) { } 342 8478 8820
658 1754 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($Token->content =~ / \A \# \s* line \s+ (\d+) \s* (?: (\"?) ([^\"]* [^\s\"]) \2 )? \s* \z /msx) 13 1741 1754
659 $Token->content =~ m<
660 \A
661 \# \s*
662 line \s+
663 (\d+) \s*
664 (?: (\"?) ([^\"]* [^\s\"]) \2 )?
665 \s*
666 \z
667 >xms
668 ) {
669 13 ▶ return $1, ($3 || $start->[LOCATION_LOGICAL_FILE]);
Condition66%2/3
$3 || $start->[4]
l!l&&r!l&&!r
1102
MC/DC50%1/2
$3 || $start->[4]
$3 $start->[4]
Truth table66%2/3
A || B
A= $3B= $start->[4]
ABresult
1X1
011
000
670 }
671 }
672 elsif ( $Token->isa('PPI::Token::Pod') ) {
673 342 my $content = $Token->content;
674 342 my $line;
675 342 my $file = $start->[LOCATION_LOGICAL_FILE];
676 342 my $end_of_directive;
677 342 ▶ while (
Branch: 1 branch
BranchTrueFalseTotal
if ($content =~ / ^ \# \s*? line \s+? (\d+) (?: (?! \n) \s)* (?: (\"?) ([^\"]*? [^\s\"]) \2 )?? \s*? $ /gmsx) 6 342 348
678 $content =~ m<
679 ^
680 \# \s*?
681 line \s+?
682 (\d+) (?: (?! \n) \s)*
683 (?: (\"?) ([^\"]*? [^\s\"]) \2 )??
684 \s*?
685 $
686 >xmsg
687 ) {
688 6 ▶ ($line, $file) = ($1, ( $3 || $file ) );
Condition66%2/3
$3 || $file
l!l&&r!l&&!r
420
MC/DC0%0/2
$3 || $file
$3 $file
Truth table66%2/3
A || B
A= $3B= $file
ABresult
1X1
011
000
689 6 $end_of_directive = pos $content;
690 }
691  
692 342 ▶ if (defined $line) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $line) 6 336 342
693 6 pos $content = $end_of_directive;
694 6 my $post_directive_newlines =()= $content =~ m< \G [^\n]* \n >xmsg;
695 6 return $line + $post_directive_newlines - 1, $file;
696 }
697 }
698 }
699  
700 return
701 65895 $start->[LOCATION_LOGICAL_LINE] + $newlines,
702 $start->[LOCATION_LOGICAL_FILE];
703 }
704  
705 sub _visual_length {
706 55366 ▶ my ($self, $content, $pos) = @_;
Subroutine _visual_length: called CC=4 SCAR=13.9
707  
708 55366 my $tab_width = $self->tab_width;
709 55366 my ($length, $vis_inc);
710  
711 55366 ▶ return length $content if $content !~ /\t/;
Branch: 1 branch
BranchTrueFalseTotal
unless $content =~ /\t/ 51156 4210 55366
712  
713 # Split the content in tab and non-tab parts and calculate the
714 # "visual increase" of each part.
715 4210 for my $part ( split(/(\t)/, $content) ) {
716 15463 ▶ if ($part eq "\t") {
Branch: 1 branch
BranchTrueFalseTotal
if ($part eq "\t") { } 7714 7749 15463
717 7714 $vis_inc = $tab_width - ($pos-1) % $tab_width;
718 }
719 else {
720 7749 $vis_inc = length $part;
721 }
722 15463 $length += $vis_inc;
723 15463 $pos += $vis_inc;
724 }
725  
726 4210 $length;
727 }
728  
729 =pod
730  
731 =head2 flush_locations
732  
733 When no longer needed, the C<flush_locations> method clears all location data
734 from the tokens.
735  
736 =cut
737  
738 sub flush_locations {
739 1 ▶ shift->_flush_locations(@_);
Subroutine flush_locations: called CC=1 SCAR=0.0
Pod documented
740 }
741  
742 =pod
743  
744 =head2 normalized
745  
746 The C<normalized> method is used to generate a "Layer 1"
747 L<PPI::Document::Normalized> object for the current Document.
748  
749 A "normalized" Perl Document is an arbitrary structure that removes any
750 irrelevant parts of the document and refactors out variations in style,
751 to attempt to approach something that is closer to the "true meaning"
752 of the Document.
753  
754 See L<PPI::Normal> for more information on document normalization and
755 the tasks for which it is useful.
756  
757 Returns a L<PPI::Document::Normalized> object, or C<undef> on error.
758  
759 =cut
760  
761 sub normalized {
762 # The normalization process will utterly destroy and mangle
763 # anything passed to it, so we are going to only give it a
764 # clone of ourselves.
765 4 ▶ PPI::Normal->process( $_[0]->clone );
Subroutine normalized: called CC=1 SCAR=0.0
Pod documented
766 }
767  
768 =pod
769  
770 =head1 complete
771  
772 The C<complete> method is used to determine if a document is cleanly
773 structured, all braces are closed, the final statement is
774 fully terminated and all heredocs are fully entered.
775  
776 Returns true if the document is complete or false if not.
777  
778 =cut
779  
780 sub complete {
781 2 ▶ my $self = shift;
Subroutine complete: called CC=5 SCAR=16.6
Pod undocumented
782  
783 # Every structure has to be complete
784 $self->find_any( sub {
785 15 ▶ $_[1]->isa('PPI::Structure')
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[1]->isa("PPI::Structure") and not $_[1]->complete 0 15 15
786 and
787 ! $_[1]->complete
788 } )
789 2 ▶ and return '';
Branch: 1 branch
BranchTrueFalseTotal
$self->find_any(sub { $_[1]->isa("PPI::Structure") and not $_[1]->complete; } ) and return "" 0 2 2
790  
791 # Strip anything that isn't a statement off the end
792 2 my @child = $self->children;
793 2 ▶ while ( @child and not $child[-1]->isa('PPI::Statement') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@child and not $child[-1]->isa("PPI::Statement")) 2 2 4
Condition66%2/3
@child and not $child[-1]->isa("PPI::Statement")
!ll&&!rl&&r
022
MC/DC50%1/2
@child and not $child[-1]->isa("PPI::Statement")
@child not $child[-1]->isa("PPI::Statement")
Truth table66%2/3
A and not(B)
A= @childB= not $child[-1]->isa("PPI::Statement")
ABresult
0X0
100
111
794 2 pop @child;
795 }
796  
797 # We must have at least one statement
798 2 ▶ return '' unless @child;
Branch: 1 branch
BranchTrueFalseTotal
unless @child 0 2 2
799  
800 # Check the completeness of the last statement
801 2 return $child[-1]->_complete;
802 }
803  
804  
805  
806  
807  
808 #####################################################################
809 # PPI::Node Methods
810  
811 # We are a scope boundary
812 ### XS -> PPI/XS.xs:_PPI_Document__scope 0.903+
813 sub scope() { 1 }
814  
815  
816  
817  
818  
819 #####################################################################
820 # PPI::Element Methods
821  
822 sub insert_before {
823 0 ▶ return undef;
Subroutine insert_before: not called CC=1 SCAR=6.9
Pod documented
824 # die "Cannot insert_before a PPI::Document";
825 }
826  
827 sub insert_after {
828 0 ▶ return undef;
Subroutine insert_after: not called CC=1 SCAR=6.9
Pod documented
829 # die "Cannot insert_after a PPI::Document";
830 }
831  
832 sub replace {
833 0 ▶ return undef;
Subroutine replace: not called CC=1 SCAR=6.9
Pod documented
834 # die "Cannot replace a PPI::Document";
835 }
836  
837  
838  
839  
840  
841 #####################################################################
842 # Error Handling
843  
844 # Set the error message
845 sub _error {
846 1 ▶ $errstr = $_[1];
Subroutine _error: called CC=1 SCAR=0.0
847 1 undef;
848 }
849  
850 # Clear the error message.
851 # Returns the object as a convenience.
852 sub _clear {
853 0 ▶ $errstr = '';
Subroutine _clear: not called CC=1 SCAR=6.9
854 0 $_[0];
855 }
856  
857 =pod
858  
859 =head2 errstr
860  
861 For error that occur when loading and saving documents, you can use
862 C<errstr>, as either a static or object method, to access the error message.
863  
864 If a Document loads or saves without error, C<errstr> will return false.
865  
866 =cut
867  
868 sub errstr {
869 12 ▶ $errstr;
Subroutine errstr: called CC=1 SCAR=0.0
Pod documented
870 }
871  
872  
873  
874  
875  
876 #####################################################################
877 # Native Storable Support
878  
879 sub STORABLE_freeze {
880 4 ▶ my $self = shift;
Subroutine STORABLE_freeze: called CC=1 SCAR=0.0
Pod undocumented
881 4 my $class = ref $self;
882 4 my %hash = %$self;
883 4 return ($class, \%hash);
884 }
885  
886 sub STORABLE_thaw {
887 6 ▶ my ($self, undef, $class, $hash) = @_;
Subroutine STORABLE_thaw: called CC=2 SCAR=6.9
Pod undocumented
888 6 bless $self, $class;
889 6 foreach ( keys %$hash ) {
890 21 $self->{$_} = delete $hash->{$_};
891 }
892 6 $self->__link_children;
893 }
894  
895 63 1;
896  
897 =pod
898  
899 =head1 TO DO
900  
901 - May need to overload some methods to forcefully prevent Document
902 objects becoming children of another Node.
903  
904 =head1 SUPPORT
905  
906 See the L<support section|PPI/SUPPORT> in the main module.
907  
908 =head1 AUTHOR
909  
910 Adam Kennedy E<lt>adamk@cpan.orgE<gt>
911  
912 =head1 SEE ALSO
913  
914 L<PPI>, L<http://ali.as/>
915  
916 =head1 COPYRIGHT
917  
918 Copyright 2001 - 2011 Adam Kennedy.
919  
920 This program is free software; you can redistribute
921 it and/or modify it under the same terms as Perl itself.
922  
923 The full text of the license can be found in the
924 LICENSE file included with this module.
925  
926 =cut
« PPI/Document/Normalized.pm ↑ Summary PPI/Token/Pod.pm »