PPI/Tokenizer.pm

filter: Statementstmt 87.8% 224 / 255 Branchbran 80.6% 121 / 150 Conditioncond 81.8% 36 / 44 MC/DCmcdc 58.3% 14 / 24 Subroutinesub 86.6% 26 / 30 Podpod 100% 5 / 5 totaltotal 83.8% 426 / 508 CC 91 SCAR 21.6
CC
91
Cov
85%
_process_next_char
14.1
__current_token_is_forced_word
14.0
new
13.3
CRAP 8.7
« PPI/Statement.pm ↑ Summary PPI/Node.pm »
1 package PPI::Tokenizer;
2  
3 =pod
4  
5 =head1 NAME
6  
7 PPI::Tokenizer - The Perl Document Tokenizer
8  
9 =head1 SYNOPSIS
10  
11 # Create a tokenizer for a file, array or string
12 $Tokenizer = PPI::Tokenizer->new( 'filename.pl' );
13 $Tokenizer = PPI::Tokenizer->new( \@lines );
14 $Tokenizer = PPI::Tokenizer->new( \$source );
15
16 # Return all the tokens for the document
17 my $tokens = $Tokenizer->all_tokens;
18
19 # Or we can use it as an iterator
20 while ( my $Token = $Tokenizer->get_token ) {
21 print "Found token '$Token'\n";
22 }
23
24 # If we REALLY need to manually nudge the cursor, you
25 # can do that to (The lexer needs this ability to do rollbacks)
26 $is_incremented = $Tokenizer->increment_cursor;
27 $is_decremented = $Tokenizer->decrement_cursor;
28  
29 =head1 DESCRIPTION
30  
31 PPI::Tokenizer is the class that provides Tokenizer objects for use in
32 breaking strings of Perl source code into Tokens.
33  
34 By the time you are reading this, you probably need to know a little
35 about the difference between how perl parses Perl "code" and how PPI
36 parsers Perl "documents".
37  
38 "perl" itself (the interpreter) uses a heavily modified lex specification
39 to specify its parsing logic, maintains several types of state as it
40 goes, and incrementally tokenizes, lexes AND EXECUTES at the same time.
41  
42 In fact, it is provably impossible to use perl's parsing method without
43 simultaneously executing code. A formal mathematical proof has been
44 published demonstrating the method.
45  
46 This is where the truism "Only perl can parse Perl" comes from.
47  
48 PPI uses a completely different approach by abandoning the (impossible)
49 ability to parse Perl the same way that the interpreter does, and instead
50 parsing the source as a document, using a document structure independently
51 derived from the Perl documentation and approximating the perl interpreter
52 interpretation as closely as possible.
53  
54 It was touch and go for a long time whether we could get it close enough,
55 but in the end it turned out that it could be done.
56  
57 In this approach, the tokenizer C<PPI::Tokenizer> is implemented separately
58 from the lexer L<PPI::Lexer>.
59  
60 The job of C<PPI::Tokenizer> is to take pure source as a string and break it
61 up into a stream/set of tokens, and contains most of the "black magic" used
62 in PPI. By comparison, the lexer implements a relatively straight forward
63 tree structure, and has an implementation that is uncomplicated (compared
64 to the insanity in the tokenizer at least).
65  
66 The Tokenizer uses an immense amount of heuristics, guessing and cruft,
67 supported by a very B<VERY> flexible internal API, but fortunately it was
68 possible to largely encapsulate the black magic, so there is not a lot that
69 gets exposed to people using the C<PPI::Tokenizer> itself.
70  
71 =head1 METHODS
72  
73 Despite the incredible complexity, the Tokenizer itself only exposes a
74 relatively small number of methods, with most of the complexity implemented
75 in private methods.
76  
77 =cut
78  
79 # Make sure everything we need is loaded so
80 # we don't have to go and load all of PPI.
81 62 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
82 62 ▶use Params::Util qw{_INSTANCE _SCALAR0 _ARRAY0};
Subroutine BEGIN: called CC=1 SCAR=0.0
83 62 ▶use List::Util 1.33 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
84 62 ▶use PPI::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
85 62 ▶use PPI::Element ();
Subroutine BEGIN: called CC=1 SCAR=0.0
86 62 ▶use PPI::Token ();
Subroutine BEGIN: called CC=1 SCAR=0.0
87 62 ▶use PPI::Exception ();
Subroutine BEGIN: called CC=1 SCAR=0.0
88 62 ▶use PPI::Exception::ParserRejection ();
Subroutine BEGIN: called CC=1 SCAR=0.0
89  
90 62 ▶use vars qw{$VERSION};
Subroutine BEGIN: called CC=1 SCAR=0.0
91 BEGIN {
92 62 ▶ $VERSION = '1.236';
Subroutine BEGIN: called CC=1 SCAR=0.0
93 }
94  
95 # The x operator cannot follow most Perl operators, implying that
96 # anything beginning with x following an operator is a word.
97 # These are the exceptions.
98 62 my %X_CAN_FOLLOW_OPERATOR = map { $_ => 1 } qw( -- ++ );
99  
100 # The x operator cannot follow most structure elements, implying that
101 # anything beginning with x following a structure element is a word.
102 # These are the exceptions.
103 62 my %X_CAN_FOLLOW_STRUCTURE = map { $_ => 1 } qw( } ] \) );
104  
105 # Something that looks like the x operator but follows a word
106 # is usually that word's argument.
107 # These are the exceptions.
108 # chop, chomp, dump are ambiguous because they can have either parms
109 # or no parms.
110 62 my %X_CAN_FOLLOW_WORD = map { $_ => 1 } qw(
111 endgrent
112 endhostent
113 endnetent
114 endprotoent
115 endpwent
116 endservent
117 fork
118 getgrent
119 gethostent
120 getlogin
121 getnetent
122 getppid
123 getprotoent
124 getpwent
125 getservent
126 setgrent
127 setpwent
128 time
129 times
130 wait
131 wantarray
132 __SUB__
133 );
134  
135  
136  
137 #####################################################################
138 # Creation and Initialization
139  
140 =pod
141  
142 =head2 new $file | \@lines | \$source
143  
144 The main C<new> constructor creates a new Tokenizer object. These
145 objects have no configuration parameters, and can only be used once,
146 to tokenize a single perl source file.
147  
148 It takes as argument either a normal scalar containing source code,
149 a reference to a scalar containing source code, or a reference to an
150 ARRAY containing newline-terminated lines of source code.
151  
152 Returns a new C<PPI::Tokenizer> object on success, or throws a
153 L<PPI::Exception> exception on error.
154  
155 =cut
156  
157 sub new {
158 15744 ▶ my $class = ref($_[0]) || $_[0];
Subroutine new: called CC=11 SCAR=25.8
Pod documented
Condition33%1/3
ref $_[0] || $_[0]
l!l&&r!l&&!r
0157440
MC/DC0%0/2
ref $_[0] || $_[0]
ref $_[0] $_[0]
Truth table33%1/3
A || B
A= ref $_[0]B= $_[0]
ABresult
1X1
011
000
159  
160 # Create the empty tokenizer struct
161 15744 my $self = bless {
162 # Source code
163 source => undef,
164 source_bytes => undef,
165  
166 # Line buffer
167 line => undef,
168 line_length => undef,
169 line_cursor => undef,
170 line_count => 0,
171  
172 # Parse state
173 token => undef,
174 class => 'PPI::Token::BOM',
175 zone => 'PPI::Token::Whitespace',
176  
177 # Output token buffer
178 tokens => [],
179 token_cursor => 0,
180 token_eof => 0,
181  
182 # Perl 6 blocks
183 perl6 => [],
184 }, $class;
185  
186 15744 ▶ if ( ! defined $_[1] ) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $_[1]) { } 0 15744 15744
elsif (not ref $_[1]) { } 468 15276 15744
elsif (&_SCALAR0($_[1])) { } 15276 0 15276
elsif (&_ARRAY0($_[1])) { } 0 0 0
187 # We weren't given anything
188 0 PPI::Exception->throw("No source provided to Tokenizer");
189  
190 } elsif ( ! ref $_[1] ) {
191 468 my $source = PPI::Util::_slurp($_[1]);
192 468 ▶ if ( ref $source ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $source) { } 468 0 468
193 # Content returned by reference
194 468 $self->{source} = $$source;
195 } else {
196 # Errors returned as a string
197 0 return( $source );
198 }
199  
200 } elsif ( _SCALAR0($_[1]) ) {
201 15276 $self->{source} = ${$_[1]};
202  
203 } elsif ( _ARRAY0($_[1]) ) {
204 0 $self->{source} = join '', map { "\n" } @{$_[1]};
205  
206 } else {
207 # We don't support whatever this is
208 0 PPI::Exception->throw(ref($_[1]) . " is not supported as a source provider");
209 }
210  
211 # We can't handle a null string
212 15744 $self->{source_bytes} = length $self->{source};
213 15744 ▶ if ( $self->{source_bytes} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'source_bytes'}) { } 15740 4 15744
214 # Split on local newlines
215 15740 $self->{source} =~ s/(?:\015{1,2}\012|\015|\012)/\n/g;
216 15740 $self->{source} = [ split /(?<=\n)/, $self->{source} ];
217  
218 } else {
219 4 $self->{source} = [ ];
220 }
221  
222 ### EVIL
223 # I'm explaining this earlier than I should so you can understand
224 # why I'm about to do something that looks very strange. There's
225 # a problem with the Tokenizer, in that tokens tend to change
226 # classes as each letter is added, but they don't get allocated
227 # their definite final class until the "end" of the token, the
228 # detection of which occurs in about a hundred different places,
229 # all through various crufty code (that triples the speed).
230 #
231 # However, in general, this does not apply to tokens in which a
232 # whitespace character is valid, such as comments, whitespace and
233 # big strings.
234 #
235 # So what we do is add a space to the end of the source. This
236 # triggers normal "end of token" functionality for all cases. Then,
237 # once the tokenizer hits end of file, it examines the last token to
238 # manually either remove the ' ' token, or chop it off the end of
239 # a longer one in which the space would be valid.
240 15744 ▶ if ( List::Util::any { /^__(?:DATA|END)__\s*$/ } @{$self->{source}} ) {
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 3 branches
BranchTrueFalseTotal
if (&List::Util::any(sub { /^__(?:DATA|END)__\s*$/; } , @{$$self{'source'};})) { } 10 15734 15744
elsif (not defined $self->{'source'}[0]) { } 4 15730 15734
elsif ($self->{'source'}[-1] =~ /\s$/) { } 963 14767 15730
241 10 $self->{source_eof_chop} = '';
242 } elsif ( ! defined $self->{source}->[0] ) {
243 4 $self->{source_eof_chop} = '';
244 } elsif ( $self->{source}->[-1] =~ /\s$/ ) {
245 963 $self->{source_eof_chop} = '';
246 } else {
247 14767 $self->{source_eof_chop} = 1;
248 14767 $self->{source}->[-1] .= ' ';
249 }
250  
251 15744 $self;
252 }
253  
254  
255  
256  
257  
258 #####################################################################
259 # Main Public Methods
260  
261 =pod
262  
263 =head2 get_token
264  
265 When using the PPI::Tokenizer object as an iterator, the C<get_token>
266 method is the primary method that is used. It increments the cursor
267 and returns the next Token in the output array.
268  
269 The actual parsing of the file is done only as-needed, and a line at
270 a time. When C<get_token> hits the end of the token array, it will
271 cause the parser to pull in the next line and parse it, continuing
272 as needed until there are more tokens on the output array that
273 get_token can then return.
274  
275 This means that a number of Tokenizer objects can be created, and
276 won't consume significant CPU until you actually begin to pull tokens
277 from it.
278  
279 Return a L<PPI::Token> object on success, C<0> if the Tokenizer had
280 reached the end of the file, or C<undef> on error.
281  
282 =cut
283  
284 sub get_token {
285 351648 ▶ my $self = shift;
Subroutine get_token: called CC=11 SCAR=25.5
Pod documented
286  
287 # Shortcut for EOF
288 351648 ▶ if ( $self->{token_eof}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"token_eof"} and $self->{"token_cursor"} > scalar @{$self->{"tokens"};}) 0 351648 351648
Condition66%2/3
$self->{"token_eof"} and $self->{"token_cursor"} > scalar @{$self->{"tokens"};}
!ll&&!rl&&r
339719119290
MC/DC0%0/2
$self->{"token_eof"} and $self->{"token_cursor"} > scalar @{$self->{"tokens"};}
$self->{"token_eof"} $self->{"token_cursor"} > scalar @{$self->{"tokens"};}
Truth table66%2/3
A and B
A= $self->{"token_eof"}B= $self->{"token_cursor"} > scalar @{$self->{"tokens"};}
ABresult
0X0
100
111
289 11929 and $self->{token_cursor} > scalar @{$self->{tokens}}
290 ) {
291 0 return 0;
292 }
293  
294 # Return the next token if we can
295 351648 ▶ if ( my $token = $self->{tokens}->[ $self->{token_cursor} ] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $token = $self->{"tokens"}[$self->{"token_cursor"}]) 280237 71411 351648
296 280237 $self->{token_cursor}++;
297 280237 return $token;
298 }
299  
300 71411 my $line_rv;
301  
302 # Catch exceptions and return undef, so that we
303 # can start to convert code to exception-based code.
304 71411 my $rv = eval {
305 # No token, we need to get some more
306 71411 ▶ while ( $line_rv = $self->_process_next_line ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line_rv = $self->_process_next_line) 64186 27587 91773
307 # If there is something in the buffer, return it
308 # The defined() prevents a ton of calls to PPI::Util::TRUE
309 64186 ▶ if ( defined( my $token = $self->{tokens}->[ $self->{token_cursor} ] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $token = $self->{"tokens"}[$self->{"token_cursor"}])) 43823 20363 64186
310 43823 $self->{token_cursor}++;
311 43823 return $token;
312 }
313 }
314 27587 return undef;
315 };
316 71411 ▶ if ( $@ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 1 71410 71411
elsif ($rv) { } 43823 27587 71410
317 1 ▶ if ( _INSTANCE($@, 'PPI::Exception') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (&_INSTANCE($@, 'PPI::Exception')) { } 1 0 1
318 1 $@->throw;
319 } else {
320 0 my $errstr = $@;
321 0 $errstr =~ s/^(.*) at line .+$/$1/;
322 0 PPI::Exception->throw( $errstr );
323 }
324 } elsif ( $rv ) {
325 43823 return $rv;
326 }
327  
328 27587 ▶ if ( defined $line_rv ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $line_rv) 27587 0 27587
329 # End of file, but we can still return things from the buffer
330 27587 ▶ if ( my $token = $self->{tokens}->[ $self->{token_cursor} ] ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $token = $self->{"tokens"}[$self->{"token_cursor"}]) 0 27587 27587
331 0 $self->{token_cursor}++;
332 0 return $token;
333 }
334  
335 # Set our token end of file flag
336 27587 $self->{token_eof} = 1;
337 27587 return 0;
338 }
339  
340 # Error, pass it up to our caller
341 0 undef;
342 }
343  
344 =pod
345  
346 =head2 all_tokens
347  
348 When not being used as an iterator, the C<all_tokens> method tells
349 the Tokenizer to parse the entire file and return all of the tokens
350 in a single ARRAY reference.
351  
352 It should be noted that C<all_tokens> does B<NOT> interfere with the
353 use of the Tokenizer object as an iterator (does not modify the token
354 cursor) and use of the two different mechanisms can be mixed safely.
355  
356 Returns a reference to an ARRAY of L<PPI::Token> objects on success
357 or throws an exception on error.
358  
359 =cut
360  
361 sub all_tokens {
362 4 ▶ my $self = shift;
Subroutine all_tokens: called CC=5 SCAR=17.4
Pod documented
363  
364 # Catch exceptions and return undef, so that we
365 # can start to convert code to exception-based code.
366 4 my $ok = eval {
367 # Process lines until we get EOF
368 4 ▶ unless ( $self->{token_eof} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"token_eof"}) 4 0 4
369 4 my $rv;
370 4 ▶ while ( $rv = $self->_process_next_line ) {}
Branch: 1 branch
BranchTrueFalseTotal
if ($rv = $self->_process_next_line) 10 4 14
371 4 ▶ unless ( defined $rv ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rv) 0 4 4
372 0 PPI::Exception->throw("Error while processing source");
373 }
374  
375 # Clean up the end of the tokenizer
376 4 $self->_clean_eof;
377 }
378 4 1;
379 };
380 4 ▶ if ( !$ok ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 4 4
381 0 my $errstr = $@;
382 0 $errstr =~ s/^(.*) at line .+$/$1/;
383 0 PPI::Exception->throw( $errstr );
384 }
385  
386 # End of file, return a copy of the token array.
387 4 return [ @{$self->{tokens}} ];
388 }
389  
390 =pod
391  
392 =head2 increment_cursor
393  
394 Although exposed as a public method, C<increment_cursor> is implemented
395 for expert use only, when writing lexers or other components that work
396 directly on token streams.
397  
398 It manually increments the token cursor forward through the file, in effect
399 "skipping" the next token.
400  
401 Return true if the cursor is incremented, C<0> if already at the end of
402 the file, or C<undef> on error.
403  
404 =cut
405  
406 sub increment_cursor {
407 # Do this via the get_token method, which makes sure there
408 # is actually a token there to move to.
409 0 ▶ $_[0]->get_token and 1;
Subroutine increment_cursor: not called CC=2 SCAR=17.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]->get_token and 1 0 0 0
410 }
411  
412 =pod
413  
414 =head2 decrement_cursor
415  
416 Although exposed as a public method, C<decrement_cursor> is implemented
417 for expert use only, when writing lexers or other components that work
418 directly on token streams.
419  
420 It manually decrements the token cursor backwards through the file, in
421 effect "rolling back" the token stream. And indeed that is what it is
422 primarily intended for, when the component that is consuming the token
423 stream needs to implement some sort of "roll back" feature in its use
424 of the token stream.
425  
426 Return true if the cursor is decremented, C<0> if already at the
427 beginning of the file, or C<undef> on error.
428  
429 =cut
430  
431 sub decrement_cursor {
432 0 ▶ my $self = shift;
Subroutine decrement_cursor: not called CC=2 SCAR=17.9
Pod documented
433  
434 # Check for the beginning of the file
435 0 ▶ return 0 unless $self->{token_cursor};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"token_cursor"} 0 0 0
436  
437 # Decrement the token cursor
438 0 $self->{token_eof} = 0;
439 0 --$self->{token_cursor};
440 }
441  
442  
443  
444  
445  
446 #####################################################################
447 # Working With Source
448  
449 # Fetches the next line from the input line buffer
450 # Returns undef at EOF.
451 sub _get_line {
452 97759 ▶ my $self = shift;
Subroutine _get_line: called CC=3 SCAR=11.0
453 97759 ▶ return undef unless $self->{source}; # EOF hit previously
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"source"} 13594 84165 97759
454  
455 # Pull off the next line
456 84165 my $line = shift @{$self->{source}};
457  
458 # Flag EOF if we hit it
459 84165 ▶ $self->{source} = undef unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 15662 68503 84165
460  
461 # Return the line (or EOF flag)
462 84165 return $line; # string or undef
463 }
464  
465 # Fetches the next line, ready to process
466 # Returns 1 on success
467 # Returns 0 on EOF
468 sub _fill_line {
469 96379 ▶ my $self = shift;
Subroutine _fill_line: called CC=3 SCAR=11.0
470 96379 my $inscan = shift;
471  
472 # Get the next line
473 96379 my $line = $self->_get_line;
474 96379 ▶ unless ( defined $line ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $line) 29192 67187 96379
475 # End of file
476 29192 ▶ unless ( $inscan ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($inscan) 27591 1601 29192
477 27591 delete $self->{line};
478 27591 delete $self->{line_cursor};
479 27591 delete $self->{line_length};
480 27591 return 0;
481 }
482  
483 # In the scan version, just set the cursor to the end
484 # of the line, and the rest should just cascade out.
485 1601 $self->{line_cursor} = $self->{line_length};
486 1601 return 0;
487 }
488  
489 # Populate the appropriate variables
490 67187 $self->{line} = $line;
491 67187 $self->{line_cursor} = -1;
492 67187 $self->{line_length} = length $line;
493 67187 $self->{line_count}++;
494  
495 67187 1;
496 }
497  
498 # Get the current character
499 sub _char {
500 0 ▶ my $self = shift;
Subroutine _char: not called CC=1 SCAR=6.9
501 0 substr( $self->{line}, $self->{line_cursor}, 1 );
502 }
503  
504  
505  
506  
507  
508 ####################################################################
509 # Per line processing methods
510  
511 # Processes the next line
512 # Returns 1 on success completion
513 # Returns 0 if EOF
514 # Returns undef on error
515 sub _process_next_line {
516 91788 ▶ my $self = shift;
Subroutine _process_next_line: called CC=11 SCAR=24.3
517  
518 # Fill the line buffer
519 91788 my $rv;
520 91788 ▶ unless ( $rv = $self->_fill_line ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rv = $self->_fill_line) 27591 64197 91788
521 27591 ▶ return undef unless defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 0 27591 27591
522  
523 # End of file, finalize last token
524 27591 $self->_finalize_token;
525 27591 return 0;
526 }
527  
528 # Run the __TOKENIZER__on_line_start
529 64197 $rv = $self->{class}->__TOKENIZER__on_line_start( $self );
530 64197 ▶ unless ( $rv ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($rv) 27314 36883 64197
531 # If there are no more source lines, then clean up
532 27314 ▶ if ( ref $self->{source} eq 'ARRAY' and ! @{$self->{source}} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"source"} eq "ARRAY" and not @{$self->{"source"};}) 306 27008 27314
Condition66%2/3
ref $self->{"source"} eq "ARRAY" and not @{$self->{"source"};}
!ll&&!rl&&r
027008306
MC/DC50%1/2
ref $self->{"source"} eq "ARRAY" and not @{$self->{"source"};}
ref $self->{"source"} eq "ARRAY" not @{$self->{"source"};}
Truth table66%2/3
A and not(B)
A= ref $self->{"source"} eq "ARRAY"B= not @{$self->{"source"};}
ABresult
0X0
100
111
533 306 $self->_clean_eof;
534 }
535  
536 # Defined but false means next line
537 27314 ▶ return 1 if defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
if defined $rv 27314 0 27314
538 0 PPI::Exception->throw("Error at line $self->{line_count}");
539 }
540  
541 # If we can't deal with the entire line, process char by char
542 36883 ▶ while ( $rv = $self->_process_next_char ) {}
Branch: 1 branch
BranchTrueFalseTotal
if ($rv = $self->_process_next_char) 361140 36882 398022
543 36882 ▶ unless ( defined $rv ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rv) 0 36882 36882
544 0 PPI::Exception->throw("Error at line $self->{line_count}, character $self->{line_cursor}");
545 }
546  
547 # Trigger any action that needs to happen at the end of a line
548 36882 $self->{class}->__TOKENIZER__on_line_end( $self );
549  
550 # If there are no more source lines, then clean up
551 36882 ▶ unless ( ref($self->{source}) eq 'ARRAY' and @{$self->{source}} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self->{"source"} eq "ARRAY" and @{$self->{"source"};}) 15433 21449 36882
Condition100%3/3
ref $self->{"source"} eq "ARRAY" and @{$self->{"source"};}
!ll&&!rl&&r
16591377421449
MC/DC100%2/2
ref $self->{"source"} eq "ARRAY" and @{$self->{"source"};}
ref $self->{"source"} eq "ARRAY" @{$self->{"source"};}
Truth table100%3/3
A and B
A= ref $self->{"source"} eq "ARRAY"B= @{$self->{"source"};}
ABresult
0X0
100
111
552 15433 return $self->_clean_eof;
553 }
554  
555 21449 return 1;
556 }
557  
558  
559  
560  
561  
562 #####################################################################
563 # Per-character processing methods
564  
565 # Process on a per-character basis.
566 # Note that due the high number of times this gets
567 # called, it has been fairly heavily in-lined, so the code
568 # might look a bit ugly and duplicated.
569 sub _process_next_char {
570 398023 ▶ my $self = shift;
Subroutine _process_next_char: called CC=12 SCAR=26.5
571  
572 ### FIXME - This checks for a screwed up condition that triggers
573 ### several warnings, amongst other things.
574 398023 ▶ if ( ! defined $self->{line_cursor} or ! defined $self->{line_length} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"line_cursor"} and defined $self->{"line_length"}) 0 398023 398023
Condition33%1/3
defined $self->{"line_cursor"} and defined $self->{"line_length"}
!ll&&!rl&&r
00398023
MC/DC0%0/2
defined $self->{"line_cursor"} and defined $self->{"line_length"}
defined $self->{"line_cursor"} defined $self->{"line_length"}
Truth table33%1/3
A and B
A= defined $self->{"line_cursor"}B= defined $self->{"line_length"}
ABresult
0X0
100
111
575 # $DB::single = 1;
576 0 return undef;
577 }
578  
579 # Increment the counter and check for end of line
580 398023 ▶ return 0 if ++$self->{line_cursor} >= $self->{line_length};
Branch: 1 branch
BranchTrueFalseTotal
if ++$self->{"line_cursor"} >= $self->{"line_length"} 36882 361141 398023
581  
582 # Pass control to the token class
583 361141 my $result;
584 361141 ▶ unless ( $result = $self->{class}->__TOKENIZER__on_char( $self ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result = $self->{"class"}->__TOKENIZER__on_char($self)) 70646 290494 361140
585 # undef is error. 0 is "Did stuff ourself, you don't have to do anything"
586 70646 ▶ return defined $result ? 1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $result ? : 70646 0 70646
587 }
588  
589 # We will need the value of the current character
590 290494 my $char = substr( $self->{line}, $self->{line_cursor}, 1 );
591 290494 ▶ if ( $result eq '1' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result eq 1) 48803 241691 290494
592 # If __TOKENIZER__on_char returns 1, it is signaling that it thinks that
593 # the character is part of it.
594  
595 # Add the character
596 48803 ▶ if ( defined $self->{token} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'token'}) { } 48803 0 48803
597 48803 $self->{token}->{content} .= $char;
598 } else {
599 0 ▶ defined($self->{token} = $self->{class}->new($char)) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
defined($self->{"token"} = $self->{"class"}->new($char)) or return undef 0 0 0
600 }
601  
602 48803 return 1;
603 }
604  
605 # We have been provided with the name of a class
606 241691 ▶ if ( $self->{class} ne "PPI::Token::$result" ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'class'} ne "PPI::Token::$result") { } 90555 151136 241691
elsif (defined $self->{'token'}) { } 27015 124121 151136
607 # New class
608 90555 $self->_new_token( $result, $char );
609 } elsif ( defined $self->{token} ) {
610 # Same class as current
611 27015 $self->{token}->{content} .= $char;
612 } else {
613 # Same class, but no current
614 124121 ▶ defined($self->{token} = $self->{class}->new($char)) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
defined($self->{"token"} = $self->{"class"}->new($char)) or return undef 0 124121 124121
615 }
616  
617 241691 1;
618 }
619  
620  
621  
622  
623  
624 #####################################################################
625 # Altering Tokens in Tokenizer
626  
627 # Finish the end of a token.
628 # Returns the resulting parse class as a convenience.
629 sub _finalize_token {
630 364625 ▶ my $self = shift;
Subroutine _finalize_token: called CC=2 SCAR=6.9
631 364625 ▶ return $self->{class} unless defined $self->{token};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"token"} 27593 337032 364625
632  
633 # Add the token to the token buffer
634 337032 push @{ $self->{tokens} }, $self->{token};
635 337032 $self->{token} = undef;
636  
637 # Return the parse class to that of the zone we are in
638 337032 $self->{class} = $self->{zone};
639 }
640  
641 # Creates a new token and sets it in the tokenizer
642 # The defined() in here prevent a ton of calls to PPI::Util::TRUE
643 sub _new_token {
644 212909 ▶ my $self = shift;
Subroutine _new_token: called CC=4 SCAR=13.9
645 # throw PPI::Exception() unless @_;
646 212909 ▶ my $class = substr( $_[0], 0, 12 ) eq 'PPI::Token::'
Branch: 1 branch
BranchTrueFalseTotal
substr($_[0], 0, 12) eq 'PPI::Token::' ? : 8668 204241 212909
647 ? shift : 'PPI::Token::' . shift;
648  
649 # Finalize any existing token
650 212909 ▶ $self->_finalize_token if defined $self->{token};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"token"} 93264 119645 212909
651  
652 # Create the new token and update the parse class
653 212909 ▶ defined($self->{token} = $class->new($_[0])) or PPI::Exception->throw;
Branch: 1 branch
BranchTrueFalseTotal
defined($self->{"token"} = $class->new($_[0])) or "PPI::Exception"->throw 0 212909 212909
654 212909 $self->{class} = $class;
655  
656 212909 1;
657 }
658  
659 # At the end of the file, we need to clean up the results of the erroneous
660 # space that we inserted at the beginning of the process.
661 sub _clean_eof {
662 15743 ▶ my $self = shift;
Subroutine _clean_eof: called CC=5 SCAR=16.2
663  
664 # Finish any partially completed token
665 15743 ▶ $self->_finalize_token if $self->{token};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"token"} 81 15662 15743
666  
667 # Find the last token, and if it has no content, kill it.
668 # There appears to be some evidence that such "null tokens" are
669 # somehow getting created accidentally.
670 15743 my $last_token = $self->{tokens}->[ -1 ];
671 15743 ▶ unless ( length $last_token->{content} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $last_token->{"content"}) 0 15743 15743
672 0 pop @{$self->{tokens}};
673 }
674  
675 # Now, if the last character of the last token is a space we added,
676 # chop it off, deleting the token if there's nothing else left.
677 15743 ▶ if ( $self->{source_eof_chop} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"source_eof_chop"}) 14737 1006 15743
678 14737 $last_token = $self->{tokens}->[ -1 ];
679 14737 $last_token->{content} =~ s/ $//;
680 14737 ▶ unless ( length $last_token->{content} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (length $last_token->{"content"}) 12944 1793 14737
681 # Popping token
682 12944 pop @{$self->{tokens}};
683 }
684  
685 # The hack involving adding an extra space is now reversed, and
686 # now nobody will ever know. The perfect crime!
687 14737 $self->{source_eof_chop} = '';
688 }
689  
690 15743 1;
691 }
692  
693  
694  
695  
696  
697 #####################################################################
698 # Utility Methods
699  
700 # Context
701 sub _last_token {
702 0 ▶ $_[0]->{tokens}->[-1];
Subroutine _last_token: not called CC=1 SCAR=6.9
703 }
704  
705 sub _last_significant_token {
706 2242 ▶ my $self = shift;
Subroutine _last_significant_token: called CC=3 SCAR=11.0
707 2242 my $cursor = $#{ $self->{tokens} };
708 2242 ▶ while ( $cursor >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cursor >= 0) 2927 211 3138
709 2927 my $token = $self->{tokens}->[$cursor--];
710 2927 ▶ return $token if $token->significant;
Branch: 1 branch
BranchTrueFalseTotal
if $token->significant 2031 896 2927
711 }
712 211 return;
713 }
714  
715 # Get an array ref of previous significant tokens.
716 # Like _last_significant_token except it gets more than just one token
717 # Returns array with 0 to x entries
718 sub _previous_significant_tokens {
719 138322 ▶ my $self = shift;
Subroutine _previous_significant_tokens: called CC=5 SCAR=16.1
720 138322 ▶ my $count = shift || 1;
Condition50%1/2
shift() || 1
l!l
1383220
MC/DC0%0/1
shift() || 1
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
721 138322 my $cursor = $#{ $self->{tokens} };
722  
723 138322 my @tokens;
724 138322 ▶ while ( $cursor >= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cursor >= 0) 222537 37412 259949
725 222537 my $token = $self->{tokens}->[$cursor--];
726 222537 ▶ next if not $token->significant;
Branch: 1 branch
BranchTrueFalseTotal
unless $token->significant 80327 142210 222537
727 142210 push @tokens, $token;
728 142210 ▶ last if @tokens >= $count;
Branch: 1 branch
BranchTrueFalseTotal
if @tokens >= $count 100910 41300 142210
729 }
730  
731 138322 return @tokens;
732 }
733  
734 62 my %OBVIOUS_CLASS = (
735 'PPI::Token::Symbol' => 'operator',
736 'PPI::Token::Magic' => 'operator',
737 'PPI::Token::Number' => 'operator',
738 'PPI::Token::ArrayIndex' => 'operator',
739 'PPI::Token::Quote::Double' => 'operator',
740 'PPI::Token::Quote::Interpolate' => 'operator',
741 'PPI::Token::Quote::Literal' => 'operator',
742 'PPI::Token::Quote::Single' => 'operator',
743 'PPI::Token::QuoteLike::Backtick' => 'operator',
744 'PPI::Token::QuoteLike::Command' => 'operator',
745 'PPI::Token::QuoteLike::Readline' => 'operator',
746 'PPI::Token::QuoteLike::Regexp' => 'operator',
747 'PPI::Token::QuoteLike::Words' => 'operator',
748 );
749  
750 62 my %OBVIOUS_CONTENT = (
751 '(' => 'operand',
752 '{' => 'operand',
753 '[' => 'operand',
754 ';' => 'operand',
755 '}' => 'operator',
756 );
757  
758  
759 62 my %USUALLY_FORCES = map { $_ => 1 } qw( sub package use no );
760  
761 # Try to determine operator/operand context, if possible.
762 # Returns "operator", "operand", or "" if unknown.
763 sub _opcontext {
764 6477 ▶ my $self = shift;
Subroutine _opcontext: called CC=6 SCAR=17.9
765 6477 my @tokens = $self->_previous_significant_tokens(1);
766 6477 my $p0 = $tokens[0];
767 6477 ▶ return '' if not $p0;
Branch: 1 branch
BranchTrueFalseTotal
unless $p0 115 6362 6477
768 6362 my $c0 = ref $p0;
769  
770 # Map the obvious cases
771 6362 ▶ return $OBVIOUS_CLASS{$c0} if defined $OBVIOUS_CLASS{$c0};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OBVIOUS_CLASS{$c0} 4233 2129 6362
772 2129 ▶ return $OBVIOUS_CONTENT{$p0} if defined $OBVIOUS_CONTENT{$p0};
Branch: 1 branch
BranchTrueFalseTotal
if defined $OBVIOUS_CONTENT{$p0} 542 1587 2129
773  
774 # Most of the time after an operator, we are an operand
775 1587 ▶ return 'operand' if $p0->isa('PPI::Token::Operator');
Branch: 1 branch
BranchTrueFalseTotal
if $p0->isa("PPI::Token::Operator") 206 1381 1587
776  
777 # If there's NOTHING, it's operand
778 1381 ▶ return 'operand' if $p0->content eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $p0->content eq "" 0 1381 1381
779  
780 # Otherwise, we don't know
781 1381 return ''
782 }
783  
784 # Assuming we are currently parsing the word 'x', return true
785 # if previous tokens imply the x is an operator, false otherwise.
786 sub _current_x_is_operator {
787 1074 ▶ my ( $self ) = @_;
Subroutine _current_x_is_operator: called CC=8 SCAR=20.8
788 1074 ▶ return if !@{$self->{tokens}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"tokens"};} 210 864 1074
789  
790 864 my ($prev, $prevprev) = $self->_previous_significant_tokens(2);
791 864 ▶ return if !$prev;
Branch: 1 branch
BranchTrueFalseTotal
unless $prev 0 864 864
792  
793 864 ▶ return !$self->__current_token_is_forced_word if $prev->isa('PPI::Token::Word');
Branch: 1 branch
BranchTrueFalseTotal
if $prev->isa("PPI::Token::Word") 159 705 864
794  
795 return (!$prev->isa('PPI::Token::Operator') || $X_CAN_FOLLOW_OPERATOR{$prev})
796 705 ▶ && (!$prev->isa('PPI::Token::Structure') || $X_CAN_FOLLOW_STRUCTURE{$prev})
Condition100%12/12
(!$prev->isa('PPI::Token::Operator') || $X_CAN_FOLLOW_OPERATOR{$prev}) && (!$prev->isa('PPI::Token::Structure') || $X_CAN_FOLLOW_STRUCTURE{$prev}) && !$prev->isa('PPI::Token::Label')
!ll&&!rl&&r
5065194
!$prev->isa("PPI::Token::Operator") || $X_CAN_FOLLOW_OPERATOR{$prev} and !$prev->isa("PPI::Token::Structure") || $X_CAN_FOLLOW_STRUCTURE{$prev}
!ll&&!rl&&r
337169199
not $prev->isa("PPI::Token::Operator") or $X_CAN_FOLLOW_OPERATOR{$prev}
l!l&&r!l&&!r
3653337
not $prev->isa("PPI::Token::Structure") or $X_CAN_FOLLOW_STRUCTURE{$prev}
l!l&&r!l&&!r
15544169
MC/DC100%5/5
(!$prev->isa('PPI::Token::Operator') || $X_CAN_FOLLOW_OPERATOR{$prev}) && (!$prev->isa('PPI::Token::Structure') || $X_CAN_FOLLOW_STRUCTURE{$prev}) && !$prev->isa('PPI::Token::Label')
not $prev->isa("PPI::Token::Operator") $X_CAN_FOLLOW_OPERATOR{$prev} not $prev->isa("PPI::Token::Structure") $X_CAN_FOLLOW_STRUCTURE{$prev} !$prev->isa('PPI::Token::Label')
Truth table54%6/11
not(A) or B and not(C) or D && not(E)
A= not $prev->isa("PPI::Token::Operator")B= $X_CAN_FOLLOW_OPERATOR{$prev}C= not $prev->isa("PPI::Token::Structure")D= $X_CAN_FOLLOW_STRUCTURE{$prev}E= !$prev->isa('PPI::Token::Label')
ABCDEresult
00XXX0
1X00X0
0100X0
1X1X00
1X0100
011X00
010100
1X1X11
1X0111
011X11
010111
797 && !$prev->isa('PPI::Token::Label')
798 ;
799 }
800  
801  
802 # Assuming we are at the end of parsing the current token that could be a word,
803 # a wordlike operator, or a version string, try to determine whether context
804 # before or after it forces it to be a bareword. This method is only useful
805 # during tokenization.
806 sub __current_token_is_forced_word {
807 31463 ▶ my ( $t, $word ) = @_;
Subroutine __current_token_is_forced_word: called CC=14 SCAR=26.4
808  
809 # Check if forced by preceding tokens.
810  
811 31463 my ( $prev, $prevprev ) = $t->_previous_significant_tokens(2);
812 31463 ▶ if ( !$prev ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $prev) { } 8869 22594 31463
813 8869 pos $t->{line} = $t->{line_cursor};
814 }
815 else {
816 22594 my $content = $prev->{content};
817  
818 # We are forced if we are a method name.
819 # '->' will always be an operator, so we don't check its type.
820 22594 ▶ return 1 if $content eq '->';
Branch: 1 branch
BranchTrueFalseTotal
if $content eq "->" 125 22469 22594
821  
822 # If we are contained in a pair of curly braces, we are probably a
823 # forced bareword hash key. '{' is never a word or operator, so we
824 # don't check its type.
825 22469 pos $t->{line} = $t->{line_cursor};
826 22469 ▶ return 1 if $content eq '{' and $t->{line} =~ /\G\s*\}/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $content eq "{" and $t->{"line"} =~ /\G\s*\}/cg 230 22239 22469
Condition100%3/3
$content eq "{" and $t->{"line"} =~ /\G\s*\}/cg
!ll&&!rl&&r
201032136230
MC/DC100%2/2
$content eq "{" and $t->{"line"} =~ /\G\s*\}/cg
$content eq "{" $t->{"line"} =~ /\G\s*\}/cg
Truth table100%3/3
A and B
A= $content eq "{"B= $t->{"line"} =~ /\G\s*\}/cg
ABresult
0X0
100
111
827  
828 # sub, package, use, and no all indicate that what immediately follows
829 # is a word not an operator or (in the case of sub and package) a
830 # version string. However, we don't want to be fooled by 'package
831 # package v10' or 'use no v10'. We're a forced package unless we're
832 # preceded by 'package sub', in which case we're a version string.
833 # We also have to make sure that the sub/package/etc doing the forcing
834 # is not a method call.
835 22239 ▶ if( $USUALLY_FORCES{$content}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($USUALLY_FORCES{$content}) 5624 16615 22239
836 5624 ▶ return if defined $word and $word =~ /^v[0-9]+$/ and ( $content eq "use" or $content eq "no" );
Branch: 1 branch
BranchTrueFalseTotal
if defined $word and $word =~ /^v[0-9]+$/ and $content eq "use" || $content eq "no" 10 5614 5624
Condition88%8/9
defined $word and $word =~ /^v[0-9]+$/ and $content eq "use" || $content eq "no"
!ll&&!rl&&r
5596262
defined $word and $word =~ /^v[0-9]+$/
!ll&&!rl&&r
5596028
$content eq "use" or $content eq "no"
l!l&&r!l&&!r
8218
MC/DC50%2/4
defined $word and $word =~ /^v[0-9]+$/ and $content eq "use" || $content eq "no"
defined $word $word =~ /^v[0-9]+$/ $content eq "use" $content eq "no"
Truth table60%3/5
A and B and C or D
A= defined $wordB= $word =~ /^v[0-9]+$/C= $content eq "use"D= $content eq "no"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
837 5614 ▶ return 1 if not $prevprev;
Branch: 1 branch
BranchTrueFalseTotal
unless $prevprev 5384 230 5614
838 230 ▶ return 1 if not $USUALLY_FORCES{$prevprev->content} and $prevprev->content ne '->';
Branch: 1 branch
BranchTrueFalseTotal
if not $USUALLY_FORCES{$prevprev->content} and $prevprev->content ne "->" 224 6 230
Condition100%3/3
not $USUALLY_FORCES{$prevprev->content} and $prevprev->content ne "->"
!ll&&!rl&&r
42224
MC/DC100%2/2
not $USUALLY_FORCES{$prevprev->content} and $prevprev->content ne "->"
not $USUALLY_FORCES{$prevprev->content} $prevprev->content ne "->"
Truth table100%3/3
not(A) and B
A= not $USUALLY_FORCES{$prevprev->content}B= $prevprev->content ne "->"
ABresult
0X0
100
111
839 6 return;
840 }
841 }
842 # pos on $t->{line} is guaranteed to be set at this point.
843  
844 # Check if forced by following tokens.
845  
846 # If the word is followed by => it is probably a word, not a regex.
847 25484 ▶ return 1 if $t->{line} =~ /\G\s*=>/gc;
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"line"} =~ /\G\s*=>/cg 790 24694 25484
848  
849 # Otherwise we probably aren't forced
850 24694 return '';
851 }
852  
853 62 1;
854  
855 =pod
856  
857 =head1 NOTES
858  
859 =head2 How the Tokenizer Works
860  
861 Understanding the Tokenizer is not for the faint-hearted. It is by far
862 the most complex and twisty piece of perl I've ever written that is actually
863 still built properly and isn't a terrible spaghetti-like mess. In fact, you
864 probably want to skip this section.
865  
866 But if you really want to understand, well then here goes.
867  
868 =head2 Source Input and Clean Up
869  
870 The Tokenizer starts by taking source in a variety of forms, sucking it
871 all in and merging into one big string, and doing our own internal line
872 split, using a "universal line separator" which allows the Tokenizer to
873 take source for any platform (and even supports a few known types of
874 broken newlines caused by mixed mac/pc/*nix editor screw ups).
875  
876 The resulting array of lines is used to feed the tokenizer, and is also
877 accessed directly by the heredoc-logic to do the line-oriented part of
878 here-doc support.
879  
880 =head2 Doing Things the Old Fashioned Way
881  
882 Due to the complexity of perl, and after 2 previously aborted parser
883 attempts, in the end the tokenizer was fashioned around a line-buffered
884 character-by-character method.
885  
886 That is, the Tokenizer pulls and holds a line at a time into a line buffer,
887 and then iterates a cursor along it. At each cursor position, a method is
888 called in whatever token class we are currently in, which will examine the
889 character at the current position, and handle it.
890  
891 As the handler methods in the various token classes are called, they
892 build up an output token array for the source code.
893  
894 Various parts of the Tokenizer use look-ahead, arbitrary-distance
895 look-behind (although currently the maximum is three significant tokens),
896 or both, and various other heuristic guesses.
897  
898 I've been told it is officially termed a I<"backtracking parser
899 with infinite lookaheads">.
900  
901 =head2 State Variables
902  
903 Aside from the current line and the character cursor, the Tokenizer
904 maintains a number of different state variables.
905  
906 =over
907  
908 =item Current Class
909  
910 The Tokenizer maintains the current token class at all times. Much of the
911 time is just going to be the "Whitespace" class, which is what the base of
912 a document is. As the tokenizer executes the various character handlers,
913 the class changes a lot as it moves a long. In fact, in some instances,
914 the character handler may not handle the character directly itself, but
915 rather change the "current class" and then hand off to the character
916 handler for the new class.
917  
918 Because of this, and some other things I'll deal with later, the number of
919 times the character handlers are called does not in fact have a direct
920 relationship to the number of actual characters in the document.
921  
922 =item Current Zone
923  
924 Rather than create a class stack to allow for infinitely nested layers of
925 classes, the Tokenizer recognises just a single layer.
926  
927 To put it a different way, in various parts of the file, the Tokenizer will
928 recognise different "base" or "substrate" classes. When a Token such as a
929 comment or a number is finalised by the tokenizer, it "falls back" to the
930 base state.
931  
932 This allows proper tokenization of special areas such as __DATA__
933 and __END__ blocks, which also contain things like comments and POD,
934 without allowing the creation of any significant Tokens inside these areas.
935  
936 For the main part of a document we use L<PPI::Token::Whitespace> for this,
937 with the idea being that code is "floating in a sea of whitespace".
938  
939 =item Current Token
940  
941 The final main state variable is the "current token". This is the Token
942 that is currently being built by the Tokenizer. For certain types, it
943 can be manipulated and morphed and change class quite a bit while being
944 assembled, as the Tokenizer's understanding of the token content changes.
945  
946 When the Tokenizer is confident that it has seen the end of the Token, it
947 will be "finalized", which adds it to the output token array and resets
948 the current class to that of the zone that we are currently in.
949  
950 I should also note at this point that the "current token" variable is
951 optional. The Tokenizer is capable of knowing what class it is currently
952 set to, without actually having accumulated any characters in the Token.
953  
954 =back
955  
956 =head2 Making It Faster
957  
958 As I'm sure you can imagine, calling several different methods for each
959 character and running regexes and other complex heuristics made the first
960 fully working version of the tokenizer extremely slow.
961  
962 During testing, I created a metric to measure parsing speed called
963 LPGC, or "lines per gigacycle" . A gigacycle is simple a billion CPU
964 cycles on a typical single-core CPU, and so a Tokenizer running at
965 "1000 lines per gigacycle" should generate around 1200 lines of tokenized
966 code when running on a 1200 MHz processor.
967  
968 The first working version of the tokenizer ran at only 350 LPGC, so to
969 tokenize a typical large module such as L<ExtUtils::MakeMaker> took
970 10-15 seconds. This sluggishness made it unpractical for many uses.
971  
972 So in the current parser, there are multiple layers of optimisation
973 very carefully built in to the basic. This has brought the tokenizer
974 up to a more reasonable 1000 LPGC, at the expense of making the code
975 quite a bit twistier.
976  
977 =head2 Making It Faster - Whole Line Classification
978  
979 The first step in the optimisation process was to add a hew handler to
980 enable several of the more basic classes (whitespace, comments) to be
981 able to be parsed a line at a time. At the start of each line, a
982 special optional handler (only supported by a few classes) is called to
983 check and see if the entire line can be parsed in one go.
984  
985 This is used mainly to handle things like POD, comments, empty lines,
986 and a few other minor special cases.
987  
988 =head2 Making It Faster - Inlining
989  
990 The second stage of the optimisation involved inlining a small
991 number of critical methods that were repeated an extremely high number
992 of times. Profiling suggested that there were about 1,000,000 individual
993 method calls per gigacycle, and by cutting these by two thirds a significant
994 speed improvement was gained, in the order of about 50%.
995  
996 You may notice that many methods in the C<PPI::Tokenizer> code look
997 very nested and long hand. This is primarily due to this inlining.
998  
999 At around this time, some statistics code that existed in the early
1000 versions of the parser was also removed, as it was determined that
1001 it was consuming around 15% of the CPU for the entire parser, while
1002 making the core more complicated.
1003  
1004 A judgment call was made that with the difficulties likely to be
1005 encountered with future planned enhancements, and given the relatively
1006 high cost involved, the statistics features would be removed from the
1007 Tokenizer.
1008  
1009 =head2 Making It Faster - Quote Engine
1010  
1011 Once inlining had reached diminishing returns, it became obvious from
1012 the profiling results that a huge amount of time was being spent
1013 stepping a char at a time though long, simple and "syntactically boring"
1014 code such as comments and strings.
1015  
1016 The existing regex engine was expanded to also encompass quotes and
1017 other quote-like things, and a special abstract base class was added
1018 that provided a number of specialised parsing methods that would "scan
1019 ahead", looking out ahead to find the end of a string, and updating
1020 the cursor to leave it in a valid position for the next call.
1021  
1022 This is also the point at which the number of character handler calls began
1023 to greatly differ from the number of characters. But it has been done
1024 in a way that allows the parser to retain the power of the original
1025 version at the critical points, while skipping through the "boring bits"
1026 as needed for additional speed.
1027  
1028 The addition of this feature allowed the tokenizer to exceed 1000 LPGC
1029 for the first time.
1030  
1031 =head2 Making It Faster - The "Complete" Mechanism
1032  
1033 As it became evident that great speed increases were available by using
1034 this "skipping ahead" mechanism, a new handler method was added that
1035 explicitly handles the parsing of an entire token, where the structure
1036 of the token is relatively simple. Tokens such as symbols fit this case,
1037 as once we are passed the initial sigil and word char, we know that we
1038 can skip ahead and "complete" the rest of the token much more easily.
1039  
1040 A number of these have been added for most or possibly all of the common
1041 cases, with most of these "complete" handlers implemented using regular
1042 expressions.
1043  
1044 In fact, so many have been added that at this point, you could arguably
1045 reclassify the tokenizer as a "hybrid regex, char-by=char heuristic
1046 tokenizer". More tokens are now consumed in "complete" methods in a
1047 typical program than are handled by the normal char-by-char methods.
1048  
1049 Many of the these complete-handlers were implemented during the writing
1050 of the Lexer, and this has allowed the full parser to maintain around
1051 1000 LPGC despite the increasing weight of the Lexer.
1052  
1053 =head2 Making It Faster - Porting To C (In Progress)
1054  
1055 While it would be extraordinarily difficult to port all of the Tokenizer
1056 to C, work has started on a L<PPI::XS> "accelerator" package which acts as
1057 a separate and automatically-detected add-on to the main PPI package.
1058  
1059 L<PPI::XS> implements faster versions of a variety of functions scattered
1060 over the entire PPI codebase, from the Tokenizer Core, Quote Engine, and
1061 various other places, and implements them identically in XS/C.
1062  
1063 In particular, the skip-ahead methods from the Quote Engine would appear
1064 to be extremely amenable to being done in C, and a number of other
1065 functions could be cherry-picked one at a time and implemented in C.
1066  
1067 Each method is heavily tested to ensure that the functionality is
1068 identical, and a versioning mechanism is included to ensure that if a
1069 function gets out of sync, L<PPI::XS> will degrade gracefully and just
1070 not replace that single method.
1071  
1072 =head1 TO DO
1073  
1074 - Add an option to reset or seek the token stream...
1075  
1076 - Implement more Tokenizer functions in L<PPI::XS>
1077  
1078 =head1 SUPPORT
1079  
1080 See the L<support section|PPI/SUPPORT> in the main module.
1081  
1082 =head1 AUTHOR
1083  
1084 Adam Kennedy E<lt>adamk@cpan.orgE<gt>
1085  
1086 =head1 COPYRIGHT
1087  
1088 Copyright 2001 - 2011 Adam Kennedy.
1089  
1090 This program is free software; you can redistribute
1091 it and/or modify it under the same terms as Perl itself.
1092  
1093 The full text of the license can be found in the
1094 LICENSE file included with this module.
1095  
1096 =cut
« PPI/Statement.pm ↑ Summary PPI/Node.pm »