1 ########################################################################
3 # the Perl::Tidy::Tokenizer package is essentially a filter which
4 # reads lines of perl source code from a source object and provides
5 # corresponding tokenized lines through its get_line() method. Lines
6 # flow from the source_object to the caller like this:
8 # source_object --> LineBuffer_object --> Tokenizer --> calling routine
9 # get_line() get_line() get_line() line_of_tokens
11 # The source object can be any object with a get_line() method which
12 # supplies one line (a character string) perl call.
13 # The LineBuffer object is created by the Tokenizer.
14 # The Tokenizer returns a reference to a data structure 'line_of_tokens'
15 # containing one tokenized line for each call to its get_line() method.
17 # WARNING: This is not a real class yet. Only one tokenizer my be used.
19 ########################################################################
21 package Perl::Tidy::Tokenizer;
24 our $VERSION = '20190601';
26 use Perl::Tidy::LineBuffer;
30 # Caution: these debug flags produce a lot of output
31 # They should all be 0 except when debugging small scripts
33 use constant TOKENIZER_DEBUG_FLAG_EXPECT => 0;
34 use constant TOKENIZER_DEBUG_FLAG_NSCAN => 0;
35 use constant TOKENIZER_DEBUG_FLAG_QUOTE => 0;
36 use constant TOKENIZER_DEBUG_FLAG_SCAN_ID => 0;
37 use constant TOKENIZER_DEBUG_FLAG_TOKENIZE => 0;
39 my $debug_warning = sub {
40 print STDOUT "TOKENIZER_DEBUGGING with key $_[0]\n";
43 TOKENIZER_DEBUG_FLAG_EXPECT && $debug_warning->('EXPECT');
44 TOKENIZER_DEBUG_FLAG_NSCAN && $debug_warning->('NSCAN');
45 TOKENIZER_DEBUG_FLAG_QUOTE && $debug_warning->('QUOTE');
46 TOKENIZER_DEBUG_FLAG_SCAN_ID && $debug_warning->('SCAN_ID');
47 TOKENIZER_DEBUG_FLAG_TOKENIZE && $debug_warning->('TOKENIZE');
53 # PACKAGE VARIABLES for processing an entire FILE.
59 $last_nonblank_block_type
67 %user_function_prototype
69 %is_block_list_function
70 %saw_function_definition
79 @nesting_sequence_number
80 @current_sequence_number
82 @paren_semicolon_count
83 @paren_structural_type
85 @brace_structural_type
89 @square_bracket_structural_type
92 @nested_statement_type
93 @starting_line_of_current_depth
96 # GLOBAL CONSTANTS for routines in this package
98 %is_indirect_object_taker
100 %expecting_operator_token
101 %expecting_operator_types
102 %expecting_term_types
103 %expecting_term_token
105 %is_file_test_operator
114 %is_keyword_taking_list
115 %is_keyword_taking_optional_args
116 %is_q_qq_qw_qx_qr_s_y_tr_m
119 # possible values of operator_expected()
120 use constant TERM => -1;
121 use constant UNKNOWN => 0;
122 use constant OPERATOR => 1;
124 # possible values of context
125 use constant SCALAR_CONTEXT => -1;
126 use constant UNKNOWN_CONTEXT => 0;
127 use constant LIST_CONTEXT => 1;
129 # Maximum number of little messages; probably need not be changed.
130 use constant MAX_NAG_MESSAGES => 6;
134 # methods to count instances
136 sub get_count { return $_count; }
137 sub _increment_count { return ++$_count }
138 sub _decrement_count { return --$_count }
143 $self->_decrement_count();
149 my ( $class, @args ) = @_;
151 # Note: 'tabs' and 'indent_columns' are temporary and should be
154 source_object => undef,
155 debugger_object => undef,
156 diagnostics_object => undef,
157 logger_object => undef,
158 starting_level => undef,
161 look_for_hash_bang => 0,
163 look_for_autoloader => 1,
164 look_for_selfloader => 1,
165 starting_line_number => 1,
166 extended_syntax => 0,
168 my %args = ( %defaults, @args );
170 # we are given an object with a get_line() method to supply source lines
171 my $source_object = $args{source_object};
173 # we create another object with a get_line() and peek_ahead() method
174 my $line_buffer_object = Perl::Tidy::LineBuffer->new($source_object);
176 # Tokenizer state data is as follows:
177 # _rhere_target_list reference to list of here-doc targets
178 # _here_doc_target the target string for a here document
179 # _here_quote_character the type of here-doc quoting (" ' ` or none)
180 # to determine if interpolation is done
181 # _quote_target character we seek if chasing a quote
182 # _line_start_quote line where we started looking for a long quote
183 # _in_here_doc flag indicating if we are in a here-doc
184 # _in_pod flag set if we are in pod documentation
185 # _in_error flag set if we saw severe error (binary in script)
186 # _in_data flag set if we are in __DATA__ section
187 # _in_end flag set if we are in __END__ section
188 # _in_format flag set if we are in a format description
189 # _in_attribute_list flag telling if we are looking for attributes
190 # _in_quote flag telling if we are chasing a quote
191 # _starting_level indentation level of first line
192 # _line_buffer_object object with get_line() method to supply source code
193 # _diagnostics_object place to write debugging information
194 # _unexpected_error_count error count used to limit output
195 # _lower_case_labels_at line numbers where lower case labels seen
196 # _hit_bug program bug detected
198 _rhere_target_list => [],
200 _here_doc_target => "",
201 _here_quote_character => "",
207 _in_attribute_list => 0,
210 _line_start_quote => -1,
211 _starting_level => $args{starting_level},
212 _know_starting_level => defined( $args{starting_level} ),
213 _tabsize => $args{tabsize},
214 _indent_columns => $args{indent_columns},
215 _look_for_hash_bang => $args{look_for_hash_bang},
216 _trim_qw => $args{trim_qw},
217 _continuation_indentation => $args{continuation_indentation},
218 _outdent_labels => $args{outdent_labels},
219 _last_line_number => $args{starting_line_number} - 1,
220 _saw_perl_dash_P => 0,
221 _saw_perl_dash_w => 0,
222 _saw_use_strict => 0,
225 _look_for_autoloader => $args{look_for_autoloader},
226 _look_for_selfloader => $args{look_for_selfloader},
227 _saw_autoloader => 0,
228 _saw_selfloader => 0,
232 _saw_negative_indentation => 0,
233 _started_tokenizing => 0,
234 _line_buffer_object => $line_buffer_object,
235 _debugger_object => $args{debugger_object},
236 _diagnostics_object => $args{diagnostics_object},
237 _logger_object => $args{logger_object},
238 _unexpected_error_count => 0,
239 _started_looking_for_here_target_at => 0,
240 _nearly_matched_here_target_at => undef,
242 _rlower_case_labels_at => undef,
243 _extended_syntax => $args{extended_syntax},
246 prepare_for_a_new_file();
247 find_starting_indentation_level();
249 bless $tokenizer_self, $class;
251 # This is not a full class yet, so die if an attempt is made to
252 # create more than one object.
254 if ( _increment_count() > 1 ) {
256 "Attempt to create more than 1 object in $class, which is not a true class yet\n";
259 return $tokenizer_self;
263 # interface to Perl::Tidy::Logger routines
266 my $logger_object = $tokenizer_self->{_logger_object};
267 if ($logger_object) {
268 $logger_object->warning($msg);
275 my $logger_object = $tokenizer_self->{_logger_object};
276 if ($logger_object) {
277 $logger_object->complain($msg);
282 sub write_logfile_entry {
284 my $logger_object = $tokenizer_self->{_logger_object};
285 if ($logger_object) {
286 $logger_object->write_logfile_entry($msg);
291 sub interrupt_logfile {
292 my $logger_object = $tokenizer_self->{_logger_object};
293 if ($logger_object) {
294 $logger_object->interrupt_logfile();
300 my $logger_object = $tokenizer_self->{_logger_object};
301 if ($logger_object) {
302 $logger_object->resume_logfile();
307 sub increment_brace_error {
308 my $logger_object = $tokenizer_self->{_logger_object};
309 if ($logger_object) {
310 $logger_object->increment_brace_error();
315 sub report_definite_bug {
316 $tokenizer_self->{_hit_bug} = 1;
317 my $logger_object = $tokenizer_self->{_logger_object};
318 if ($logger_object) {
319 $logger_object->report_definite_bug();
326 my $logger_object = $tokenizer_self->{_logger_object};
327 if ($logger_object) {
328 $logger_object->brace_warning($msg);
333 sub get_saw_brace_error {
334 my $logger_object = $tokenizer_self->{_logger_object};
335 if ($logger_object) {
336 return $logger_object->get_saw_brace_error();
343 # interface to Perl::Tidy::Diagnostics routines
344 sub write_diagnostics {
346 if ( $tokenizer_self->{_diagnostics_object} ) {
347 $tokenizer_self->{_diagnostics_object}->write_diagnostics($msg);
352 sub report_tokenization_errors {
355 my $severe_error = $self->{_in_error};
357 my $level = get_indentation_level();
358 if ( $level != $tokenizer_self->{_starting_level} ) {
359 warning("final indentation level: $level\n");
362 check_final_nesting_depths();
364 if ( $tokenizer_self->{_look_for_hash_bang}
365 && !$tokenizer_self->{_saw_hash_bang} )
368 "hit EOF without seeing hash-bang line; maybe don't need -x?\n");
371 if ( $tokenizer_self->{_in_format} ) {
372 warning("hit EOF while in format description\n");
375 if ( $tokenizer_self->{_in_pod} ) {
377 # Just write log entry if this is after __END__ or __DATA__
378 # because this happens to often, and it is not likely to be
380 if ( $tokenizer_self->{_saw_data} || $tokenizer_self->{_saw_end} ) {
382 "hit eof while in pod documentation (no =cut seen)\n\tthis can cause trouble with some pod utilities\n"
388 "hit eof while in pod documentation (no =cut seen)\n\tthis can cause trouble with some pod utilities\n"
394 if ( $tokenizer_self->{_in_here_doc} ) {
396 my $here_doc_target = $tokenizer_self->{_here_doc_target};
397 my $started_looking_for_here_target_at =
398 $tokenizer_self->{_started_looking_for_here_target_at};
399 if ($here_doc_target) {
401 "hit EOF in here document starting at line $started_looking_for_here_target_at with target: $here_doc_target\n"
406 "hit EOF in here document starting at line $started_looking_for_here_target_at with empty target string\n"
409 my $nearly_matched_here_target_at =
410 $tokenizer_self->{_nearly_matched_here_target_at};
411 if ($nearly_matched_here_target_at) {
413 "NOTE: almost matched at input line $nearly_matched_here_target_at except for whitespace\n"
418 if ( $tokenizer_self->{_in_quote} ) {
420 my $line_start_quote = $tokenizer_self->{_line_start_quote};
421 my $quote_target = $tokenizer_self->{_quote_target};
423 ( $tokenizer_self->{_in_attribute_list} )
427 "hit EOF seeking end of $what starting at line $line_start_quote ending in $quote_target\n"
431 if ( $tokenizer_self->{_hit_bug} ) {
435 my $logger_object = $tokenizer_self->{_logger_object};
437 # TODO: eventually may want to activate this to cause file to be output verbatim
440 # Set the severe error for a fairly high warning count because
441 # some of the warnings do not harm formatting, such as duplicate
443 my $warning_count = $logger_object->{_warning_count};
444 if ( $warning_count > 50 ) {
448 # Brace errors are significant, so set the severe error flag at
450 my $saw_brace_error = $logger_object->{_saw_brace_error};
451 if ( $saw_brace_error > 2 ) {
456 unless ( $tokenizer_self->{_saw_perl_dash_w} ) {
458 write_logfile_entry("Suggest including '-w parameter'\n");
461 write_logfile_entry("Suggest including 'use warnings;'\n");
465 if ( $tokenizer_self->{_saw_perl_dash_P} ) {
466 write_logfile_entry("Use of -P parameter for defines is discouraged\n");
469 unless ( $tokenizer_self->{_saw_use_strict} ) {
470 write_logfile_entry("Suggest including 'use strict;'\n");
473 # it is suggested that labels have at least one upper case character
474 # for legibility and to avoid code breakage as new keywords are introduced
475 if ( $tokenizer_self->{_rlower_case_labels_at} ) {
476 my @lower_case_labels_at =
477 @{ $tokenizer_self->{_rlower_case_labels_at} };
479 "Suggest using upper case characters in label(s)\n");
481 write_logfile_entry(" defined at line(s): (@lower_case_labels_at)\n");
483 return $severe_error;
486 sub report_v_string {
488 # warn if this version can't handle v-strings
490 unless ( $tokenizer_self->{_saw_v_string} ) {
491 $tokenizer_self->{_saw_v_string} = $tokenizer_self->{_last_line_number};
495 "Found v-string '$tok' but v-strings are not implemented in your version of perl; see Camel 3 book ch 2\n"
501 sub get_input_line_number {
502 return $tokenizer_self->{_last_line_number};
505 # returns the next tokenized line
510 # USES GLOBAL VARIABLES: $tokenizer_self, $brace_depth,
511 # $square_bracket_depth, $paren_depth
513 my $input_line = $tokenizer_self->{_line_buffer_object}->get_line();
514 $tokenizer_self->{_line_text} = $input_line;
516 return unless ($input_line);
518 my $input_line_number = ++$tokenizer_self->{_last_line_number};
520 # Find and remove what characters terminate this line, including any
522 my $input_line_separator = "";
523 if ( chomp($input_line) ) { $input_line_separator = $/ }
525 # TODO: what other characters should be included here?
526 if ( $input_line =~ s/((\r|\035|\032)+)$// ) {
527 $input_line_separator = $2 . $input_line_separator;
530 # for backwards compatibility we keep the line text terminated with
531 # a newline character
533 $tokenizer_self->{_line_text} = $input_line; # update
535 # create a data structure describing this line which will be
536 # returned to the caller.
538 # _line_type codes are:
539 # SYSTEM - system-specific code before hash-bang line
540 # CODE - line of perl code (including comments)
541 # POD_START - line starting pod, such as '=head'
542 # POD - pod documentation text
543 # POD_END - last line of pod section, '=cut'
544 # HERE - text of here-document
545 # HERE_END - last line of here-doc (target word)
546 # FORMAT - format section
547 # FORMAT_END - last line of format section, '.'
548 # DATA_START - __DATA__ line
549 # DATA - unidentified text following __DATA__
550 # END_START - __END__ line
551 # END - unidentified text following __END__
552 # ERROR - we are in big trouble, probably not a perl script
555 # _curly_brace_depth - depth of curly braces at start of line
556 # _square_bracket_depth - depth of square brackets at start of line
557 # _paren_depth - depth of parens at start of line
558 # _starting_in_quote - this line continues a multi-line quote
559 # (so don't trim leading blanks!)
560 # _ending_in_quote - this line ends in a multi-line quote
561 # (so don't trim trailing blanks!)
562 my $line_of_tokens = {
564 _line_text => $input_line,
565 _line_number => $input_line_number,
566 _rtoken_type => undef,
570 _rblock_type => undef,
571 _rcontainer_type => undef,
572 _rcontainer_environment => undef,
573 _rtype_sequence => undef,
574 _rnesting_tokens => undef,
575 _rci_levels => undef,
576 _rnesting_blocks => undef,
577 _guessed_indentation_level => 0,
578 _starting_in_quote => 0, # to be set by subroutine
579 _ending_in_quote => 0,
580 _curly_brace_depth => $brace_depth,
581 _square_bracket_depth => $square_bracket_depth,
582 _paren_depth => $paren_depth,
583 _quote_character => '',
586 # must print line unchanged if we are in a here document
587 if ( $tokenizer_self->{_in_here_doc} ) {
589 $line_of_tokens->{_line_type} = 'HERE';
590 my $here_doc_target = $tokenizer_self->{_here_doc_target};
591 my $here_quote_character = $tokenizer_self->{_here_quote_character};
592 my $candidate_target = $input_line;
593 chomp $candidate_target;
595 # Handle <<~ targets, which are indicated here by a leading space on
596 # the here quote character
597 if ( $here_quote_character =~ /^\s/ ) {
598 $candidate_target =~ s/^\s*//;
600 if ( $candidate_target eq $here_doc_target ) {
601 $tokenizer_self->{_nearly_matched_here_target_at} = undef;
602 $line_of_tokens->{_line_type} = 'HERE_END';
603 write_logfile_entry("Exiting HERE document $here_doc_target\n");
605 my $rhere_target_list = $tokenizer_self->{_rhere_target_list};
606 if ( @{$rhere_target_list} ) { # there can be multiple here targets
607 ( $here_doc_target, $here_quote_character ) =
608 @{ shift @{$rhere_target_list} };
609 $tokenizer_self->{_here_doc_target} = $here_doc_target;
610 $tokenizer_self->{_here_quote_character} =
611 $here_quote_character;
613 "Entering HERE document $here_doc_target\n");
614 $tokenizer_self->{_nearly_matched_here_target_at} = undef;
615 $tokenizer_self->{_started_looking_for_here_target_at} =
619 $tokenizer_self->{_in_here_doc} = 0;
620 $tokenizer_self->{_here_doc_target} = "";
621 $tokenizer_self->{_here_quote_character} = "";
625 # check for error of extra whitespace
626 # note for PERL6: leading whitespace is allowed
628 $candidate_target =~ s/\s*$//;
629 $candidate_target =~ s/^\s*//;
630 if ( $candidate_target eq $here_doc_target ) {
631 $tokenizer_self->{_nearly_matched_here_target_at} =
635 return $line_of_tokens;
638 # must print line unchanged if we are in a format section
639 elsif ( $tokenizer_self->{_in_format} ) {
641 if ( $input_line =~ /^\.[\s#]*$/ ) {
642 write_logfile_entry("Exiting format section\n");
643 $tokenizer_self->{_in_format} = 0;
644 $line_of_tokens->{_line_type} = 'FORMAT_END';
647 $line_of_tokens->{_line_type} = 'FORMAT';
649 return $line_of_tokens;
652 # must print line unchanged if we are in pod documentation
653 elsif ( $tokenizer_self->{_in_pod} ) {
655 $line_of_tokens->{_line_type} = 'POD';
656 if ( $input_line =~ /^=cut/ ) {
657 $line_of_tokens->{_line_type} = 'POD_END';
658 write_logfile_entry("Exiting POD section\n");
659 $tokenizer_self->{_in_pod} = 0;
661 if ( $input_line =~ /^\#\!.*perl\b/ ) {
663 "Hash-bang in pod can cause older versions of perl to fail! \n"
667 return $line_of_tokens;
670 # must print line unchanged if we have seen a severe error (i.e., we
671 # are seeing illegal tokens and cannot continue. Syntax errors do
672 # not pass this route). Calling routine can decide what to do, but
673 # the default can be to just pass all lines as if they were after __END__
674 elsif ( $tokenizer_self->{_in_error} ) {
675 $line_of_tokens->{_line_type} = 'ERROR';
676 return $line_of_tokens;
679 # print line unchanged if we are __DATA__ section
680 elsif ( $tokenizer_self->{_in_data} ) {
682 # ...but look for POD
683 # Note that the _in_data and _in_end flags remain set
684 # so that we return to that state after seeing the
685 # end of a pod section
686 if ( $input_line =~ /^=(?!cut)/ ) {
687 $line_of_tokens->{_line_type} = 'POD_START';
688 write_logfile_entry("Entering POD section\n");
689 $tokenizer_self->{_in_pod} = 1;
690 return $line_of_tokens;
693 $line_of_tokens->{_line_type} = 'DATA';
694 return $line_of_tokens;
698 # print line unchanged if we are in __END__ section
699 elsif ( $tokenizer_self->{_in_end} ) {
701 # ...but look for POD
702 # Note that the _in_data and _in_end flags remain set
703 # so that we return to that state after seeing the
704 # end of a pod section
705 if ( $input_line =~ /^=(?!cut)/ ) {
706 $line_of_tokens->{_line_type} = 'POD_START';
707 write_logfile_entry("Entering POD section\n");
708 $tokenizer_self->{_in_pod} = 1;
709 return $line_of_tokens;
712 $line_of_tokens->{_line_type} = 'END';
713 return $line_of_tokens;
717 # check for a hash-bang line if we haven't seen one
718 if ( !$tokenizer_self->{_saw_hash_bang} ) {
719 if ( $input_line =~ /^\#\!.*perl\b/ ) {
720 $tokenizer_self->{_saw_hash_bang} = $input_line_number;
722 # check for -w and -P flags
723 if ( $input_line =~ /^\#\!.*perl\s.*-.*P/ ) {
724 $tokenizer_self->{_saw_perl_dash_P} = 1;
727 if ( $input_line =~ /^\#\!.*perl\s.*-.*w/ ) {
728 $tokenizer_self->{_saw_perl_dash_w} = 1;
732 ( $input_line_number > 1 )
734 # leave any hash bang in a BEGIN block alone
735 # i.e. see 'debugger-duck_type.t'
737 $last_nonblank_block_type
738 && $last_nonblank_block_type eq 'BEGIN'
740 && ( !$tokenizer_self->{_look_for_hash_bang} )
744 # this is helpful for VMS systems; we may have accidentally
745 # tokenized some DCL commands
746 if ( $tokenizer_self->{_started_tokenizing} ) {
748 "There seems to be a hash-bang after line 1; do you need to run with -x ?\n"
752 complain("Useless hash-bang after line 1\n");
756 # Report the leading hash-bang as a system line
757 # This will prevent -dac from deleting it
759 $line_of_tokens->{_line_type} = 'SYSTEM';
760 return $line_of_tokens;
765 # wait for a hash-bang before parsing if the user invoked us with -x
766 if ( $tokenizer_self->{_look_for_hash_bang}
767 && !$tokenizer_self->{_saw_hash_bang} )
769 $line_of_tokens->{_line_type} = 'SYSTEM';
770 return $line_of_tokens;
773 # a first line of the form ': #' will be marked as SYSTEM
774 # since lines of this form may be used by tcsh
775 if ( $input_line_number == 1 && $input_line =~ /^\s*\:\s*\#/ ) {
776 $line_of_tokens->{_line_type} = 'SYSTEM';
777 return $line_of_tokens;
780 # now we know that it is ok to tokenize the line...
781 # the line tokenizer will modify any of these private variables:
789 my $ending_in_quote_last = $tokenizer_self->{_in_quote};
790 tokenize_this_line($line_of_tokens);
792 # Now finish defining the return structure and return it
793 $line_of_tokens->{_ending_in_quote} = $tokenizer_self->{_in_quote};
795 # handle severe error (binary data in script)
796 if ( $tokenizer_self->{_in_error} ) {
797 $tokenizer_self->{_in_quote} = 0; # to avoid any more messages
798 warning("Giving up after error\n");
799 $line_of_tokens->{_line_type} = 'ERROR';
800 reset_indentation_level(0); # avoid error messages
801 return $line_of_tokens;
804 # handle start of pod documentation
805 if ( $tokenizer_self->{_in_pod} ) {
807 # This gets tricky..above a __DATA__ or __END__ section, perl
808 # accepts '=cut' as the start of pod section. But afterwards,
809 # only pod utilities see it and they may ignore an =cut without
810 # leading =head. In any case, this isn't good.
811 if ( $input_line =~ /^=cut\b/ ) {
812 if ( $tokenizer_self->{_saw_data} || $tokenizer_self->{_saw_end} ) {
813 complain("=cut while not in pod ignored\n");
814 $tokenizer_self->{_in_pod} = 0;
815 $line_of_tokens->{_line_type} = 'POD_END';
818 $line_of_tokens->{_line_type} = 'POD_START';
820 "=cut starts a pod section .. this can fool pod utilities.\n"
822 write_logfile_entry("Entering POD section\n");
827 $line_of_tokens->{_line_type} = 'POD_START';
828 write_logfile_entry("Entering POD section\n");
831 return $line_of_tokens;
834 # update indentation levels for log messages
835 if ( $input_line !~ /^\s*$/ ) {
836 my $rlevels = $line_of_tokens->{_rlevels};
837 $line_of_tokens->{_guessed_indentation_level} =
838 guess_old_indentation_level($input_line);
841 # see if this line contains here doc targets
842 my $rhere_target_list = $tokenizer_self->{_rhere_target_list};
843 if ( @{$rhere_target_list} ) {
845 my ( $here_doc_target, $here_quote_character ) =
846 @{ shift @{$rhere_target_list} };
847 $tokenizer_self->{_in_here_doc} = 1;
848 $tokenizer_self->{_here_doc_target} = $here_doc_target;
849 $tokenizer_self->{_here_quote_character} = $here_quote_character;
850 write_logfile_entry("Entering HERE document $here_doc_target\n");
851 $tokenizer_self->{_started_looking_for_here_target_at} =
855 # NOTE: __END__ and __DATA__ statements are written unformatted
856 # because they can theoretically contain additional characters
857 # which are not tokenized (and cannot be read with <DATA> either!).
858 if ( $tokenizer_self->{_in_data} ) {
859 $line_of_tokens->{_line_type} = 'DATA_START';
860 write_logfile_entry("Starting __DATA__ section\n");
861 $tokenizer_self->{_saw_data} = 1;
863 # keep parsing after __DATA__ if use SelfLoader was seen
864 if ( $tokenizer_self->{_saw_selfloader} ) {
865 $tokenizer_self->{_in_data} = 0;
867 "SelfLoader seen, continuing; -nlsl deactivates\n");
870 return $line_of_tokens;
873 elsif ( $tokenizer_self->{_in_end} ) {
874 $line_of_tokens->{_line_type} = 'END_START';
875 write_logfile_entry("Starting __END__ section\n");
876 $tokenizer_self->{_saw_end} = 1;
878 # keep parsing after __END__ if use AutoLoader was seen
879 if ( $tokenizer_self->{_saw_autoloader} ) {
880 $tokenizer_self->{_in_end} = 0;
882 "AutoLoader seen, continuing; -nlal deactivates\n");
884 return $line_of_tokens;
887 # now, finally, we know that this line is type 'CODE'
888 $line_of_tokens->{_line_type} = 'CODE';
890 # remember if we have seen any real code
891 if ( !$tokenizer_self->{_started_tokenizing}
892 && $input_line !~ /^\s*$/
893 && $input_line !~ /^\s*#/ )
895 $tokenizer_self->{_started_tokenizing} = 1;
898 if ( $tokenizer_self->{_debugger_object} ) {
899 $tokenizer_self->{_debugger_object}->write_debug_entry($line_of_tokens);
902 # Note: if keyword 'format' occurs in this line code, it is still CODE
903 # (keyword 'format' need not start a line)
904 if ( $tokenizer_self->{_in_format} ) {
905 write_logfile_entry("Entering format section\n");
908 if ( $tokenizer_self->{_in_quote}
909 and ( $tokenizer_self->{_line_start_quote} < 0 ) )
912 #if ( ( my $quote_target = get_quote_target() ) !~ /^\s*$/ ) {
914 ( my $quote_target = $tokenizer_self->{_quote_target} ) !~ /^\s*$/ )
916 $tokenizer_self->{_line_start_quote} = $input_line_number;
918 "Start multi-line quote or pattern ending in $quote_target\n");
921 elsif ( ( $tokenizer_self->{_line_start_quote} >= 0 )
922 && !$tokenizer_self->{_in_quote} )
924 $tokenizer_self->{_line_start_quote} = -1;
925 write_logfile_entry("End of multi-line quote or pattern\n");
928 # we are returning a line of CODE
929 return $line_of_tokens;
932 sub find_starting_indentation_level {
934 # We need to find the indentation level of the first line of the
935 # script being formatted. Often it will be zero for an entire file,
936 # but if we are formatting a local block of code (within an editor for
937 # example) it may not be zero. The user may specify this with the
938 # -sil=n parameter but normally doesn't so we have to guess.
940 # USES GLOBAL VARIABLES: $tokenizer_self
941 my $starting_level = 0;
943 # use value if given as parameter
944 if ( $tokenizer_self->{_know_starting_level} ) {
945 $starting_level = $tokenizer_self->{_starting_level};
948 # if we know there is a hash_bang line, the level must be zero
949 elsif ( $tokenizer_self->{_look_for_hash_bang} ) {
950 $tokenizer_self->{_know_starting_level} = 1;
953 # otherwise figure it out from the input file
958 # keep looking at lines until we find a hash bang or piece of code
961 $tokenizer_self->{_line_buffer_object}->peek_ahead( $i++ ) )
964 # if first line is #! then assume starting level is zero
965 if ( $i == 1 && $line =~ /^\#\!/ ) {
969 next if ( $line =~ /^\s*#/ ); # skip past comments
970 next if ( $line =~ /^\s*$/ ); # skip past blank lines
971 $starting_level = guess_old_indentation_level($line);
974 $msg = "Line $i implies starting-indentation-level = $starting_level\n";
975 write_logfile_entry("$msg");
977 $tokenizer_self->{_starting_level} = $starting_level;
978 reset_indentation_level($starting_level);
982 sub guess_old_indentation_level {
985 # Guess the indentation level of an input line.
987 # For the first line of code this result will define the starting
988 # indentation level. It will mainly be non-zero when perltidy is applied
989 # within an editor to a local block of code.
991 # This is an impossible task in general because we can't know what tabs
992 # meant for the old script and how many spaces were used for one
993 # indentation level in the given input script. For example it may have
994 # been previously formatted with -i=7 -et=3. But we can at least try to
995 # make sure that perltidy guesses correctly if it is applied repeatedly to
996 # a block of code within an editor, so that the block stays at the same
997 # level when perltidy is applied repeatedly.
999 # USES GLOBAL VARIABLES: $tokenizer_self
1002 # find leading tabs, spaces, and any statement label
1004 if ( $line =~ /^(\t+)?(\s+)?(\w+:[^:])?/ ) {
1006 # If there are leading tabs, we use the tab scheme for this run, if
1007 # any, so that the code will remain stable when editing.
1008 if ($1) { $spaces += length($1) * $tokenizer_self->{_tabsize} }
1010 if ($2) { $spaces += length($2) }
1012 # correct for outdented labels
1013 if ( $3 && $tokenizer_self->{'_outdent_labels'} ) {
1014 $spaces += $tokenizer_self->{_continuation_indentation};
1018 # compute indentation using the value of -i for this run.
1019 # If -i=0 is used for this run (which is possible) it doesn't matter
1020 # what we do here but we'll guess that the old run used 4 spaces per level.
1021 my $indent_columns = $tokenizer_self->{_indent_columns};
1022 $indent_columns = 4 if ( !$indent_columns );
1023 $level = int( $spaces / $indent_columns );
1027 # This is a currently unused debug routine
1028 sub dump_functions {
1031 foreach my $pkg ( keys %is_user_function ) {
1032 print $fh "\nnon-constant subs in package $pkg\n";
1034 foreach my $sub ( keys %{ $is_user_function{$pkg} } ) {
1036 if ( $is_block_list_function{$pkg}{$sub} ) {
1037 $msg = 'block_list';
1040 if ( $is_block_function{$pkg}{$sub} ) {
1043 print $fh "$sub $msg\n";
1047 foreach my $pkg ( keys %is_constant ) {
1048 print $fh "\nconstants and constant subs in package $pkg\n";
1050 foreach my $sub ( keys %{ $is_constant{$pkg} } ) {
1059 # count number of 1's in a string of 1's and 0's
1060 # example: ones_count("010101010101") gives 6
1062 return $str =~ tr/1/0/;
1065 sub prepare_for_a_new_file {
1067 # previous tokens needed to determine what to expect next
1068 $last_nonblank_token = ';'; # the only possible starting state which
1069 $last_nonblank_type = ';'; # will make a leading brace a code block
1070 $last_nonblank_block_type = '';
1072 # scalars for remembering statement types across multiple lines
1073 $statement_type = ''; # '' or 'use' or 'sub..' or 'case..'
1074 $in_attribute_list = 0;
1076 # scalars for remembering where we are in the file
1077 $current_package = "main";
1078 $context = UNKNOWN_CONTEXT;
1080 # hashes used to remember function information
1081 %is_constant = (); # user-defined constants
1082 %is_user_function = (); # user-defined functions
1083 %user_function_prototype = (); # their prototypes
1084 %is_block_function = ();
1085 %is_block_list_function = ();
1086 %saw_function_definition = ();
1088 # variables used to track depths of various containers
1089 # and report nesting errors
1092 $square_bracket_depth = 0;
1093 @current_depth = (0) x scalar @closing_brace_names;
1096 @nesting_sequence_number = ( 0 .. @closing_brace_names - 1 );
1097 @current_sequence_number = ();
1098 $paren_type[$paren_depth] = '';
1099 $paren_semicolon_count[$paren_depth] = 0;
1100 $paren_structural_type[$brace_depth] = '';
1101 $brace_type[$brace_depth] = ';'; # identify opening brace as code block
1102 $brace_structural_type[$brace_depth] = '';
1103 $brace_context[$brace_depth] = UNKNOWN_CONTEXT;
1104 $brace_package[$paren_depth] = $current_package;
1105 $square_bracket_type[$square_bracket_depth] = '';
1106 $square_bracket_structural_type[$square_bracket_depth] = '';
1108 initialize_tokenizer_state();
1112 { # begin tokenize_this_line
1114 use constant BRACE => 0;
1115 use constant SQUARE_BRACKET => 1;
1116 use constant PAREN => 2;
1117 use constant QUESTION_COLON => 3;
1119 # TV1: scalars for processing one LINE.
1120 # Re-initialized on each entry to sub tokenize_this_line.
1122 $block_type, $container_type, $expecting,
1123 $i, $i_tok, $input_line,
1124 $input_line_number, $last_nonblank_i, $max_token_index,
1125 $next_tok, $next_type, $peeked_ahead,
1126 $prototype, $rhere_target_list, $rtoken_map,
1127 $rtoken_type, $rtokens, $tok,
1128 $type, $type_sequence, $indent_flag,
1131 # TV2: refs to ARRAYS for processing one LINE
1132 # Re-initialized on each call.
1133 my $routput_token_list = []; # stack of output token indexes
1134 my $routput_token_type = []; # token types
1135 my $routput_block_type = []; # types of code block
1136 my $routput_container_type = []; # paren types, such as if, elsif, ..
1137 my $routput_type_sequence = []; # nesting sequential number
1138 my $routput_indent_flag = []; #
1140 # TV3: SCALARS for quote variables. These are initialized with a
1141 # subroutine call and continually updated as lines are processed.
1142 my ( $in_quote, $quote_type, $quote_character, $quote_pos, $quote_depth,
1143 $quoted_string_1, $quoted_string_2, $allowed_quote_modifiers, );
1145 # TV4: SCALARS for multi-line identifiers and
1146 # statements. These are initialized with a subroutine call
1147 # and continually updated as lines are processed.
1148 my ( $id_scan_state, $identifier, $want_paren, $indented_if_level );
1150 # TV5: SCALARS for tracking indentation level.
1151 # Initialized once and continually updated as lines are
1154 $nesting_token_string, $nesting_type_string,
1155 $nesting_block_string, $nesting_block_flag,
1156 $nesting_list_string, $nesting_list_flag,
1157 $ci_string_in_tokenizer, $continuation_string_in_tokenizer,
1158 $in_statement_continuation, $level_in_tokenizer,
1159 $slevel_in_tokenizer, $rslevel_stack,
1162 # TV6: SCALARS for remembering several previous
1163 # tokens. Initialized once and continually updated as
1164 # lines are processed.
1166 $last_nonblank_container_type, $last_nonblank_type_sequence,
1167 $last_last_nonblank_token, $last_last_nonblank_type,
1168 $last_last_nonblank_block_type, $last_last_nonblank_container_type,
1169 $last_last_nonblank_type_sequence, $last_nonblank_prototype,
1172 # ----------------------------------------------------------------
1173 # beginning of tokenizer variable access and manipulation routines
1174 # ----------------------------------------------------------------
1176 sub initialize_tokenizer_state {
1178 # TV1: initialized on each call
1179 # TV2: initialized on each call
1183 $quote_character = "";
1186 $quoted_string_1 = "";
1187 $quoted_string_2 = "";
1188 $allowed_quote_modifiers = "";
1191 $id_scan_state = '';
1194 $indented_if_level = 0;
1197 $nesting_token_string = "";
1198 $nesting_type_string = "";
1199 $nesting_block_string = '1'; # initially in a block
1200 $nesting_block_flag = 1;
1201 $nesting_list_string = '0'; # initially not in a list
1202 $nesting_list_flag = 0; # initially not in a list
1203 $ci_string_in_tokenizer = "";
1204 $continuation_string_in_tokenizer = "0";
1205 $in_statement_continuation = 0;
1206 $level_in_tokenizer = 0;
1207 $slevel_in_tokenizer = 0;
1208 $rslevel_stack = [];
1211 $last_nonblank_container_type = '';
1212 $last_nonblank_type_sequence = '';
1213 $last_last_nonblank_token = ';';
1214 $last_last_nonblank_type = ';';
1215 $last_last_nonblank_block_type = '';
1216 $last_last_nonblank_container_type = '';
1217 $last_last_nonblank_type_sequence = '';
1218 $last_nonblank_prototype = "";
1222 sub save_tokenizer_state {
1225 $block_type, $container_type, $expecting,
1226 $i, $i_tok, $input_line,
1227 $input_line_number, $last_nonblank_i, $max_token_index,
1228 $next_tok, $next_type, $peeked_ahead,
1229 $prototype, $rhere_target_list, $rtoken_map,
1230 $rtoken_type, $rtokens, $tok,
1231 $type, $type_sequence, $indent_flag,
1235 $routput_token_list, $routput_token_type,
1236 $routput_block_type, $routput_container_type,
1237 $routput_type_sequence, $routput_indent_flag,
1241 $in_quote, $quote_type,
1242 $quote_character, $quote_pos,
1243 $quote_depth, $quoted_string_1,
1244 $quoted_string_2, $allowed_quote_modifiers,
1248 [ $id_scan_state, $identifier, $want_paren, $indented_if_level ];
1251 $nesting_token_string, $nesting_type_string,
1252 $nesting_block_string, $nesting_block_flag,
1253 $nesting_list_string, $nesting_list_flag,
1254 $ci_string_in_tokenizer, $continuation_string_in_tokenizer,
1255 $in_statement_continuation, $level_in_tokenizer,
1256 $slevel_in_tokenizer, $rslevel_stack,
1260 $last_nonblank_container_type,
1261 $last_nonblank_type_sequence,
1262 $last_last_nonblank_token,
1263 $last_last_nonblank_type,
1264 $last_last_nonblank_block_type,
1265 $last_last_nonblank_container_type,
1266 $last_last_nonblank_type_sequence,
1267 $last_nonblank_prototype,
1269 return [ $rTV1, $rTV2, $rTV3, $rTV4, $rTV5, $rTV6 ];
1272 sub restore_tokenizer_state {
1274 my ( $rTV1, $rTV2, $rTV3, $rTV4, $rTV5, $rTV6 ) = @{$rstate};
1276 $block_type, $container_type, $expecting,
1277 $i, $i_tok, $input_line,
1278 $input_line_number, $last_nonblank_i, $max_token_index,
1279 $next_tok, $next_type, $peeked_ahead,
1280 $prototype, $rhere_target_list, $rtoken_map,
1281 $rtoken_type, $rtokens, $tok,
1282 $type, $type_sequence, $indent_flag,
1286 $routput_token_list, $routput_token_type,
1287 $routput_block_type, $routput_container_type,
1288 $routput_type_sequence, $routput_type_sequence,
1292 $in_quote, $quote_type, $quote_character, $quote_pos, $quote_depth,
1293 $quoted_string_1, $quoted_string_2, $allowed_quote_modifiers,
1296 ( $id_scan_state, $identifier, $want_paren, $indented_if_level ) =
1300 $nesting_token_string, $nesting_type_string,
1301 $nesting_block_string, $nesting_block_flag,
1302 $nesting_list_string, $nesting_list_flag,
1303 $ci_string_in_tokenizer, $continuation_string_in_tokenizer,
1304 $in_statement_continuation, $level_in_tokenizer,
1305 $slevel_in_tokenizer, $rslevel_stack,
1309 $last_nonblank_container_type,
1310 $last_nonblank_type_sequence,
1311 $last_last_nonblank_token,
1312 $last_last_nonblank_type,
1313 $last_last_nonblank_block_type,
1314 $last_last_nonblank_container_type,
1315 $last_last_nonblank_type_sequence,
1316 $last_nonblank_prototype,
1321 sub get_indentation_level {
1323 # patch to avoid reporting error if indented if is not terminated
1324 if ($indented_if_level) { return $level_in_tokenizer - 1 }
1325 return $level_in_tokenizer;
1328 sub reset_indentation_level {
1329 $level_in_tokenizer = $slevel_in_tokenizer = shift;
1330 push @{$rslevel_stack}, $slevel_in_tokenizer;
1336 $peeked_ahead = defined($flag) ? $flag : $peeked_ahead;
1337 return $peeked_ahead;
1340 # ------------------------------------------------------------
1341 # end of tokenizer variable access and manipulation routines
1342 # ------------------------------------------------------------
1344 # ------------------------------------------------------------
1345 # beginning of various scanner interface routines
1346 # ------------------------------------------------------------
1347 sub scan_replacement_text {
1349 # check for here-docs in replacement text invoked by
1350 # a substitution operator with executable modifier 'e'.
1355 # $rht = reference to any here-doc targets
1356 my ($replacement_text) = @_;
1359 return unless ( $replacement_text =~ /<</ );
1361 write_logfile_entry("scanning replacement text for here-doc targets\n");
1363 # save the logger object for error messages
1364 my $logger_object = $tokenizer_self->{_logger_object};
1366 # localize all package variables
1368 $tokenizer_self, $last_nonblank_token,
1369 $last_nonblank_type, $last_nonblank_block_type,
1370 $statement_type, $in_attribute_list,
1371 $current_package, $context,
1372 %is_constant, %is_user_function,
1373 %user_function_prototype, %is_block_function,
1374 %is_block_list_function, %saw_function_definition,
1375 $brace_depth, $paren_depth,
1376 $square_bracket_depth, @current_depth,
1377 @total_depth, $total_depth,
1378 @nesting_sequence_number, @current_sequence_number,
1379 @paren_type, @paren_semicolon_count,
1380 @paren_structural_type, @brace_type,
1381 @brace_structural_type, @brace_context,
1382 @brace_package, @square_bracket_type,
1383 @square_bracket_structural_type, @depth_array,
1384 @starting_line_of_current_depth, @nested_ternary_flag,
1385 @nested_statement_type,
1388 # save all lexical variables
1389 my $rstate = save_tokenizer_state();
1390 _decrement_count(); # avoid error check for multiple tokenizers
1392 # make a new tokenizer
1394 my $rpending_logfile_message;
1396 Perl::Tidy::LineSource->new( \$replacement_text, $rOpts,
1397 $rpending_logfile_message );
1398 my $tokenizer = Perl::Tidy::Tokenizer->new(
1399 source_object => $source_object,
1400 logger_object => $logger_object,
1401 starting_line_number => $input_line_number,
1404 # scan the replacement text
1405 1 while ( $tokenizer->get_line() );
1407 # remove any here doc targets
1409 if ( $tokenizer_self->{_in_here_doc} ) {
1413 $tokenizer_self->{_here_doc_target},
1414 $tokenizer_self->{_here_quote_character}
1416 if ( $tokenizer_self->{_rhere_target_list} ) {
1417 push @{$rht}, @{ $tokenizer_self->{_rhere_target_list} };
1418 $tokenizer_self->{_rhere_target_list} = undef;
1420 $tokenizer_self->{_in_here_doc} = undef;
1423 # now its safe to report errors
1424 my $severe_error = $tokenizer->report_tokenization_errors();
1426 # TODO: Could propagate a severe error up
1428 # restore all tokenizer lexical variables
1429 restore_tokenizer_state($rstate);
1431 # return the here doc targets
1435 sub scan_bare_identifier {
1436 ( $i, $tok, $type, $prototype ) =
1437 scan_bare_identifier_do( $input_line, $i, $tok, $type, $prototype,
1438 $rtoken_map, $max_token_index );
1442 sub scan_identifier {
1443 ( $i, $tok, $type, $id_scan_state, $identifier ) =
1444 scan_identifier_do( $i, $id_scan_state, $identifier, $rtokens,
1445 $max_token_index, $expecting, $paren_type[$paren_depth] );
1450 ( $i, $tok, $type, $id_scan_state ) =
1451 scan_id_do( $input_line, $i, $tok, $rtokens, $rtoken_map,
1452 $id_scan_state, $max_token_index );
1458 ( $i, $type, $number ) =
1459 scan_number_do( $input_line, $i, $rtoken_map, $type,
1464 # a sub to warn if token found where term expected
1465 sub error_if_expecting_TERM {
1466 if ( $expecting == TERM ) {
1467 if ( $really_want_term{$last_nonblank_type} ) {
1468 report_unexpected( $tok, "term", $i_tok, $last_nonblank_i,
1469 $rtoken_map, $rtoken_type, $input_line );
1476 # a sub to warn if token found where operator expected
1477 sub error_if_expecting_OPERATOR {
1479 if ( $expecting == OPERATOR ) {
1480 if ( !defined($thing) ) { $thing = $tok }
1481 report_unexpected( $thing, "operator", $i_tok, $last_nonblank_i,
1482 $rtoken_map, $rtoken_type, $input_line );
1483 if ( $i_tok == 0 ) {
1484 interrupt_logfile();
1485 warning("Missing ';' above?\n");
1493 # ------------------------------------------------------------
1494 # end scanner interfaces
1495 # ------------------------------------------------------------
1498 @_ = qw(for foreach);
1499 @is_for_foreach{@_} = (1) x scalar(@_);
1503 @is_my_our{@_} = (1) x scalar(@_);
1505 # These keywords may introduce blocks after parenthesized expressions,
1507 # keyword ( .... ) { BLOCK }
1508 # patch for SWITCH/CASE: added 'switch' 'case' 'given' 'when'
1509 my %is_blocktype_with_paren;
1511 qw(if elsif unless while until for foreach switch case given when catch);
1512 @is_blocktype_with_paren{@_} = (1) x scalar(@_);
1514 # ------------------------------------------------------------
1515 # begin hash of code for handling most token types
1516 # ------------------------------------------------------------
1517 my $tokenization_code = {
1519 # no special code for these types yet, but syntax checks
1554 error_if_expecting_TERM()
1555 if ( $expecting == TERM );
1558 error_if_expecting_TERM()
1559 if ( $expecting == TERM );
1563 # start looking for a scalar
1564 error_if_expecting_OPERATOR("Scalar")
1565 if ( $expecting == OPERATOR );
1568 if ( $identifier eq '$^W' ) {
1569 $tokenizer_self->{_saw_perl_dash_w} = 1;
1572 # Check for identifier in indirect object slot
1573 # (vorboard.pl, sort.t). Something like:
1574 # /^(print|printf|sort|exec|system)$/
1576 $is_indirect_object_taker{$last_nonblank_token}
1578 || ( ( $last_nonblank_token eq '(' )
1579 && $is_indirect_object_taker{ $paren_type[$paren_depth] } )
1580 || ( $last_nonblank_type =~ /^[Uw]$/ ) # possible object
1589 $paren_semicolon_count[$paren_depth] = 0;
1591 $container_type = $want_paren;
1594 elsif ( $statement_type =~ /^sub\b/ ) {
1595 $container_type = $statement_type;
1598 $container_type = $last_nonblank_token;
1600 # We can check for a syntax error here of unexpected '(',
1601 # but this is going to get messy...
1603 $expecting == OPERATOR
1605 # be sure this is not a method call of the form
1606 # &method(...), $method->(..), &{method}(...),
1607 # $ref[2](list) is ok & short for $ref[2]->(list)
1608 # NOTE: at present, braces in something like &{ xxx }
1609 # are not marked as a block, we might have a method call
1610 && $last_nonblank_token !~ /^([\]\}\&]|\-\>)/
1615 # ref: camel 3 p 703.
1616 if ( $last_last_nonblank_token eq 'do' ) {
1618 "do SUBROUTINE is deprecated; consider & or -> notation\n"
1623 # if this is an empty list, (), then it is not an
1624 # error; for example, we might have a constant pi and
1625 # invoke it with pi() or just pi;
1626 my ( $next_nonblank_token, $i_next ) =
1627 find_next_nonblank_token( $i, $rtokens,
1629 if ( $next_nonblank_token ne ')' ) {
1631 error_if_expecting_OPERATOR('(');
1633 if ( $last_nonblank_type eq 'C' ) {
1635 "$last_nonblank_token has a void prototype\n";
1637 elsif ( $last_nonblank_type eq 'i' ) {
1639 && $last_nonblank_token =~ /^\$/ )
1642 "Do you mean '$last_nonblank_token->(' ?\n";
1646 interrupt_logfile();
1650 } ## end if ( $next_nonblank_token...
1651 } ## end else [ if ( $last_last_nonblank_token...
1652 } ## end if ( $expecting == OPERATOR...
1654 $paren_type[$paren_depth] = $container_type;
1655 ( $type_sequence, $indent_flag ) =
1656 increase_nesting_depth( PAREN, $rtoken_map->[$i_tok] );
1658 # propagate types down through nested parens
1659 # for example: the second paren in 'if ((' would be structural
1660 # since the first is.
1662 if ( $last_nonblank_token eq '(' ) {
1663 $type = $last_nonblank_type;
1666 # We exclude parens as structural after a ',' because it
1667 # causes subtle problems with continuation indentation for
1668 # something like this, where the first 'or' will not get
1673 # ( not defined $check )
1675 # or $check eq "new"
1676 # or $check eq "old",
1679 # Likewise, we exclude parens where a statement can start
1680 # because of problems with continuation indentation, like
1683 # ($firstline =~ /^#\!.*perl/)
1684 # and (print $File::Find::name, "\n")
1687 # (ref($usage_fref) =~ /CODE/)
1689 # : (&blast_usage, &blast_params, &blast_general_params);
1695 if ( $last_nonblank_type eq ')' ) {
1697 "Syntax error? found token '$last_nonblank_type' then '('\n"
1700 $paren_structural_type[$paren_depth] = $type;
1704 ( $type_sequence, $indent_flag ) =
1705 decrease_nesting_depth( PAREN, $rtoken_map->[$i_tok] );
1707 if ( $paren_structural_type[$paren_depth] eq '{' ) {
1711 $container_type = $paren_type[$paren_depth];
1713 # restore statement type as 'sub' at closing paren of a signature
1714 # so that a subsequent ':' is identified as an attribute
1715 if ( $container_type =~ /^sub\b/ ) {
1716 $statement_type = $container_type;
1720 if ( $is_for_foreach{ $paren_type[$paren_depth] } ) {
1721 my $num_sc = $paren_semicolon_count[$paren_depth];
1722 if ( $num_sc > 0 && $num_sc != 2 ) {
1723 warning("Expected 2 ';' in 'for(;;)' but saw $num_sc\n");
1727 if ( $paren_depth > 0 ) { $paren_depth-- }
1730 if ( $last_nonblank_type eq ',' ) {
1731 complain("Repeated ','s \n");
1734 # patch for operator_expected: note if we are in the list (use.t)
1735 if ( $statement_type eq 'use' ) { $statement_type = '_use' }
1736 ## FIXME: need to move this elsewhere, perhaps check after a '('
1737 ## elsif ($last_nonblank_token eq '(') {
1738 ## warning("Leading ','s illegal in some versions of perl\n");
1742 $context = UNKNOWN_CONTEXT;
1743 $statement_type = '';
1747 if ( $is_for_foreach{ $paren_type[$paren_depth] } )
1748 { # mark ; in for loop
1750 # Be careful: we do not want a semicolon such as the
1751 # following to be included:
1753 # for (sort {strcoll($a,$b);} keys %investments) {
1755 if ( $brace_depth == $depth_array[PAREN][BRACE][$paren_depth]
1756 && $square_bracket_depth ==
1757 $depth_array[PAREN][SQUARE_BRACKET][$paren_depth] )
1761 $paren_semicolon_count[$paren_depth]++;
1767 error_if_expecting_OPERATOR("String")
1768 if ( $expecting == OPERATOR );
1771 $allowed_quote_modifiers = "";
1774 error_if_expecting_OPERATOR("String")
1775 if ( $expecting == OPERATOR );
1778 $allowed_quote_modifiers = "";
1781 error_if_expecting_OPERATOR("String")
1782 if ( $expecting == OPERATOR );
1785 $allowed_quote_modifiers = "";
1790 # a pattern cannot follow certain keywords which take optional
1791 # arguments, like 'shift' and 'pop'. See also '?'.
1792 if ( $last_nonblank_type eq 'k'
1793 && $is_keyword_taking_optional_args{$last_nonblank_token} )
1797 elsif ( $expecting == UNKNOWN ) { # indeterminate, must guess..
1799 ( $is_pattern, $msg ) =
1800 guess_if_pattern_or_division( $i, $rtokens, $rtoken_map,
1804 write_diagnostics("DIVIDE:$msg\n");
1805 write_logfile_entry($msg);
1808 else { $is_pattern = ( $expecting == TERM ) }
1813 $allowed_quote_modifiers = '[msixpodualngc]';
1815 else { # not a pattern; check for a /= token
1817 if ( $rtokens->[ $i + 1 ] eq '=' ) { # form token /=
1823 #DEBUG - collecting info on what tokens follow a divide
1824 # for development of guessing algorithm
1825 #if ( numerator_expected( $i, $rtokens, $max_token_index ) < 0 ) {
1826 # #write_diagnostics( "DIVIDE? $input_line\n" );
1832 # if we just saw a ')', we will label this block with
1833 # its type. We need to do this to allow sub
1834 # code_block_type to determine if this brace starts a
1835 # code block or anonymous hash. (The type of a paren
1836 # pair is the preceding token, such as 'if', 'else',
1838 $container_type = "";
1840 # ATTRS: for a '{' following an attribute list, reset
1841 # things to look like we just saw the sub name
1842 if ( $statement_type =~ /^sub/ ) {
1843 $last_nonblank_token = $statement_type;
1844 $last_nonblank_type = 'i';
1845 $statement_type = "";
1848 # patch for SWITCH/CASE: hide these keywords from an immediately
1849 # following opening brace
1850 elsif ( ( $statement_type eq 'case' || $statement_type eq 'when' )
1851 && $statement_type eq $last_nonblank_token )
1853 $last_nonblank_token = ";";
1856 elsif ( $last_nonblank_token eq ')' ) {
1857 $last_nonblank_token = $paren_type[ $paren_depth + 1 ];
1859 # defensive move in case of a nesting error (pbug.t)
1860 # in which this ')' had no previous '('
1861 # this nesting error will have been caught
1862 if ( !defined($last_nonblank_token) ) {
1863 $last_nonblank_token = 'if';
1866 # check for syntax error here;
1867 unless ( $is_blocktype_with_paren{$last_nonblank_token} ) {
1868 if ( $tokenizer_self->{'_extended_syntax'} ) {
1870 # we append a trailing () to mark this as an unknown
1871 # block type. This allows perltidy to format some
1872 # common extensions of perl syntax.
1873 # This is used by sub code_block_type
1874 $last_nonblank_token .= '()';
1878 join( ' ', sort keys %is_blocktype_with_paren );
1880 "syntax error at ') {', didn't see one of: <<$list>>; If this code is okay try using the -xs flag\n"
1886 # patch for paren-less for/foreach glitch, part 2.
1887 # see note below under 'qw'
1888 elsif ($last_nonblank_token eq 'qw'
1889 && $is_for_foreach{$want_paren} )
1891 $last_nonblank_token = $want_paren;
1892 if ( $last_last_nonblank_token eq $want_paren ) {
1894 "syntax error at '$want_paren .. {' -- missing \$ loop variable\n"
1901 # now identify which of the three possible types of
1902 # curly braces we have: hash index container, anonymous
1903 # hash reference, or code block.
1905 # non-structural (hash index) curly brace pair
1906 # get marked 'L' and 'R'
1907 if ( is_non_structural_brace() ) {
1910 # patch for SWITCH/CASE:
1911 # allow paren-less identifier after 'when'
1912 # if the brace is preceded by a space
1913 if ( $statement_type eq 'when'
1914 && $last_nonblank_type eq 'i'
1915 && $last_last_nonblank_type eq 'k'
1916 && ( $i_tok == 0 || $rtoken_type->[ $i_tok - 1 ] eq 'b' ) )
1919 $block_type = $statement_type;
1923 # code and anonymous hash have the same type, '{', but are
1924 # distinguished by 'block_type',
1925 # which will be blank for an anonymous hash
1928 $block_type = code_block_type( $i_tok, $rtokens, $rtoken_type,
1931 # patch to promote bareword type to function taking block
1933 && $last_nonblank_type eq 'w'
1934 && $last_nonblank_i >= 0 )
1936 if ( $routput_token_type->[$last_nonblank_i] eq 'w' ) {
1937 $routput_token_type->[$last_nonblank_i] = 'G';
1941 # patch for SWITCH/CASE: if we find a stray opening block brace
1942 # where we might accept a 'case' or 'when' block, then take it
1943 if ( $statement_type eq 'case'
1944 || $statement_type eq 'when' )
1946 if ( !$block_type || $block_type eq '}' ) {
1947 $block_type = $statement_type;
1952 $brace_type[ ++$brace_depth ] = $block_type;
1953 $brace_package[$brace_depth] = $current_package;
1954 $brace_structural_type[$brace_depth] = $type;
1955 $brace_context[$brace_depth] = $context;
1956 ( $type_sequence, $indent_flag ) =
1957 increase_nesting_depth( BRACE, $rtoken_map->[$i_tok] );
1960 $block_type = $brace_type[$brace_depth];
1961 if ($block_type) { $statement_type = '' }
1962 if ( defined( $brace_package[$brace_depth] ) ) {
1963 $current_package = $brace_package[$brace_depth];
1966 # can happen on brace error (caught elsewhere)
1969 ( $type_sequence, $indent_flag ) =
1970 decrease_nesting_depth( BRACE, $rtoken_map->[$i_tok] );
1972 if ( $brace_structural_type[$brace_depth] eq 'L' ) {
1976 # propagate type information for 'do' and 'eval' blocks, and also
1977 # for smartmatch operator. This is necessary to enable us to know
1978 # if an operator or term is expected next.
1979 if ( $is_block_operator{$block_type} ) {
1983 $context = $brace_context[$brace_depth];
1984 if ( $brace_depth > 0 ) { $brace_depth--; }
1986 '&' => sub { # maybe sub call? start looking
1988 # We have to check for sub call unless we are sure we
1989 # are expecting an operator. This example from s2p
1990 # got mistaken as a q operator in an early version:
1991 # print BODY &q(<<'EOT');
1992 if ( $expecting != OPERATOR ) {
1994 # But only look for a sub call if we are expecting a term or
1995 # if there is no existing space after the &.
1996 # For example we probably don't want & as sub call here:
1997 # Fcntl::S_IRUSR & $mode;
1998 if ( $expecting == TERM || $next_type ne 'b' ) {
2005 '<' => sub { # angle operator or less than?
2007 if ( $expecting != OPERATOR ) {
2009 find_angle_operator_termination( $input_line, $i, $rtoken_map,
2010 $expecting, $max_token_index );
2012 if ( $type eq '<' && $expecting == TERM ) {
2013 error_if_expecting_TERM();
2014 interrupt_logfile();
2015 warning("Unterminated <> operator?\n");
2022 '?' => sub { # ?: conditional or starting pattern?
2026 # Patch for rt #126965
2027 # a pattern cannot follow certain keywords which take optional
2028 # arguments, like 'shift' and 'pop'. See also '/'.
2029 if ( $last_nonblank_type eq 'k'
2030 && $is_keyword_taking_optional_args{$last_nonblank_token} )
2034 elsif ( $expecting == UNKNOWN ) {
2037 ( $is_pattern, $msg ) =
2038 guess_if_pattern_or_conditional( $i, $rtokens, $rtoken_map,
2041 if ($msg) { write_logfile_entry($msg) }
2043 else { $is_pattern = ( $expecting == TERM ) }
2048 $allowed_quote_modifiers = '[msixpodualngc]';
2051 ( $type_sequence, $indent_flag ) =
2052 increase_nesting_depth( QUESTION_COLON,
2053 $rtoken_map->[$i_tok] );
2056 '*' => sub { # typeglob, or multiply?
2058 if ( $expecting == TERM ) {
2063 if ( $rtokens->[ $i + 1 ] eq '=' ) {
2068 elsif ( $rtokens->[ $i + 1 ] eq '*' ) {
2072 if ( $rtokens->[ $i + 1 ] eq '=' ) {
2080 '.' => sub { # what kind of . ?
2082 if ( $expecting != OPERATOR ) {
2084 if ( $type eq '.' ) {
2085 error_if_expecting_TERM()
2086 if ( $expecting == TERM );
2094 # if this is the first nonblank character, call it a label
2095 # since perl seems to just swallow it
2096 if ( $input_line_number == 1 && $last_nonblank_i == -1 ) {
2100 # ATTRS: check for a ':' which introduces an attribute list
2101 # (this might eventually get its own token type)
2102 elsif ( $statement_type =~ /^sub\b/ ) {
2104 $in_attribute_list = 1;
2107 # check for scalar attribute, such as
2108 # my $foo : shared = 1;
2109 elsif ($is_my_our{$statement_type}
2110 && $current_depth[QUESTION_COLON] == 0 )
2113 $in_attribute_list = 1;
2116 # otherwise, it should be part of a ?/: operator
2118 ( $type_sequence, $indent_flag ) =
2119 decrease_nesting_depth( QUESTION_COLON,
2120 $rtoken_map->[$i_tok] );
2121 if ( $last_nonblank_token eq '?' ) {
2122 warning("Syntax error near ? :\n");
2126 '+' => sub { # what kind of plus?
2128 if ( $expecting == TERM ) {
2129 my $number = scan_number();
2131 # unary plus is safest assumption if not a number
2132 if ( !defined($number) ) { $type = 'p'; }
2134 elsif ( $expecting == OPERATOR ) {
2137 if ( $next_type eq 'w' ) { $type = 'p' }
2142 error_if_expecting_OPERATOR("Array")
2143 if ( $expecting == OPERATOR );
2146 '%' => sub { # hash or modulo?
2148 # first guess is hash if no following blank
2149 if ( $expecting == UNKNOWN ) {
2150 if ( $next_type ne 'b' ) { $expecting = TERM }
2152 if ( $expecting == TERM ) {
2157 $square_bracket_type[ ++$square_bracket_depth ] =
2158 $last_nonblank_token;
2159 ( $type_sequence, $indent_flag ) =
2160 increase_nesting_depth( SQUARE_BRACKET, $rtoken_map->[$i_tok] );
2162 # It may seem odd, but structural square brackets have
2163 # type '{' and '}'. This simplifies the indentation logic.
2164 if ( !is_non_structural_brace() ) {
2167 $square_bracket_structural_type[$square_bracket_depth] = $type;
2170 ( $type_sequence, $indent_flag ) =
2171 decrease_nesting_depth( SQUARE_BRACKET, $rtoken_map->[$i_tok] );
2173 if ( $square_bracket_structural_type[$square_bracket_depth] eq '{' )
2178 # propagate type information for smartmatch operator. This is
2179 # necessary to enable us to know if an operator or term is expected
2181 if ( $square_bracket_type[$square_bracket_depth] eq '~~' ) {
2182 $tok = $square_bracket_type[$square_bracket_depth];
2185 if ( $square_bracket_depth > 0 ) { $square_bracket_depth--; }
2187 '-' => sub { # what kind of minus?
2189 if ( ( $expecting != OPERATOR )
2190 && $is_file_test_operator{$next_tok} )
2192 my ( $next_nonblank_token, $i_next ) =
2193 find_next_nonblank_token( $i + 1, $rtokens,
2196 # check for a quoted word like "-w=>xx";
2197 # it is sufficient to just check for a following '='
2198 if ( $next_nonblank_token eq '=' ) {
2207 elsif ( $expecting == TERM ) {
2208 my $number = scan_number();
2210 # maybe part of bareword token? unary is safest
2211 if ( !defined($number) ) { $type = 'm'; }
2214 elsif ( $expecting == OPERATOR ) {
2218 if ( $next_type eq 'w' ) {
2226 # check for special variables like ${^WARNING_BITS}
2227 if ( $expecting == TERM ) {
2229 # FIXME: this should work but will not catch errors
2230 # because we also have to be sure that previous token is
2231 # a type character ($,@,%).
2232 if ( $last_nonblank_token eq '{'
2233 && ( $next_tok =~ /^[A-Za-z_]/ ) )
2236 if ( $next_tok eq 'W' ) {
2237 $tokenizer_self->{_saw_perl_dash_w} = 1;
2239 $tok = $tok . $next_tok;
2245 unless ( error_if_expecting_TERM() ) {
2247 # Something like this is valid but strange:
2249 complain("The '^' seems unusual here\n");
2255 '::' => sub { # probably a sub call
2256 scan_bare_identifier();
2258 '<<' => sub { # maybe a here-doc?
2260 unless ( $i < $max_token_index )
2261 ; # here-doc not possible if end of line
2263 if ( $expecting != OPERATOR ) {
2264 my ( $found_target, $here_doc_target, $here_quote_character,
2267 $found_target, $here_doc_target, $here_quote_character, $i,
2270 = find_here_doc( $expecting, $i, $rtokens, $rtoken_map,
2273 if ($found_target) {
2274 push @{$rhere_target_list},
2275 [ $here_doc_target, $here_quote_character ];
2277 if ( length($here_doc_target) > 80 ) {
2278 my $truncated = substr( $here_doc_target, 0, 80 );
2279 complain("Long here-target: '$truncated' ...\n");
2281 elsif ( $here_doc_target !~ /^[A-Z_]\w+$/ ) {
2283 "Unconventional here-target: '$here_doc_target'\n");
2286 elsif ( $expecting == TERM ) {
2287 unless ($saw_error) {
2289 # shouldn't happen..
2290 warning("Program bug; didn't find here doc target\n");
2291 report_definite_bug();
2298 '<<~' => sub { # a here-doc, new type added in v26
2300 unless ( $i < $max_token_index )
2301 ; # here-doc not possible if end of line
2302 if ( $expecting != OPERATOR ) {
2303 my ( $found_target, $here_doc_target, $here_quote_character,
2306 $found_target, $here_doc_target, $here_quote_character, $i,
2309 = find_here_doc( $expecting, $i, $rtokens, $rtoken_map,
2312 if ($found_target) {
2314 if ( length($here_doc_target) > 80 ) {
2315 my $truncated = substr( $here_doc_target, 0, 80 );
2316 complain("Long here-target: '$truncated' ...\n");
2318 elsif ( $here_doc_target !~ /^[A-Z_]\w+$/ ) {
2320 "Unconventional here-target: '$here_doc_target'\n");
2323 # Note that we put a leading space on the here quote
2324 # character indicate that it may be preceded by spaces
2325 $here_quote_character = " " . $here_quote_character;
2326 push @{$rhere_target_list},
2327 [ $here_doc_target, $here_quote_character ];
2330 elsif ( $expecting == TERM ) {
2331 unless ($saw_error) {
2333 # shouldn't happen..
2334 warning("Program bug; didn't find here doc target\n");
2335 report_definite_bug();
2344 # if -> points to a bare word, we must scan for an identifier,
2345 # otherwise something like ->y would look like the y operator
2349 # type = 'pp' for pre-increment, '++' for post-increment
2351 if ( $expecting == TERM ) { $type = 'pp' }
2352 elsif ( $expecting == UNKNOWN ) {
2353 my ( $next_nonblank_token, $i_next ) =
2354 find_next_nonblank_token( $i, $rtokens, $max_token_index );
2355 if ( $next_nonblank_token eq '$' ) { $type = 'pp' }
2360 if ( $last_nonblank_type eq $tok ) {
2361 complain("Repeated '=>'s \n");
2364 # patch for operator_expected: note if we are in the list (use.t)
2365 # TODO: make version numbers a new token type
2366 if ( $statement_type eq 'use' ) { $statement_type = '_use' }
2369 # type = 'mm' for pre-decrement, '--' for post-decrement
2372 if ( $expecting == TERM ) { $type = 'mm' }
2373 elsif ( $expecting == UNKNOWN ) {
2374 my ( $next_nonblank_token, $i_next ) =
2375 find_next_nonblank_token( $i, $rtokens, $max_token_index );
2376 if ( $next_nonblank_token eq '$' ) { $type = 'mm' }
2381 error_if_expecting_TERM()
2382 if ( $expecting == TERM );
2386 error_if_expecting_TERM()
2387 if ( $expecting == TERM );
2391 error_if_expecting_TERM()
2392 if ( $expecting == TERM );
2396 # ------------------------------------------------------------
2397 # end hash of code for handling individual token types
2398 # ------------------------------------------------------------
2400 my %matching_start_token = ( '}' => '{', ']' => '[', ')' => '(' );
2402 # These block types terminate statements and do not need a trailing
2404 # patched for SWITCH/CASE/
2405 my %is_zero_continuation_block_type;
2406 @_ = qw( } { BEGIN END CHECK INIT AUTOLOAD DESTROY UNITCHECK continue ;
2407 if elsif else unless while until for foreach switch case given when);
2408 @is_zero_continuation_block_type{@_} = (1) x scalar(@_);
2410 my %is_not_zero_continuation_block_type;
2411 @_ = qw(sort grep map do eval);
2412 @is_not_zero_continuation_block_type{@_} = (1) x scalar(@_);
2414 my %is_logical_container;
2415 @_ = qw(if elsif unless while and or err not && ! || for foreach);
2416 @is_logical_container{@_} = (1) x scalar(@_);
2420 @is_binary_type{@_} = (1) x scalar(@_);
2422 my %is_binary_keyword;
2423 @_ = qw(and or err eq ne cmp);
2424 @is_binary_keyword{@_} = (1) x scalar(@_);
2426 # 'L' is token for opening { at hash key
2427 my %is_opening_type;
2429 @is_opening_type{@_} = (1) x scalar(@_);
2431 # 'R' is token for closing } at hash key
2432 my %is_closing_type;
2434 @is_closing_type{@_} = (1) x scalar(@_);
2436 my %is_redo_last_next_goto;
2437 @_ = qw(redo last next goto);
2438 @is_redo_last_next_goto{@_} = (1) x scalar(@_);
2441 @_ = qw(use require);
2442 @is_use_require{@_} = (1) x scalar(@_);
2445 @_ = qw(sub package);
2446 @is_sub_package{@_} = (1) x scalar(@_);
2448 # This hash holds the hash key in $tokenizer_self for these keywords:
2449 my %is_format_END_DATA = (
2450 'format' => '_in_format',
2451 '__END__' => '_in_end',
2452 '__DATA__' => '_in_data',
2455 # original ref: camel 3 p 147,
2456 # but perl may accept undocumented flags
2457 # perl 5.10 adds 'p' (preserve)
2458 # Perl version 5.22 added 'n'
2459 # From http://perldoc.perl.org/perlop.html we have
2460 # /PATTERN/msixpodualngc or m?PATTERN?msixpodualngc
2461 # s/PATTERN/REPLACEMENT/msixpodualngcer
2462 # y/SEARCHLIST/REPLACEMENTLIST/cdsr
2463 # tr/SEARCHLIST/REPLACEMENTLIST/cdsr
2464 # qr/STRING/msixpodualn
2465 my %quote_modifiers = (
2466 's' => '[msixpodualngcer]',
2469 'm' => '[msixpodualngc]',
2470 'qr' => '[msixpodualn]',
2477 # table showing how many quoted things to look for after quote operator..
2478 # s, y, tr have 2 (pattern and replacement)
2479 # others have 1 (pattern only)
2492 sub tokenize_this_line {
2494 # This routine breaks a line of perl code into tokens which are of use in
2495 # indentation and reformatting. One of my goals has been to define tokens
2496 # such that a newline may be inserted between any pair of tokens without
2497 # changing or invalidating the program. This version comes close to this,
2498 # although there are necessarily a few exceptions which must be caught by
2499 # the formatter. Many of these involve the treatment of bare words.
2501 # The tokens and their types are returned in arrays. See previous
2502 # routine for their names.
2504 # See also the array "valid_token_types" in the BEGIN section for an
2507 # To simplify things, token types are either a single character, or they
2508 # are identical to the tokens themselves.
2510 # As a debugging aid, the -D flag creates a file containing a side-by-side
2511 # comparison of the input string and its tokenization for each line of a file.
2512 # This is an invaluable debugging aid.
2514 # In addition to tokens, and some associated quantities, the tokenizer
2515 # also returns flags indication any special line types. These include
2516 # quotes, here_docs, formats.
2518 # -----------------------------------------------------------------------
2520 # How to add NEW_TOKENS:
2522 # New token types will undoubtedly be needed in the future both to keep up
2523 # with changes in perl and to help adapt the tokenizer to other applications.
2525 # Here are some notes on the minimal steps. I wrote these notes while
2526 # adding the 'v' token type for v-strings, which are things like version
2527 # numbers 5.6.0, and ip addresses, and will use that as an example. ( You
2528 # can use your editor to search for the string "NEW_TOKENS" to find the
2529 # appropriate sections to change):
2531 # *. Try to talk somebody else into doing it! If not, ..
2533 # *. Make a backup of your current version in case things don't work out!
2535 # *. Think of a new, unused character for the token type, and add to
2536 # the array @valid_token_types in the BEGIN section of this package.
2537 # For example, I used 'v' for v-strings.
2539 # *. Implement coding to recognize the $type of the token in this routine.
2540 # This is the hardest part, and is best done by imitating or modifying
2541 # some of the existing coding. For example, to recognize v-strings, I
2542 # patched 'sub scan_bare_identifier' to recognize v-strings beginning with
2543 # 'v' and 'sub scan_number' to recognize v-strings without the leading 'v'.
2545 # *. Update sub operator_expected. This update is critically important but
2546 # the coding is trivial. Look at the comments in that routine for help.
2547 # For v-strings, which should behave like numbers, I just added 'v' to the
2548 # regex used to handle numbers and strings (types 'n' and 'Q').
2550 # *. Implement a 'bond strength' rule in sub set_bond_strengths in
2551 # Perl::Tidy::Formatter for breaking lines around this token type. You can
2552 # skip this step and take the default at first, then adjust later to get
2553 # desired results. For adding type 'v', I looked at sub bond_strength and
2554 # saw that number type 'n' was using default strengths, so I didn't do
2555 # anything. I may tune it up someday if I don't like the way line
2556 # breaks with v-strings look.
2558 # *. Implement a 'whitespace' rule in sub set_whitespace_flags in
2559 # Perl::Tidy::Formatter. For adding type 'v', I looked at this routine
2560 # and saw that type 'n' used spaces on both sides, so I just added 'v'
2561 # to the array @spaces_both_sides.
2563 # *. Update HtmlWriter package so that users can colorize the token as
2564 # desired. This is quite easy; see comments identified by 'NEW_TOKENS' in
2565 # that package. For v-strings, I initially chose to use a default color
2566 # equal to the default for numbers, but it might be nice to change that
2569 # *. Update comments in Perl::Tidy::Tokenizer::dump_token_types.
2571 # *. Run lots and lots of debug tests. Start with special files designed
2572 # to test the new token type. Run with the -D flag to create a .DEBUG
2573 # file which shows the tokenization. When these work ok, test as many old
2574 # scripts as possible. Start with all of the '.t' files in the 'test'
2575 # directory of the distribution file. Compare .tdy output with previous
2576 # version and updated version to see the differences. Then include as
2577 # many more files as possible. My own technique has been to collect a huge
2578 # number of perl scripts (thousands!) into one directory and run perltidy
2579 # *, then run diff between the output of the previous version and the
2582 # *. For another example, search for the smartmatch operator '~~'
2583 # with your editor to see where updates were made for it.
2585 # -----------------------------------------------------------------------
2587 my $line_of_tokens = shift;
2588 my ($untrimmed_input_line) = $line_of_tokens->{_line_text};
2590 # patch while coding change is underway
2591 # make callers private data to allow access
2592 # $tokenizer_self = $caller_tokenizer_self;
2594 # extract line number for use in error messages
2595 $input_line_number = $line_of_tokens->{_line_number};
2597 # reinitialize for multi-line quote
2598 $line_of_tokens->{_starting_in_quote} = $in_quote && $quote_type eq 'Q';
2600 # check for pod documentation
2601 if ( ( $untrimmed_input_line =~ /^=[A-Za-z_]/ ) ) {
2603 # must not be in multi-line quote
2604 # and must not be in an equation
2605 if ( !$in_quote && ( operator_expected( 'b', '=', 'b' ) == TERM ) )
2607 $tokenizer_self->{_in_pod} = 1;
2612 $input_line = $untrimmed_input_line;
2616 # trim start of this line unless we are continuing a quoted line
2617 # do not trim end because we might end in a quote (test: deken4.pl)
2618 # Perl::Tidy::Formatter will delete needless trailing blanks
2619 unless ( $in_quote && ( $quote_type eq 'Q' ) ) {
2620 $input_line =~ s/^\s*//; # trim left end
2623 # Set a flag to indicate if we might be at an __END__ or __DATA__ line
2624 # This will be used below to avoid quoting a bare word followed by
2626 my $is_END_or_DATA = $input_line =~ /^\s*__(END|DATA)__\s*$/;
2628 # update the copy of the line for use in error messages
2629 # This must be exactly what we give the pre_tokenizer
2630 $tokenizer_self->{_line_text} = $input_line;
2632 # re-initialize for the main loop
2633 $routput_token_list = []; # stack of output token indexes
2634 $routput_token_type = []; # token types
2635 $routput_block_type = []; # types of code block
2636 $routput_container_type = []; # paren types, such as if, elsif, ..
2637 $routput_type_sequence = []; # nesting sequential number
2639 $rhere_target_list = [];
2641 $tok = $last_nonblank_token;
2642 $type = $last_nonblank_type;
2643 $prototype = $last_nonblank_prototype;
2644 $last_nonblank_i = -1;
2645 $block_type = $last_nonblank_block_type;
2646 $container_type = $last_nonblank_container_type;
2647 $type_sequence = $last_nonblank_type_sequence;
2651 # tokenization is done in two stages..
2652 # stage 1 is a very simple pre-tokenization
2653 my $max_tokens_wanted = 0; # this signals pre_tokenize to get all tokens
2655 # a little optimization for a full-line comment
2656 if ( !$in_quote && ( $input_line =~ /^#/ ) ) {
2657 $max_tokens_wanted = 1 # no use tokenizing a comment
2660 # start by breaking the line into pre-tokens
2661 ( $rtokens, $rtoken_map, $rtoken_type ) =
2662 pre_tokenize( $input_line, $max_tokens_wanted );
2664 $max_token_index = scalar( @{$rtokens} ) - 1;
2665 push( @{$rtokens}, ' ', ' ', ' ' ); # extra whitespace simplifies logic
2666 push( @{$rtoken_map}, 0, 0, 0 ); # shouldn't be referenced
2667 push( @{$rtoken_type}, 'b', 'b', 'b' );
2669 # initialize for main loop
2670 foreach my $ii ( 0 .. $max_token_index + 3 ) {
2671 $routput_token_type->[$ii] = "";
2672 $routput_block_type->[$ii] = "";
2673 $routput_container_type->[$ii] = "";
2674 $routput_type_sequence->[$ii] = "";
2675 $routput_indent_flag->[$ii] = 0;
2680 # ------------------------------------------------------------
2681 # begin main tokenization loop
2682 # ------------------------------------------------------------
2684 # we are looking at each pre-token of one line and combining them
2686 while ( ++$i <= $max_token_index ) {
2688 if ($in_quote) { # continue looking for end of a quote
2689 $type = $quote_type;
2691 unless ( @{$routput_token_list} )
2692 { # initialize if continuation line
2693 push( @{$routput_token_list}, $i );
2694 $routput_token_type->[$i] = $type;
2697 $tok = $quote_character unless ( $quote_character =~ /^\s*$/ );
2699 # scan for the end of the quote or pattern
2701 $i, $in_quote, $quote_character, $quote_pos, $quote_depth,
2702 $quoted_string_1, $quoted_string_2
2705 $i, $in_quote, $quote_character,
2706 $quote_pos, $quote_depth, $quoted_string_1,
2707 $quoted_string_2, $rtokens, $rtoken_map,
2711 # all done if we didn't find it
2712 last if ($in_quote);
2714 # save pattern and replacement text for rescanning
2715 my $qs1 = $quoted_string_1;
2716 my $qs2 = $quoted_string_2;
2718 # re-initialize for next search
2719 $quote_character = '';
2722 $quoted_string_1 = "";
2723 $quoted_string_2 = "";
2724 last if ( ++$i > $max_token_index );
2726 # look for any modifiers
2727 if ($allowed_quote_modifiers) {
2729 # check for exact quote modifiers
2730 if ( $rtokens->[$i] =~ /^[A-Za-z_]/ ) {
2731 my $str = $rtokens->[$i];
2733 while ( $str =~ /\G$allowed_quote_modifiers/gc ) {
2734 my $pos = pos($str);
2735 my $char = substr( $str, $pos - 1, 1 );
2736 $saw_modifier_e ||= ( $char eq 'e' );
2739 # For an 'e' quote modifier we must scan the replacement
2740 # text for here-doc targets.
2741 if ($saw_modifier_e) {
2743 my $rht = scan_replacement_text($qs1);
2745 # Change type from 'Q' to 'h' for quotes with
2746 # here-doc targets so that the formatter (see sub
2747 # print_line_of_tokens) will not make any line
2748 # breaks after this point.
2750 push @{$rhere_target_list}, @{$rht};
2753 my $ilast = $routput_token_list->[-1];
2754 $routput_token_type->[$ilast] = $type;
2759 if ( defined( pos($str) ) ) {
2762 if ( pos($str) == length($str) ) {
2763 last if ( ++$i > $max_token_index );
2766 # Looks like a joined quote modifier
2767 # and keyword, maybe something like
2768 # s/xxx/yyy/gefor @k=...
2769 # Example is "galgen.pl". Would have to split
2770 # the word and insert a new token in the
2771 # pre-token list. This is so rare that I haven't
2772 # done it. Will just issue a warning citation.
2774 # This error might also be triggered if my quote
2775 # modifier characters are incomplete
2779 Partial match to quote modifier $allowed_quote_modifiers at word: '$str'
2780 Please put a space between quote modifiers and trailing keywords.
2783 # print "token $rtokens->[$i]\n";
2784 # my $num = length($str) - pos($str);
2785 # $rtokens->[$i]=substr($rtokens->[$i],pos($str),$num);
2786 # print "continuing with new token $rtokens->[$i]\n";
2788 # skipping past this token does least damage
2789 last if ( ++$i > $max_token_index );
2794 # example file: rokicki4.pl
2795 # This error might also be triggered if my quote
2796 # modifier characters are incomplete
2797 write_logfile_entry(
2798 "Note: found word $str at quote modifier location\n"
2804 $allowed_quote_modifiers = "";
2808 unless ( $tok =~ /^\s*$/ || $tok eq 'CORE::' ) {
2810 # try to catch some common errors
2811 if ( ( $type eq 'n' ) && ( $tok ne '0' ) ) {
2813 if ( $last_nonblank_token eq 'eq' ) {
2814 complain("Should 'eq' be '==' here ?\n");
2816 elsif ( $last_nonblank_token eq 'ne' ) {
2817 complain("Should 'ne' be '!=' here ?\n");
2821 $last_last_nonblank_token = $last_nonblank_token;
2822 $last_last_nonblank_type = $last_nonblank_type;
2823 $last_last_nonblank_block_type = $last_nonblank_block_type;
2824 $last_last_nonblank_container_type =
2825 $last_nonblank_container_type;
2826 $last_last_nonblank_type_sequence =
2827 $last_nonblank_type_sequence;
2828 $last_nonblank_token = $tok;
2829 $last_nonblank_type = $type;
2830 $last_nonblank_prototype = $prototype;
2831 $last_nonblank_block_type = $block_type;
2832 $last_nonblank_container_type = $container_type;
2833 $last_nonblank_type_sequence = $type_sequence;
2834 $last_nonblank_i = $i_tok;
2837 # store previous token type
2838 if ( $i_tok >= 0 ) {
2839 $routput_token_type->[$i_tok] = $type;
2840 $routput_block_type->[$i_tok] = $block_type;
2841 $routput_container_type->[$i_tok] = $container_type;
2842 $routput_type_sequence->[$i_tok] = $type_sequence;
2843 $routput_indent_flag->[$i_tok] = $indent_flag;
2845 my $pre_tok = $rtokens->[$i]; # get the next pre-token
2846 my $pre_type = $rtoken_type->[$i]; # and type
2848 $type = $pre_type; # to be modified as necessary
2849 $block_type = ""; # blank for all tokens except code block braces
2850 $container_type = ""; # blank for all tokens except some parens
2851 $type_sequence = ""; # blank for all tokens except ?/:
2853 $prototype = ""; # blank for all tokens except user defined subs
2856 # this pre-token will start an output token
2857 push( @{$routput_token_list}, $i_tok );
2859 # continue gathering identifier if necessary
2860 # but do not start on blanks and comments
2861 if ( $id_scan_state && $pre_type !~ /[b#]/ ) {
2863 if ( $id_scan_state =~ /^(sub|package)/ ) {
2870 last if ($id_scan_state);
2871 next if ( ( $i > 0 ) || $type );
2873 # didn't find any token; start over
2878 # handle whitespace tokens..
2879 next if ( $type eq 'b' );
2880 my $prev_tok = $i > 0 ? $rtokens->[ $i - 1 ] : ' ';
2881 my $prev_type = $i > 0 ? $rtoken_type->[ $i - 1 ] : 'b';
2883 # Build larger tokens where possible, since we are not in a quote.
2885 # First try to assemble digraphs. The following tokens are
2886 # excluded and handled specially:
2887 # '/=' is excluded because the / might start a pattern.
2888 # 'x=' is excluded since it might be $x=, with $ on previous line
2889 # '**' and *= might be typeglobs of punctuation variables
2890 # I have allowed tokens starting with <, such as <=,
2891 # because I don't think these could be valid angle operators.
2892 # test file: storrs4.pl
2893 my $test_tok = $tok . $rtokens->[ $i + 1 ];
2894 my $combine_ok = $is_digraph{$test_tok};
2896 # check for special cases which cannot be combined
2899 # '//' must be defined_or operator if an operator is expected.
2900 # TODO: Code for other ambiguous digraphs (/=, x=, **, *=)
2901 # could be migrated here for clarity
2903 # Patch for RT#102371, misparsing a // in the following snippet:
2904 # state $b //= ccc();
2905 # The solution is to always accept the digraph (or trigraph) after
2906 # token type 'Z' (possible file handle). The reason is that
2907 # sub operator_expected gives TERM expected here, which is
2908 # wrong in this case.
2909 if ( $test_tok eq '//' && $last_nonblank_type ne 'Z' ) {
2910 my $next_type = $rtokens->[ $i + 1 ];
2912 operator_expected( $prev_type, $tok, $next_type );
2914 # Patched for RT#101547, was 'unless ($expecting==OPERATOR)'
2915 $combine_ok = 0 if ( $expecting == TERM );
2918 # Patch for RT #114359: Missparsing of "print $x ** 0.5;
2919 # Accept the digraphs '**' only after type 'Z'
2920 # Otherwise postpone the decision.
2921 if ( $test_tok eq '**' ) {
2922 if ( $last_nonblank_type ne 'Z' ) { $combine_ok = 0 }
2929 && ( $test_tok ne '/=' ) # might be pattern
2930 && ( $test_tok ne 'x=' ) # might be $x
2931 && ( $test_tok ne '*=' ) # typeglob?
2933 # Moved above as part of fix for
2934 # RT #114359: Missparsing of "print $x ** 0.5;
2935 # && ( $test_tok ne '**' ) # typeglob?
2941 # Now try to assemble trigraphs. Note that all possible
2942 # perl trigraphs can be constructed by appending a character
2944 $test_tok = $tok . $rtokens->[ $i + 1 ];
2946 if ( $is_trigraph{$test_tok} ) {
2951 # The only current tetragraph is the double diamond operator
2952 # and its first three characters are not a trigraph, so
2953 # we do can do a special test for it
2954 elsif ( $test_tok eq '<<>' ) {
2955 $test_tok .= $rtokens->[ $i + 2 ];
2956 if ( $is_tetragraph{$test_tok} ) {
2964 $next_tok = $rtokens->[ $i + 1 ];
2965 $next_type = $rtoken_type->[ $i + 1 ];
2967 TOKENIZER_DEBUG_FLAG_TOKENIZE && do {
2970 $last_nonblank_token, $tok,
2971 $next_tok, $brace_depth,
2972 $brace_type[$brace_depth], $paren_depth,
2973 $paren_type[$paren_depth]
2975 print STDOUT "TOKENIZE:(@debug_list)\n";
2978 # turn off attribute list on first non-blank, non-bareword
2979 if ( $pre_type ne 'w' ) { $in_attribute_list = 0 }
2981 ###############################################################
2982 # We have the next token, $tok.
2983 # Now we have to examine this token and decide what it is
2984 # and define its $type
2986 # section 1: bare words
2987 ###############################################################
2989 if ( $pre_type eq 'w' ) {
2990 $expecting = operator_expected( $prev_type, $tok, $next_type );
2991 my ( $next_nonblank_token, $i_next ) =
2992 find_next_nonblank_token( $i, $rtokens, $max_token_index );
2994 # ATTRS: handle sub and variable attributes
2995 if ($in_attribute_list) {
2997 # treat bare word followed by open paren like qw(
2998 if ( $next_nonblank_token eq '(' ) {
2999 $in_quote = $quote_items{'q'};
3000 $allowed_quote_modifiers = $quote_modifiers{'q'};
3006 # handle bareword not followed by open paren
3013 # quote a word followed by => operator
3014 # unless the word __END__ or __DATA__ and the only word on
3016 if ( !$is_END_or_DATA && $next_nonblank_token eq '=' ) {
3018 if ( $rtokens->[ $i_next + 1 ] eq '>' ) {
3019 if ( $is_constant{$current_package}{$tok} ) {
3022 elsif ( $is_user_function{$current_package}{$tok} ) {
3025 $user_function_prototype{$current_package}{$tok};
3027 elsif ( $tok =~ /^v\d+$/ ) {
3029 report_v_string($tok);
3031 else { $type = 'w' }
3037 # quote a bare word within braces..like xxx->{s}; note that we
3038 # must be sure this is not a structural brace, to avoid
3039 # mistaking {s} in the following for a quoted bare word:
3040 # for(@[){s}bla}BLA}
3041 # Also treat q in something like var{-q} as a bare word, not qoute operator
3043 $next_nonblank_token eq '}'
3045 $last_nonblank_type eq 'L'
3046 || ( $last_nonblank_type eq 'm'
3047 && $last_last_nonblank_type eq 'L' )
3055 # a bare word immediately followed by :: is not a keyword;
3056 # use $tok_kw when testing for keywords to avoid a mistake
3058 if ( $rtokens->[ $i + 1 ] eq ':'
3059 && $rtokens->[ $i + 2 ] eq ':' )
3064 # handle operator x (now we know it isn't $x=)
3065 if ( ( $tok =~ /^x\d*$/ ) && ( $expecting == OPERATOR ) ) {
3066 if ( $tok eq 'x' ) {
3068 if ( $rtokens->[ $i + 1 ] eq '=' ) { # x=
3078 # FIXME: Patch: mark something like x4 as an integer for now
3079 # It gets fixed downstream. This is easier than
3080 # splitting the pretoken.
3085 elsif ( $tok_kw eq 'CORE::' ) {
3086 $type = $tok = $tok_kw;
3089 elsif ( ( $tok eq 'strict' )
3090 and ( $last_nonblank_token eq 'use' ) )
3092 $tokenizer_self->{_saw_use_strict} = 1;
3093 scan_bare_identifier();
3096 elsif ( ( $tok eq 'warnings' )
3097 and ( $last_nonblank_token eq 'use' ) )
3099 $tokenizer_self->{_saw_perl_dash_w} = 1;
3101 # scan as identifier, so that we pick up something like:
3102 # use warnings::register
3103 scan_bare_identifier();
3107 $tok eq 'AutoLoader'
3108 && $tokenizer_self->{_look_for_autoloader}
3110 $last_nonblank_token eq 'use'
3112 # these regexes are from AutoSplit.pm, which we want
3114 || $input_line =~ /^\s*(use|require)\s+AutoLoader\b/
3115 || $input_line =~ /\bISA\s*=.*\bAutoLoader\b/
3119 write_logfile_entry("AutoLoader seen, -nlal deactivates\n");
3120 $tokenizer_self->{_saw_autoloader} = 1;
3121 $tokenizer_self->{_look_for_autoloader} = 0;
3122 scan_bare_identifier();
3126 $tok eq 'SelfLoader'
3127 && $tokenizer_self->{_look_for_selfloader}
3128 && ( $last_nonblank_token eq 'use'
3129 || $input_line =~ /^\s*(use|require)\s+SelfLoader\b/
3130 || $input_line =~ /\bISA\s*=.*\bSelfLoader\b/ )
3133 write_logfile_entry("SelfLoader seen, -nlsl deactivates\n");
3134 $tokenizer_self->{_saw_selfloader} = 1;
3135 $tokenizer_self->{_look_for_selfloader} = 0;
3136 scan_bare_identifier();
3139 elsif ( ( $tok eq 'constant' )
3140 and ( $last_nonblank_token eq 'use' ) )
3142 scan_bare_identifier();
3143 my ( $next_nonblank_token, $i_next ) =
3144 find_next_nonblank_token( $i, $rtokens,
3147 if ($next_nonblank_token) {
3149 if ( $is_keyword{$next_nonblank_token} ) {
3151 # Assume qw is used as a quote and okay, as in:
3152 # use constant qw{ DEBUG 0 };
3153 # Not worth trying to parse for just a warning
3155 # NOTE: This warning is deactivated because recent
3156 # versions of perl do not complain here, but
3157 # the coding is retained for reference.
3158 if ( 0 && $next_nonblank_token ne 'qw' ) {
3160 "Attempting to define constant '$next_nonblank_token' which is a perl keyword\n"
3165 # FIXME: could check for error in which next token is
3166 # not a word (number, punctuation, ..)
3168 $is_constant{$current_package}{$next_nonblank_token}
3174 # various quote operators
3175 elsif ( $is_q_qq_qw_qx_qr_s_y_tr_m{$tok} ) {
3177 if ( $expecting == OPERATOR ) {
3179 # Be careful not to call an error for a qw quote
3180 # where a parenthesized list is allowed. For example,
3181 # it could also be a for/foreach construct such as
3183 # foreach my $key qw\Uno Due Tres Quadro\ {
3184 # print "Set $key\n";
3188 # Or it could be a function call.
3189 # NOTE: Braces in something like &{ xxx } are not
3190 # marked as a block, we might have a method call.
3191 # &method(...), $method->(..), &{method}(...),
3192 # $ref[2](list) is ok & short for $ref[2]->(list)
3194 # See notes in 'sub code_block_type' and
3195 # 'sub is_non_structural_brace'
3199 && ( $last_nonblank_token =~ /^([\]\}\&]|\-\>)/
3200 || $is_for_foreach{$want_paren} )
3203 error_if_expecting_OPERATOR();
3206 $in_quote = $quote_items{$tok};
3207 $allowed_quote_modifiers = $quote_modifiers{$tok};
3209 # All quote types are 'Q' except possibly qw quotes.
3210 # qw quotes are special in that they may generally be trimmed
3211 # of leading and trailing whitespace. So they are given a
3212 # separate type, 'q', unless requested otherwise.
3214 ( $tok eq 'qw' && $tokenizer_self->{_trim_qw} )
3217 $quote_type = $type;
3220 # check for a statement label
3222 ( $next_nonblank_token eq ':' )
3223 && ( $rtokens->[ $i_next + 1 ] ne ':' )
3224 && ( $i_next <= $max_token_index ) # colon on same line
3228 if ( $tok !~ /[A-Z]/ ) {
3229 push @{ $tokenizer_self->{_rlower_case_labels_at} },
3238 # 'sub' || 'package'
3239 elsif ( $is_sub_package{$tok_kw} ) {
3240 error_if_expecting_OPERATOR()
3241 if ( $expecting == OPERATOR );
3245 # Note on token types for format, __DATA__, __END__:
3246 # It simplifies things to give these type ';', so that when we
3247 # start rescanning we will be expecting a token of type TERM.
3248 # We will switch to type 'k' before outputting the tokens.
3249 elsif ( $is_format_END_DATA{$tok_kw} ) {
3250 $type = ';'; # make tokenizer look for TERM next
3251 $tokenizer_self->{ $is_format_END_DATA{$tok_kw} } = 1;
3255 elsif ( $is_keyword{$tok_kw} ) {
3258 # Since for and foreach may not be followed immediately
3259 # by an opening paren, we have to remember which keyword
3260 # is associated with the next '('
3261 if ( $is_for_foreach{$tok} ) {
3262 if ( new_statement_ok() ) {
3267 # recognize 'use' statements, which are special
3268 elsif ( $is_use_require{$tok} ) {
3269 $statement_type = $tok;
3270 error_if_expecting_OPERATOR()
3271 if ( $expecting == OPERATOR );
3274 # remember my and our to check for trailing ": shared"
3275 elsif ( $is_my_our{$tok} ) {
3276 $statement_type = $tok;
3279 # Check for misplaced 'elsif' and 'else', but allow isolated
3280 # else or elsif blocks to be formatted. This is indicated
3281 # by a last noblank token of ';'
3282 elsif ( $tok eq 'elsif' ) {
3283 if ( $last_nonblank_token ne ';'
3284 && $last_nonblank_block_type !~
3285 /^(if|elsif|unless)$/ )
3288 "expecting '$tok' to follow one of 'if|elsif|unless'\n"
3292 elsif ( $tok eq 'else' ) {
3294 # patched for SWITCH/CASE
3296 $last_nonblank_token ne ';'
3297 && $last_nonblank_block_type !~
3298 /^(if|elsif|unless|case|when)$/
3300 # patch to avoid an unwanted error message for
3301 # the case of a parenless 'case' (RT 105484):
3302 # switch ( 1 ) { case x { 2 } else { } }
3303 && $statement_type !~
3304 /^(if|elsif|unless|case|when)$/
3308 "expecting '$tok' to follow one of 'if|elsif|unless|case|when'\n"
3312 elsif ( $tok eq 'continue' ) {
3313 if ( $last_nonblank_token ne ';'
3314 && $last_nonblank_block_type !~
3315 /(^(\{|\}|;|while|until|for|foreach)|:$)/ )
3318 # note: ';' '{' and '}' in list above
3319 # because continues can follow bare blocks;
3320 # ':' is labeled block
3322 ############################################
3323 # NOTE: This check has been deactivated because
3324 # continue has an alternative usage for given/when
3325 # blocks in perl 5.10
3326 ## warning("'$tok' should follow a block\n");
3327 ############################################
3331 # patch for SWITCH/CASE if 'case' and 'when are
3332 # treated as keywords.
3333 elsif ( $tok eq 'when' || $tok eq 'case' ) {
3334 $statement_type = $tok; # next '{' is block
3338 # indent trailing if/unless/while/until
3339 # outdenting will be handled by later indentation loop
3340 ## DEACTIVATED: unfortunately this can cause some unwanted indentation like:
3352 ## if ( $tok =~ /^(if|unless|while|until)$/
3353 ## && $next_nonblank_token ne '(' )
3355 ## $indent_flag = 1;
3359 # check for inline label following
3360 # /^(redo|last|next|goto)$/
3361 elsif (( $last_nonblank_type eq 'k' )
3362 && ( $is_redo_last_next_goto{$last_nonblank_token} ) )
3371 scan_bare_identifier();
3372 if ( $type eq 'w' ) {
3374 if ( $expecting == OPERATOR ) {
3376 # don't complain about possible indirect object
3380 # sub new($) { ... }
3381 # $b = new A::; # calls A::new
3382 # $c = new A; # same thing but suspicious
3383 # This will call A::new but we have a 'new' in
3384 # main:: which looks like a constant.
3386 if ( $last_nonblank_type eq 'C' ) {
3387 if ( $tok !~ /::$/ ) {
3389 Expecting operator after '$last_nonblank_token' but found bare word '$tok'
3390 Maybe indirectet object notation?
3395 error_if_expecting_OPERATOR("bareword");
3399 # mark bare words immediately followed by a paren as
3401 $next_tok = $rtokens->[ $i + 1 ];
3402 if ( $next_tok eq '(' ) {
3406 # underscore after file test operator is file handle
3407 if ( $tok eq '_' && $last_nonblank_type eq 'F' ) {
3411 # patch for SWITCH/CASE if 'case' and 'when are
3412 # not treated as keywords:
3416 && $brace_type[$brace_depth] eq 'switch'
3419 && $brace_type[$brace_depth] eq 'given' )
3422 $statement_type = $tok; # next '{' is block
3423 $type = 'k'; # for keyword syntax coloring
3426 # patch for SWITCH/CASE if switch and given not keywords
3427 # Switch is not a perl 5 keyword, but we will gamble
3428 # and mark switch followed by paren as a keyword. This
3429 # is only necessary to get html syntax coloring nice,
3430 # and does not commit this as being a switch/case.
3431 if ( $next_nonblank_token eq '('
3432 && ( $tok eq 'switch' || $tok eq 'given' ) )
3434 $type = 'k'; # for keyword syntax coloring
3440 ###############################################################
3441 # section 2: strings of digits
3442 ###############################################################
3443 elsif ( $pre_type eq 'd' ) {
3444 $expecting = operator_expected( $prev_type, $tok, $next_type );
3445 error_if_expecting_OPERATOR("Number")
3446 if ( $expecting == OPERATOR );
3447 my $number = scan_number();
3448 if ( !defined($number) ) {
3450 # shouldn't happen - we should always get a number
3451 warning("non-number beginning with digit--program bug\n");
3452 report_definite_bug();
3456 ###############################################################
3457 # section 3: all other tokens
3458 ###############################################################
3461 last if ( $tok eq '#' );
3462 my $code = $tokenization_code->{$tok};
3465 operator_expected( $prev_type, $tok, $next_type );
3472 # -----------------------------
3473 # end of main tokenization loop
3474 # -----------------------------
3476 if ( $i_tok >= 0 ) {
3477 $routput_token_type->[$i_tok] = $type;
3478 $routput_block_type->[$i_tok] = $block_type;
3479 $routput_container_type->[$i_tok] = $container_type;
3480 $routput_type_sequence->[$i_tok] = $type_sequence;
3481 $routput_indent_flag->[$i_tok] = $indent_flag;
3484 unless ( ( $type eq 'b' ) || ( $type eq '#' ) ) {
3485 $last_last_nonblank_token = $last_nonblank_token;
3486 $last_last_nonblank_type = $last_nonblank_type;
3487 $last_last_nonblank_block_type = $last_nonblank_block_type;
3488 $last_last_nonblank_container_type = $last_nonblank_container_type;
3489 $last_last_nonblank_type_sequence = $last_nonblank_type_sequence;
3490 $last_nonblank_token = $tok;
3491 $last_nonblank_type = $type;
3492 $last_nonblank_block_type = $block_type;
3493 $last_nonblank_container_type = $container_type;
3494 $last_nonblank_type_sequence = $type_sequence;
3495 $last_nonblank_prototype = $prototype;
3498 # reset indentation level if necessary at a sub or package
3499 # in an attempt to recover from a nesting error
3500 if ( $level_in_tokenizer < 0 ) {
3501 if ( $input_line =~ /^\s*(sub|package)\s+(\w+)/ ) {
3502 reset_indentation_level(0);
3503 brace_warning("resetting level to 0 at $1 $2\n");
3507 # all done tokenizing this line ...
3508 # now prepare the final list of tokens and types
3510 my @token_type = (); # stack of output token types
3511 my @block_type = (); # stack of output code block types
3512 my @container_type = (); # stack of output code container types
3513 my @type_sequence = (); # stack of output type sequence numbers
3514 my @tokens = (); # output tokens
3515 my @levels = (); # structural brace levels of output tokens
3516 my @slevels = (); # secondary nesting levels of output tokens
3517 my @nesting_tokens = (); # string of tokens leading to this depth
3518 my @nesting_types = (); # string of token types leading to this depth
3519 my @nesting_blocks = (); # string of block types leading to this depth
3520 my @nesting_lists = (); # string of list types leading to this depth
3521 my @ci_string = (); # string needed to compute continuation indentation
3522 my @container_environment = (); # BLOCK or LIST
3523 my $container_environment = '';
3524 my $im = -1; # previous $i value
3526 my $ci_string_sum = ones_count($ci_string_in_tokenizer);
3528 # Computing Token Indentation
3530 # The final section of the tokenizer forms tokens and also computes
3531 # parameters needed to find indentation. It is much easier to do it
3532 # in the tokenizer than elsewhere. Here is a brief description of how
3533 # indentation is computed. Perl::Tidy computes indentation as the sum
3536 # (1) structural indentation, such as if/else/elsif blocks
3537 # (2) continuation indentation, such as long parameter call lists.
3539 # These are occasionally called primary and secondary indentation.
3541 # Structural indentation is introduced by tokens of type '{', although
3542 # the actual tokens might be '{', '(', or '['. Structural indentation
3543 # is of two types: BLOCK and non-BLOCK. Default structural indentation
3544 # is 4 characters if the standard indentation scheme is used.
3546 # Continuation indentation is introduced whenever a line at BLOCK level
3547 # is broken before its termination. Default continuation indentation
3548 # is 2 characters in the standard indentation scheme.
3550 # Both types of indentation may be nested arbitrarily deep and
3551 # interlaced. The distinction between the two is somewhat arbitrary.
3553 # For each token, we will define two variables which would apply if
3554 # the current statement were broken just before that token, so that
3555 # that token started a new line:
3557 # $level = the structural indentation level,
3558 # $ci_level = the continuation indentation level
3560 # The total indentation will be $level * (4 spaces) + $ci_level * (2 spaces),
3561 # assuming defaults. However, in some special cases it is customary
3562 # to modify $ci_level from this strict value.
3564 # The total structural indentation is easy to compute by adding and
3565 # subtracting 1 from a saved value as types '{' and '}' are seen. The
3566 # running value of this variable is $level_in_tokenizer.
3568 # The total continuation is much more difficult to compute, and requires
3569 # several variables. These variables are:
3571 # $ci_string_in_tokenizer = a string of 1's and 0's indicating, for
3572 # each indentation level, if there are intervening open secondary
3573 # structures just prior to that level.
3574 # $continuation_string_in_tokenizer = a string of 1's and 0's indicating
3575 # if the last token at that level is "continued", meaning that it
3576 # is not the first token of an expression.
3577 # $nesting_block_string = a string of 1's and 0's indicating, for each
3578 # indentation level, if the level is of type BLOCK or not.
3579 # $nesting_block_flag = the most recent 1 or 0 of $nesting_block_string
3580 # $nesting_list_string = a string of 1's and 0's indicating, for each
3581 # indentation level, if it is appropriate for list formatting.
3582 # If so, continuation indentation is used to indent long list items.
3583 # $nesting_list_flag = the most recent 1 or 0 of $nesting_list_string
3584 # @{$rslevel_stack} = a stack of total nesting depths at each
3585 # structural indentation level, where "total nesting depth" means
3586 # the nesting depth that would occur if every nesting token -- '{', '[',
3587 # and '(' -- , regardless of context, is used to compute a nesting
3590 #my $nesting_block_flag = ($nesting_block_string =~ /1$/);
3591 #my $nesting_list_flag = ($nesting_list_string =~ /1$/);
3593 my ( $ci_string_i, $level_i, $nesting_block_string_i,
3594 $nesting_list_string_i, $nesting_token_string_i,
3595 $nesting_type_string_i, );
3597 foreach my $i ( @{$routput_token_list} )
3598 { # scan the list of pre-tokens indexes
3600 # self-checking for valid token types
3601 my $type = $routput_token_type->[$i];
3602 my $forced_indentation_flag = $routput_indent_flag->[$i];
3604 # See if we should undo the $forced_indentation_flag.
3605 # Forced indentation after 'if', 'unless', 'while' and 'until'
3606 # expressions without trailing parens is optional and doesn't
3607 # always look good. It is usually okay for a trailing logical
3608 # expression, but if the expression is a function call, code block,
3609 # or some kind of list it puts in an unwanted extra indentation
3610 # level which is hard to remove.
3612 # Example where extra indentation looks ok:
3614 # if $det_a < 0 and $det_b > 0
3615 # or $det_a > 0 and $det_b < 0;
3617 # Example where extra indentation is not needed because
3618 # the eval brace also provides indentation:
3619 # print "not " if defined eval {
3620 # reduce { die if $b > 2; $a + $b } 0, 1, 2, 3, 4;
3623 # The following rule works fairly well:
3624 # Undo the flag if the end of this line, or start of the next
3625 # line, is an opening container token or a comma.
3626 # This almost always works, but if not after another pass it will
3628 if ( $forced_indentation_flag && $type eq 'k' ) {
3630 my $ilast = $routput_token_list->[$ixlast];
3631 my $toklast = $routput_token_type->[$ilast];
3632 if ( $toklast eq '#' ) {
3634 $ilast = $routput_token_list->[$ixlast];
3635 $toklast = $routput_token_type->[$ilast];
3637 if ( $toklast eq 'b' ) {
3639 $ilast = $routput_token_list->[$ixlast];
3640 $toklast = $routput_token_type->[$ilast];
3642 if ( $toklast =~ /^[\{,]$/ ) {
3643 $forced_indentation_flag = 0;
3646 ( $toklast, my $i_next ) =
3647 find_next_nonblank_token( $max_token_index, $rtokens,
3649 if ( $toklast =~ /^[\{,]$/ ) {
3650 $forced_indentation_flag = 0;
3655 # if we are already in an indented if, see if we should outdent
3656 if ($indented_if_level) {
3658 # don't try to nest trailing if's - shouldn't happen
3659 if ( $type eq 'k' ) {
3660 $forced_indentation_flag = 0;
3663 # check for the normal case - outdenting at next ';'
3664 elsif ( $type eq ';' ) {
3665 if ( $level_in_tokenizer == $indented_if_level ) {
3666 $forced_indentation_flag = -1;
3667 $indented_if_level = 0;
3671 # handle case of missing semicolon
3672 elsif ( $type eq '}' ) {
3673 if ( $level_in_tokenizer == $indented_if_level ) {
3674 $indented_if_level = 0;
3676 # TBD: This could be a subroutine call
3677 $level_in_tokenizer--;
3678 if ( @{$rslevel_stack} > 1 ) {
3679 pop( @{$rslevel_stack} );
3681 if ( length($nesting_block_string) > 1 )
3682 { # true for valid script
3683 chop $nesting_block_string;
3684 chop $nesting_list_string;
3691 my $tok = $rtokens->[$i]; # the token, but ONLY if same as pretoken
3692 $level_i = $level_in_tokenizer;
3694 # This can happen by running perltidy on non-scripts
3695 # although it could also be bug introduced by programming change.
3696 # Perl silently accepts a 032 (^Z) and takes it as the end
3697 if ( !$is_valid_token_type{$type} ) {
3698 my $val = ord($type);
3700 "unexpected character decimal $val ($type) in script\n");
3701 $tokenizer_self->{_in_error} = 1;
3704 # ----------------------------------------------------------------
3705 # TOKEN TYPE PATCHES
3706 # output __END__, __DATA__, and format as type 'k' instead of ';'
3707 # to make html colors correct, etc.
3708 my $fix_type = $type;
3709 if ( $type eq ';' && $tok =~ /\w/ ) { $fix_type = 'k' }
3711 # output anonymous 'sub' as keyword
3712 if ( $type eq 't' && $tok eq 'sub' ) { $fix_type = 'k' }
3714 # -----------------------------------------------------------------
3716 $nesting_token_string_i = $nesting_token_string;
3717 $nesting_type_string_i = $nesting_type_string;
3718 $nesting_block_string_i = $nesting_block_string;
3719 $nesting_list_string_i = $nesting_list_string;
3721 # set primary indentation levels based on structural braces
3722 # Note: these are set so that the leading braces have a HIGHER
3723 # level than their CONTENTS, which is convenient for indentation
3724 # Also, define continuation indentation for each token.
3725 if ( $type eq '{' || $type eq 'L' || $forced_indentation_flag > 0 )
3728 # use environment before updating
3729 $container_environment =
3730 $nesting_block_flag ? 'BLOCK'
3731 : $nesting_list_flag ? 'LIST'
3734 # if the difference between total nesting levels is not 1,
3735 # there are intervening non-structural nesting types between
3736 # this '{' and the previous unclosed '{'
3737 my $intervening_secondary_structure = 0;
3738 if ( @{$rslevel_stack} ) {
3739 $intervening_secondary_structure =
3740 $slevel_in_tokenizer - $rslevel_stack->[-1];
3743 # Continuation Indentation
3745 # Having tried setting continuation indentation both in the formatter and
3746 # in the tokenizer, I can say that setting it in the tokenizer is much,
3747 # much easier. The formatter already has too much to do, and can't
3748 # make decisions on line breaks without knowing what 'ci' will be at
3749 # arbitrary locations.
3751 # But a problem with setting the continuation indentation (ci) here
3752 # in the tokenizer is that we do not know where line breaks will actually
3753 # be. As a result, we don't know if we should propagate continuation
3754 # indentation to higher levels of structure.
3756 # For nesting of only structural indentation, we never need to do this.
3757 # For example, in a long if statement, like this
3759 # if ( !$output_block_type[$i]
3760 # && ($in_statement_continuation) )
3765 # the second line has ci but we do normally give the lines within the BLOCK
3766 # any ci. This would be true if we had blocks nested arbitrarily deeply.
3768 # But consider something like this, where we have created a break after
3769 # an opening paren on line 1, and the paren is not (currently) a
3770 # structural indentation token:
3772 # my $file = $menubar->Menubutton(
3773 # qw/-text File -underline 0 -menuitems/ => [
3775 # Cascade => '~View',
3779 # The second line has ci, so it would seem reasonable to propagate it
3780 # down, giving the third line 1 ci + 1 indentation. This suggests the
3781 # following rule, which is currently used to propagating ci down: if there
3782 # are any non-structural opening parens (or brackets, or braces), before
3783 # an opening structural brace, then ci is propagated down, and otherwise
3784 # not. The variable $intervening_secondary_structure contains this
3785 # information for the current token, and the string
3786 # "$ci_string_in_tokenizer" is a stack of previous values of this
3789 # save the current states
3790 push( @{$rslevel_stack}, 1 + $slevel_in_tokenizer );
3791 $level_in_tokenizer++;
3793 if ($forced_indentation_flag) {
3795 # break BEFORE '?' when there is forced indentation
3796 if ( $type eq '?' ) { $level_i = $level_in_tokenizer; }
3797 if ( $type eq 'k' ) {
3798 $indented_if_level = $level_in_tokenizer;
3801 # do not change container environment here if we are not
3802 # at a real list. Adding this check prevents "blinkers"
3803 # often near 'unless" clauses, such as in the following
3808 ## File::Spec->catdir( $_, "auto", $root, "$sub$lib_ext" )
3811 $nesting_block_string .= "$nesting_block_flag";
3815 if ( $routput_block_type->[$i] ) {
3816 $nesting_block_flag = 1;
3817 $nesting_block_string .= '1';
3820 $nesting_block_flag = 0;
3821 $nesting_block_string .= '0';
3825 # we will use continuation indentation within containers
3826 # which are not blocks and not logical expressions
3828 if ( !$routput_block_type->[$i] ) {
3830 # propagate flag down at nested open parens
3831 if ( $routput_container_type->[$i] eq '(' ) {
3832 $bit = 1 if $nesting_list_flag;
3835 # use list continuation if not a logical grouping
3836 # /^(if|elsif|unless|while|and|or|not|&&|!|\|\||for|foreach)$/
3840 $is_logical_container{ $routput_container_type->[$i]
3844 $nesting_list_string .= $bit;
3845 $nesting_list_flag = $bit;
3847 $ci_string_in_tokenizer .=
3848 ( $intervening_secondary_structure != 0 ) ? '1' : '0';
3849 $ci_string_sum = ones_count($ci_string_in_tokenizer);
3850 $continuation_string_in_tokenizer .=
3851 ( $in_statement_continuation > 0 ) ? '1' : '0';
3853 # Sometimes we want to give an opening brace continuation indentation,
3854 # and sometimes not. For code blocks, we don't do it, so that the leading
3855 # '{' gets outdented, like this:
3857 # if ( !$output_block_type[$i]
3858 # && ($in_statement_continuation) )
3861 # For other types, we will give them continuation indentation. For example,
3862 # here is how a list looks with the opening paren indented:
3865 # ( [ "fred", "barney" ], [ "george", "jane", "elroy" ],
3866 # [ "homer", "marge", "bart" ], );
3868 # This looks best when 'ci' is one-half of the indentation (i.e., 2 and 4)
3870 my $total_ci = $ci_string_sum;
3872 !$routput_block_type->[$i] # patch: skip for BLOCK
3873 && ($in_statement_continuation)
3874 && !( $forced_indentation_flag && $type eq ':' )
3877 $total_ci += $in_statement_continuation
3878 unless ( $ci_string_in_tokenizer =~ /1$/ );
3881 $ci_string_i = $total_ci;
3882 $in_statement_continuation = 0;
3887 || $forced_indentation_flag < 0 )
3890 # only a nesting error in the script would prevent popping here
3891 if ( @{$rslevel_stack} > 1 ) { pop( @{$rslevel_stack} ); }
3893 $level_i = --$level_in_tokenizer;
3895 # restore previous level values
3896 if ( length($nesting_block_string) > 1 )
3897 { # true for valid script
3898 chop $nesting_block_string;
3899 $nesting_block_flag = ( $nesting_block_string =~ /1$/ );
3900 chop $nesting_list_string;
3901 $nesting_list_flag = ( $nesting_list_string =~ /1$/ );
3903 chop $ci_string_in_tokenizer;
3904 $ci_string_sum = ones_count($ci_string_in_tokenizer);
3906 $in_statement_continuation =
3907 chop $continuation_string_in_tokenizer;
3909 # zero continuation flag at terminal BLOCK '}' which
3911 if ( $routput_block_type->[$i] ) {
3913 # ...These include non-anonymous subs
3914 # note: could be sub ::abc { or sub 'abc
3915 if ( $routput_block_type->[$i] =~ m/^sub\s*/gc ) {
3917 # note: older versions of perl require the /gc modifier
3918 # here or else the \G does not work.
3919 if ( $routput_block_type->[$i] =~ /\G('|::|\w)/gc )
3921 $in_statement_continuation = 0;
3925 # ...and include all block types except user subs with
3926 # block prototypes and these: (sort|grep|map|do|eval)
3927 # /^(\}|\{|BEGIN|END|CHECK|INIT|AUTOLOAD|DESTROY|UNITCHECK|continue|;|if|elsif|else|unless|while|until|for|foreach)$/
3929 $is_zero_continuation_block_type{
3930 $routput_block_type->[$i]
3933 $in_statement_continuation = 0;
3936 # ..but these are not terminal types:
3937 # /^(sort|grep|map|do|eval)$/ )
3939 $is_not_zero_continuation_block_type{
3940 $routput_block_type->[$i]
3945 # ..and a block introduced by a label
3947 elsif ( $routput_block_type->[$i] =~ /:$/ ) {
3948 $in_statement_continuation = 0;
3951 # user function with block prototype
3953 $in_statement_continuation = 0;
3957 # If we are in a list, then
3958 # we must set continuation indentation at the closing
3959 # paren of something like this (paren after $check):
3962 # ( not defined $check )
3964 # or $check eq "new"
3965 # or $check eq "old",
3967 elsif ( $tok eq ')' ) {
3968 $in_statement_continuation = 1
3969 if $routput_container_type->[$i] =~ /^[;,\{\}]$/;
3972 elsif ( $tok eq ';' ) { $in_statement_continuation = 0 }
3975 # use environment after updating
3976 $container_environment =
3977 $nesting_block_flag ? 'BLOCK'
3978 : $nesting_list_flag ? 'LIST'
3980 $ci_string_i = $ci_string_sum + $in_statement_continuation;
3981 $nesting_block_string_i = $nesting_block_string;
3982 $nesting_list_string_i = $nesting_list_string;
3985 # not a structural indentation type..
3988 $container_environment =
3989 $nesting_block_flag ? 'BLOCK'
3990 : $nesting_list_flag ? 'LIST'
3993 # zero the continuation indentation at certain tokens so
3994 # that they will be at the same level as its container. For
3995 # commas, this simplifies the -lp indentation logic, which
3996 # counts commas. For ?: it makes them stand out.
3997 if ($nesting_list_flag) {
3998 if ( $type =~ /^[,\?\:]$/ ) {
3999 $in_statement_continuation = 0;
4003 # be sure binary operators get continuation indentation
4005 $container_environment
4006 && ( $type eq 'k' && $is_binary_keyword{$tok}
4007 || $is_binary_type{$type} )
4010 $in_statement_continuation = 1;
4013 # continuation indentation is sum of any open ci from previous
4014 # levels plus the current level
4015 $ci_string_i = $ci_string_sum + $in_statement_continuation;
4017 # update continuation flag ...
4018 # if this isn't a blank or comment..
4019 if ( $type ne 'b' && $type ne '#' ) {
4021 # and we are in a BLOCK
4022 if ($nesting_block_flag) {
4024 # the next token after a ';' and label starts a new stmt
4025 if ( $type eq ';' || $type eq 'J' ) {
4026 $in_statement_continuation = 0;
4029 # otherwise, we are continuing the current statement
4031 $in_statement_continuation = 1;
4035 # if we are not in a BLOCK..
4038 # do not use continuation indentation if not list
4039 # environment (could be within if/elsif clause)
4040 if ( !$nesting_list_flag ) {
4041 $in_statement_continuation = 0;
4044 # otherwise, the token after a ',' starts a new term
4046 # Patch FOR RT#99961; no continuation after a ';'
4047 # This is needed because perltidy currently marks
4048 # a block preceded by a type character like % or @
4049 # as a non block, to simplify formatting. But these
4050 # are actually blocks and can have semicolons.
4051 # See code_block_type() and is_non_structural_brace().
4052 elsif ( $type eq ',' || $type eq ';' ) {
4053 $in_statement_continuation = 0;
4056 # otherwise, we are continuing the current term
4058 $in_statement_continuation = 1;
4064 if ( $level_in_tokenizer < 0 ) {
4065 unless ( $tokenizer_self->{_saw_negative_indentation} ) {
4066 $tokenizer_self->{_saw_negative_indentation} = 1;
4067 warning("Starting negative indentation\n");
4071 # set secondary nesting levels based on all containment token types
4072 # Note: these are set so that the nesting depth is the depth
4073 # of the PREVIOUS TOKEN, which is convenient for setting
4074 # the strength of token bonds
4075 my $slevel_i = $slevel_in_tokenizer;
4078 if ( $is_opening_type{$type} ) {
4079 $slevel_in_tokenizer++;
4080 $nesting_token_string .= $tok;
4081 $nesting_type_string .= $type;
4085 elsif ( $is_closing_type{$type} ) {
4086 $slevel_in_tokenizer--;
4087 my $char = chop $nesting_token_string;
4089 if ( $char ne $matching_start_token{$tok} ) {
4090 $nesting_token_string .= $char . $tok;
4091 $nesting_type_string .= $type;
4094 chop $nesting_type_string;
4098 push( @block_type, $routput_block_type->[$i] );
4099 push( @ci_string, $ci_string_i );
4100 push( @container_environment, $container_environment );
4101 push( @container_type, $routput_container_type->[$i] );
4102 push( @levels, $level_i );
4103 push( @nesting_tokens, $nesting_token_string_i );
4104 push( @nesting_types, $nesting_type_string_i );
4105 push( @slevels, $slevel_i );
4106 push( @token_type, $fix_type );
4107 push( @type_sequence, $routput_type_sequence->[$i] );
4108 push( @nesting_blocks, $nesting_block_string );
4109 push( @nesting_lists, $nesting_list_string );
4111 # now form the previous token
4114 $rtoken_map->[$i] - $rtoken_map->[$im]; # how many characters
4118 substr( $input_line, $rtoken_map->[$im], $num ) );
4124 $num = length($input_line) - $rtoken_map->[$im]; # make the last token
4126 push( @tokens, substr( $input_line, $rtoken_map->[$im], $num ) );
4129 $tokenizer_self->{_in_attribute_list} = $in_attribute_list;
4130 $tokenizer_self->{_in_quote} = $in_quote;
4131 $tokenizer_self->{_quote_target} =
4132 $in_quote ? matching_end_token($quote_character) : "";
4133 $tokenizer_self->{_rhere_target_list} = $rhere_target_list;
4135 $line_of_tokens->{_rtoken_type} = \@token_type;
4136 $line_of_tokens->{_rtokens} = \@tokens;
4137 $line_of_tokens->{_rblock_type} = \@block_type;
4138 $line_of_tokens->{_rcontainer_type} = \@container_type;
4139 $line_of_tokens->{_rcontainer_environment} = \@container_environment;
4140 $line_of_tokens->{_rtype_sequence} = \@type_sequence;
4141 $line_of_tokens->{_rlevels} = \@levels;
4142 $line_of_tokens->{_rslevels} = \@slevels;
4143 $line_of_tokens->{_rnesting_tokens} = \@nesting_tokens;
4144 $line_of_tokens->{_rci_levels} = \@ci_string;
4145 $line_of_tokens->{_rnesting_blocks} = \@nesting_blocks;
4149 } # end tokenize_this_line
4151 #########i#############################################################
4152 # Tokenizer routines which assist in identifying token types
4153 #######################################################################
4155 sub operator_expected {
4157 # Many perl symbols have two or more meanings. For example, '<<'
4158 # can be a shift operator or a here-doc operator. The
4159 # interpretation of these symbols depends on the current state of
4160 # the tokenizer, which may either be expecting a term or an
4161 # operator. For this example, a << would be a shift if an operator
4162 # is expected, and a here-doc if a term is expected. This routine
4163 # is called to make this decision for any current token. It returns
4164 # one of three possible values:
4166 # OPERATOR - operator expected (or at least, not a term)
4167 # UNKNOWN - can't tell
4168 # TERM - a term is expected (or at least, not an operator)
4170 # The decision is based on what has been seen so far. This
4171 # information is stored in the "$last_nonblank_type" and
4172 # "$last_nonblank_token" variables. For example, if the
4173 # $last_nonblank_type is '=~', then we are expecting a TERM, whereas
4174 # if $last_nonblank_type is 'n' (numeric), we are expecting an
4177 # If a UNKNOWN is returned, the calling routine must guess. A major
4178 # goal of this tokenizer is to minimize the possibility of returning
4179 # UNKNOWN, because a wrong guess can spoil the formatting of a
4182 # adding NEW_TOKENS: it is critically important that this routine be
4183 # updated to allow it to determine if an operator or term is to be
4184 # expected after the new token. Doing this simply involves adding
4185 # the new token character to one of the regexes in this routine or
4186 # to one of the hash lists
4187 # that it uses, which are initialized in the BEGIN section.
4188 # USES GLOBAL VARIABLES: $last_nonblank_type, $last_nonblank_token,
4191 my ( $prev_type, $tok, $next_type ) = @_;
4193 my $op_expected = UNKNOWN;
4195 ##print "tok=$tok last type=$last_nonblank_type last tok=$last_nonblank_token\n";
4197 # Note: function prototype is available for token type 'U' for future
4198 # program development. It contains the leading and trailing parens,
4199 # and no blanks. It might be used to eliminate token type 'C', for
4200 # example (prototype = '()'). Thus:
4201 # if ($last_nonblank_type eq 'U') {
4202 # print "previous token=$last_nonblank_token type=$last_nonblank_type prototype=$last_nonblank_prototype\n";
4205 # A possible filehandle (or object) requires some care...
4206 if ( $last_nonblank_type eq 'Z' ) {
4209 if ( $last_nonblank_token =~ /^[A-Za-z_]/ ) {
4210 $op_expected = UNKNOWN;
4213 # For possible file handle like "$a", Perl uses weird parsing rules.
4215 # print $a/2,"/hi"; - division
4216 # print $a / 2,"/hi"; - division
4217 # print $a/ 2,"/hi"; - division
4218 # print $a /2,"/hi"; - pattern (and error)!
4219 elsif ( ( $prev_type eq 'b' ) && ( $next_type ne 'b' ) ) {
4220 $op_expected = TERM;
4223 # Note when an operation is being done where a
4224 # filehandle might be expected, since a change in whitespace
4225 # could change the interpretation of the statement.
4227 if ( $tok =~ /^([x\/\+\-\*\%\&\.\?\<]|\>\>)$/ ) {
4228 complain("operator in print statement not recommended\n");
4229 $op_expected = OPERATOR;
4234 # Check for smartmatch operator before preceding brace or square bracket.
4235 # For example, at the ? after the ] in the following expressions we are
4236 # expecting an operator:
4238 # qr/3/ ~~ ['1234'] ? 1 : 0;
4239 # map { $_ ~~ [ '0', '1' ] ? 'x' : 'o' } @a;
4240 elsif ( $last_nonblank_type eq '}' && $last_nonblank_token eq '~~' ) {
4241 $op_expected = OPERATOR;
4244 # handle something after 'do' and 'eval'
4245 elsif ( $is_block_operator{$last_nonblank_token} ) {
4247 # something like $a = eval "expression";
4249 if ( $last_nonblank_type eq 'k' ) {
4250 $op_expected = TERM; # expression or list mode following keyword
4253 # something like $a = do { BLOCK } / 2;
4254 # or this ? after a smartmatch anonynmous hash or array reference:
4255 # qr/3/ ~~ ['1234'] ? 1 : 0;
4258 $op_expected = OPERATOR; # block mode following }
4262 # handle bare word..
4263 elsif ( $last_nonblank_type eq 'w' ) {
4265 # unfortunately, we can't tell what type of token to expect next
4266 # after most bare words
4267 $op_expected = UNKNOWN;
4270 # operator, but not term possible after these types
4271 # Note: moved ')' from type to token because parens in list context
4272 # get marked as '{' '}' now. This is a minor glitch in the following:
4273 # my %opts = (ref $_[0] eq 'HASH') ? %{shift()} : ();
4275 elsif (( $last_nonblank_type =~ /^[\]RnviQh]$/ )
4276 || ( $last_nonblank_token =~ /^(\)|\$|\-\>)/ ) )
4278 $op_expected = OPERATOR;
4280 # in a 'use' statement, numbers and v-strings are not true
4281 # numbers, so to avoid incorrect error messages, we will
4282 # mark them as unknown for now (use.t)
4283 # TODO: it would be much nicer to create a new token V for VERSION
4284 # number in a use statement. Then this could be a check on type V
4285 # and related patches which change $statement_type for '=>'
4286 # and ',' could be removed. Further, it would clean things up to
4287 # scan the 'use' statement with a separate subroutine.
4288 if ( ( $statement_type eq 'use' )
4289 && ( $last_nonblank_type =~ /^[nv]$/ ) )
4291 $op_expected = UNKNOWN;
4294 # expecting VERSION or {} after package NAMESPACE
4295 elsif ($statement_type =~ /^package\b/
4296 && $last_nonblank_token =~ /^package\b/ )
4298 $op_expected = TERM;
4302 # no operator after many keywords, such as "die", "warn", etc
4303 elsif ( $expecting_term_token{$last_nonblank_token} ) {
4305 # // may follow perl functions which may be unary operators
4306 # see test file dor.t (defined or);
4308 && $next_type eq '/'
4309 && $last_nonblank_type eq 'k'
4310 && $is_keyword_taking_optional_args{$last_nonblank_token} )
4312 $op_expected = OPERATOR;
4315 $op_expected = TERM;
4319 # no operator after things like + - ** (i.e., other operators)
4320 elsif ( $expecting_term_types{$last_nonblank_type} ) {
4321 $op_expected = TERM;
4324 # a few operators, like "time", have an empty prototype () and so
4325 # take no parameters but produce a value to operate on
4326 elsif ( $expecting_operator_token{$last_nonblank_token} ) {
4327 $op_expected = OPERATOR;
4330 # post-increment and decrement produce values to be operated on
4331 elsif ( $expecting_operator_types{$last_nonblank_type} ) {
4332 $op_expected = OPERATOR;
4335 # no value to operate on after sub block
4336 elsif ( $last_nonblank_token =~ /^sub\s/ ) { $op_expected = TERM; }
4338 # a right brace here indicates the end of a simple block.
4339 # all non-structural right braces have type 'R'
4340 # all braces associated with block operator keywords have been given those
4341 # keywords as "last_nonblank_token" and caught above.
4342 # (This statement is order dependent, and must come after checking
4343 # $last_nonblank_token).
4344 elsif ( $last_nonblank_type eq '}' ) {
4346 # patch for dor.t (defined or).
4348 && $next_type eq '/'
4349 && $last_nonblank_token eq ']' )
4351 $op_expected = OPERATOR;
4354 # Patch for RT #116344: misparse a ternary operator after an anonymous
4356 # return ref {} ? 1 : 0;
4357 # The right brace should really be marked type 'R' in this case, and
4358 # it is safest to return an UNKNOWN here. Expecting a TERM will
4359 # cause the '?' to always be interpreted as a pattern delimiter
4360 # rather than introducing a ternary operator.
4361 elsif ( $tok eq '?' ) {
4362 $op_expected = UNKNOWN;
4365 $op_expected = TERM;
4369 # something else..what did I forget?
4372 # collecting diagnostics on unknown operator types..see what was missed
4373 $op_expected = UNKNOWN;
4375 "OP: unknown after type=$last_nonblank_type token=$last_nonblank_token\n"
4379 TOKENIZER_DEBUG_FLAG_EXPECT && do {
4381 "EXPECT: returns $op_expected for last type $last_nonblank_type token $last_nonblank_token\n";
4383 return $op_expected;
4386 sub new_statement_ok {
4388 # return true if the current token can start a new statement
4389 # USES GLOBAL VARIABLES: $last_nonblank_type
4391 return label_ok() # a label would be ok here
4393 || $last_nonblank_type eq 'J'; # or we follow a label
4399 # Decide if a bare word followed by a colon here is a label
4400 # USES GLOBAL VARIABLES: $last_nonblank_token, $last_nonblank_type,
4401 # $brace_depth, @brace_type
4403 # if it follows an opening or closing code block curly brace..
4404 if ( ( $last_nonblank_token eq '{' || $last_nonblank_token eq '}' )
4405 && $last_nonblank_type eq $last_nonblank_token )
4408 # it is a label if and only if the curly encloses a code block
4409 return $brace_type[$brace_depth];
4412 # otherwise, it is a label if and only if it follows a ';' (real or fake)
4415 return ( $last_nonblank_type eq ';' || $last_nonblank_type eq 'J' );
4419 sub code_block_type {
4421 # Decide if this is a block of code, and its type.
4422 # Must be called only when $type = $token = '{'
4423 # The problem is to distinguish between the start of a block of code
4424 # and the start of an anonymous hash reference
4425 # Returns "" if not code block, otherwise returns 'last_nonblank_token'
4426 # to indicate the type of code block. (For example, 'last_nonblank_token'
4427 # might be 'if' for an if block, 'else' for an else block, etc).
4428 # USES GLOBAL VARIABLES: $last_nonblank_token, $last_nonblank_type,
4429 # $last_nonblank_block_type, $brace_depth, @brace_type
4431 # handle case of multiple '{'s
4433 # print "BLOCK_TYPE EXAMINING: type=$last_nonblank_type tok=$last_nonblank_token\n";
4435 my ( $i, $rtokens, $rtoken_type, $max_token_index ) = @_;
4436 if ( $last_nonblank_token eq '{'
4437 && $last_nonblank_type eq $last_nonblank_token )
4440 # opening brace where a statement may appear is probably
4441 # a code block but might be and anonymous hash reference
4442 if ( $brace_type[$brace_depth] ) {
4443 return decide_if_code_block( $i, $rtokens, $rtoken_type,
4447 # cannot start a code block within an anonymous hash
4453 elsif ( $last_nonblank_token eq ';' ) {
4455 # an opening brace where a statement may appear is probably
4456 # a code block but might be and anonymous hash reference
4457 return decide_if_code_block( $i, $rtokens, $rtoken_type,
4461 # handle case of '}{'
4462 elsif ($last_nonblank_token eq '}'
4463 && $last_nonblank_type eq $last_nonblank_token )
4466 # a } { situation ...
4467 # could be hash reference after code block..(blktype1.t)
4468 if ($last_nonblank_block_type) {
4469 return decide_if_code_block( $i, $rtokens, $rtoken_type,
4473 # must be a block if it follows a closing hash reference
4475 return $last_nonblank_token;
4479 ################################################################
4480 # NOTE: braces after type characters start code blocks, but for
4481 # simplicity these are not identified as such. See also
4482 # sub is_non_structural_brace.
4483 ################################################################
4485 ## elsif ( $last_nonblank_type eq 't' ) {
4486 ## return $last_nonblank_token;
4489 # brace after label:
4490 elsif ( $last_nonblank_type eq 'J' ) {
4491 return $last_nonblank_token;
4494 # otherwise, look at previous token. This must be a code block if
4495 # it follows any of these:
4496 # /^(BEGIN|END|CHECK|INIT|AUTOLOAD|DESTROY|UNITCHECK|continue|if|elsif|else|unless|do|while|until|eval|for|foreach|map|grep|sort)$/
4497 elsif ( $is_code_block_token{$last_nonblank_token} ) {
4499 # Bug Patch: Note that the opening brace after the 'if' in the following
4500 # snippet is an anonymous hash ref and not a code block!
4501 # print 'hi' if { x => 1, }->{x};
4502 # We can identify this situation because the last nonblank type
4503 # will be a keyword (instead of a closing peren)
4504 if ( $last_nonblank_token =~ /^(if|unless)$/
4505 && $last_nonblank_type eq 'k' )
4510 return $last_nonblank_token;
4514 # or a sub or package BLOCK
4515 elsif ( ( $last_nonblank_type eq 'i' || $last_nonblank_type eq 't' )
4516 && $last_nonblank_token =~ /^(sub|package)\b/ )
4518 return $last_nonblank_token;
4521 elsif ( $statement_type =~ /^(sub|package)\b/ ) {
4522 return $statement_type;
4525 # user-defined subs with block parameters (like grep/map/eval)
4526 elsif ( $last_nonblank_type eq 'G' ) {
4527 return $last_nonblank_token;
4531 elsif ( $last_nonblank_type eq 'w' ) {
4532 return decide_if_code_block( $i, $rtokens, $rtoken_type,
4536 # Patch for bug # RT #94338 reported by Daniel Trizen
4537 # for-loop in a parenthesized block-map triggering an error message:
4538 # map( { foreach my $item ( '0', '1' ) { print $item} } qw(a b c) );
4539 # Check for a code block within a parenthesized function call
4540 elsif ( $last_nonblank_token eq '(' ) {
4541 my $paren_type = $paren_type[$paren_depth];
4542 if ( $paren_type && $paren_type =~ /^(map|grep|sort)$/ ) {
4544 # We will mark this as a code block but use type 't' instead
4545 # of the name of the contining function. This will allow for
4546 # correct parsing but will usually produce better formatting.
4547 # Braces with block type 't' are not broken open automatically
4548 # in the formatter as are other code block types, and this usually
4550 return 't'; # (Not $paren_type)
4557 # handle unknown syntax ') {'
4558 # we previously appended a '()' to mark this case
4559 elsif ( $last_nonblank_token =~ /\(\)$/ ) {
4560 return $last_nonblank_token;
4563 # anything else must be anonymous hash reference
4569 sub decide_if_code_block {
4571 # USES GLOBAL VARIABLES: $last_nonblank_token
4572 my ( $i, $rtokens, $rtoken_type, $max_token_index ) = @_;
4574 my ( $next_nonblank_token, $i_next ) =
4575 find_next_nonblank_token( $i, $rtokens, $max_token_index );
4577 # we are at a '{' where a statement may appear.
4578 # We must decide if this brace starts an anonymous hash or a code
4580 # return "" if anonymous hash, and $last_nonblank_token otherwise
4582 # initialize to be code BLOCK
4583 my $code_block_type = $last_nonblank_token;
4585 # Check for the common case of an empty anonymous hash reference:
4586 # Maybe something like sub { { } }
4587 if ( $next_nonblank_token eq '}' ) {
4588 $code_block_type = "";
4593 # To guess if this '{' is an anonymous hash reference, look ahead
4594 # and test as follows:
4596 # it is a hash reference if next come:
4597 # - a string or digit followed by a comma or =>
4598 # - bareword followed by =>
4599 # otherwise it is a code block
4601 # Examples of anonymous hash ref:
4605 # Examples of code blocks:
4606 # {1; print "hello\n", 1;}
4609 # We are only going to look ahead one more (nonblank/comment) line.
4610 # Strange formatting could cause a bad guess, but that's unlikely.
4614 # Ignore the rest of this line if it is a side comment
4615 if ( $next_nonblank_token ne '#' ) {
4616 @pre_types = @{$rtoken_type}[ $i + 1 .. $max_token_index ];
4617 @pre_tokens = @{$rtokens}[ $i + 1 .. $max_token_index ];
4619 my ( $rpre_tokens, $rpre_types ) =
4620 peek_ahead_for_n_nonblank_pre_tokens(20); # 20 is arbitrary but
4621 # generous, and prevents
4623 # time in mangled files
4624 if ( defined($rpre_types) && @{$rpre_types} ) {
4625 push @pre_types, @{$rpre_types};
4626 push @pre_tokens, @{$rpre_tokens};
4629 # put a sentinel token to simplify stopping the search
4630 push @pre_types, '}';
4631 push @pre_types, '}';
4634 $jbeg = 1 if $pre_types[0] eq 'b';
4636 # first look for one of these
4638 # - bareword with leading -
4642 if ( $pre_types[$j] =~ /^[\'\"]/ ) {
4644 # find the closing quote; don't worry about escapes
4645 my $quote_mark = $pre_types[$j];
4646 foreach my $k ( $j + 1 .. @pre_types - 2 ) {
4647 if ( $pre_types[$k] eq $quote_mark ) {
4649 my $next = $pre_types[$j];
4654 elsif ( $pre_types[$j] eq 'd' ) {
4657 elsif ( $pre_types[$j] eq 'w' ) {
4660 elsif ( $pre_types[$j] eq '-' && $pre_types[ ++$j ] eq 'w' ) {
4665 $j++ if $pre_types[$j] eq 'b';
4667 # Patched for RT #95708
4670 # it is a comma which is not a pattern delimeter except for qw
4672 $pre_types[$j] eq ','
4673 && $pre_tokens[$jbeg] !~ /^(s|m|y|tr|qr|q|qq|qx)$/
4677 || ( $pre_types[$j] eq '=' && $pre_types[ ++$j ] eq '>' )
4680 $code_block_type = "";
4685 return $code_block_type;
4688 sub report_unexpected {
4690 # report unexpected token type and show where it is
4691 # USES GLOBAL VARIABLES: $tokenizer_self
4692 my ( $found, $expecting, $i_tok, $last_nonblank_i, $rpretoken_map,
4693 $rpretoken_type, $input_line )
4696 if ( ++$tokenizer_self->{_unexpected_error_count} <= MAX_NAG_MESSAGES ) {
4697 my $msg = "found $found where $expecting expected";
4698 my $pos = $rpretoken_map->[$i_tok];
4699 interrupt_logfile();
4700 my $input_line_number = $tokenizer_self->{_last_line_number};
4701 my ( $offset, $numbered_line, $underline ) =
4702 make_numbered_line( $input_line_number, $input_line, $pos );
4703 $underline = write_on_underline( $underline, $pos - $offset, '^' );
4706 if ( ( $i_tok > 0 ) && ( $last_nonblank_i >= 0 ) ) {
4707 my $pos_prev = $rpretoken_map->[$last_nonblank_i];
4709 if ( $rpretoken_type->[ $i_tok - 1 ] eq 'b' ) {
4710 $num = $rpretoken_map->[ $i_tok - 1 ] - $pos_prev;
4713 $num = $pos - $pos_prev;
4715 if ( $num > 40 ) { $num = 40; $pos_prev = $pos - 40; }
4718 write_on_underline( $underline, $pos_prev - $offset, '-' x $num );
4719 $trailer = " (previous token underlined)";
4721 warning( $numbered_line . "\n" );
4722 warning( $underline . "\n" );
4723 warning( $msg . $trailer . "\n" );
4729 sub is_non_structural_brace {
4731 # Decide if a brace or bracket is structural or non-structural
4732 # by looking at the previous token and type
4733 # USES GLOBAL VARIABLES: $last_nonblank_type, $last_nonblank_token
4735 # EXPERIMENTAL: Mark slices as structural; idea was to improve formatting.
4736 # Tentatively deactivated because it caused the wrong operator expectation
4738 # $user = @vars[1] / 100;
4739 # Must update sub operator_expected before re-implementing.
4740 # if ( $last_nonblank_type eq 'i' && $last_nonblank_token =~ /^@/ ) {
4744 ################################################################
4745 # NOTE: braces after type characters start code blocks, but for
4746 # simplicity these are not identified as such. See also
4747 # sub code_block_type
4748 ################################################################
4750 ##if ($last_nonblank_type eq 't') {return 0}
4752 # otherwise, it is non-structural if it is decorated
4753 # by type information.
4754 # For example, the '{' here is non-structural: ${xxx}
4756 $last_nonblank_token =~ /^([\$\@\*\&\%\)]|->|::)/
4758 # or if we follow a hash or array closing curly brace or bracket
4759 # For example, the second '{' in this is non-structural: $a{'x'}{'y'}
4760 # because the first '}' would have been given type 'R'
4761 || $last_nonblank_type =~ /^([R\]])$/
4765 #########i#############################################################
4766 # Tokenizer routines for tracking container nesting depths
4767 #######################################################################
4769 # The following routines keep track of nesting depths of the nesting
4770 # types, ( [ { and ?. This is necessary for determining the indentation
4771 # level, and also for debugging programs. Not only do they keep track of
4772 # nesting depths of the individual brace types, but they check that each
4773 # of the other brace types is balanced within matching pairs. For
4774 # example, if the program sees this sequence:
4778 # then it can determine that there is an extra left paren somewhere
4779 # between the { and the }. And so on with every other possible
4780 # combination of outer and inner brace types. For another
4785 # which has an extra ] within the parens.
4787 # The brace types have indexes 0 .. 3 which are indexes into
4790 # The pair ? : are treated as just another nesting type, with ? acting
4791 # as the opening brace and : acting as the closing brace.
4795 # $depth_array[$a][$b][ $current_depth[$a] ] = $current_depth[$b];
4797 # saves the nesting depth of brace type $b (where $b is either of the other
4798 # nesting types) when brace type $a enters a new depth. When this depth
4799 # decreases, a check is made that the current depth of brace types $b is
4800 # unchanged, or otherwise there must have been an error. This can
4801 # be very useful for localizing errors, particularly when perl runs to
4802 # the end of a large file (such as this one) and announces that there
4803 # is a problem somewhere.
4805 # A numerical sequence number is maintained for every nesting type,
4806 # so that each matching pair can be uniquely identified in a simple
4809 sub increase_nesting_depth {
4810 my ( $aa, $pos ) = @_;
4812 # USES GLOBAL VARIABLES: $tokenizer_self, @current_depth,
4813 # @current_sequence_number, @depth_array, @starting_line_of_current_depth,
4815 $current_depth[$aa]++;
4817 $total_depth[$aa][ $current_depth[$aa] ] = $total_depth;
4818 my $input_line_number = $tokenizer_self->{_last_line_number};
4819 my $input_line = $tokenizer_self->{_line_text};
4821 # Sequence numbers increment by number of items. This keeps
4822 # a unique set of numbers but still allows the relative location
4823 # of any type to be determined.
4824 $nesting_sequence_number[$aa] += scalar(@closing_brace_names);
4825 my $seqno = $nesting_sequence_number[$aa];
4826 $current_sequence_number[$aa][ $current_depth[$aa] ] = $seqno;
4828 $starting_line_of_current_depth[$aa][ $current_depth[$aa] ] =
4829 [ $input_line_number, $input_line, $pos ];
4831 for my $bb ( 0 .. @closing_brace_names - 1 ) {
4832 next if ( $bb == $aa );
4833 $depth_array[$aa][$bb][ $current_depth[$aa] ] = $current_depth[$bb];
4836 # set a flag for indenting a nested ternary statement
4838 if ( $aa == QUESTION_COLON ) {
4839 $nested_ternary_flag[ $current_depth[$aa] ] = 0;
4840 if ( $current_depth[$aa] > 1 ) {
4841 if ( $nested_ternary_flag[ $current_depth[$aa] - 1 ] == 0 ) {
4842 my $pdepth = $total_depth[$aa][ $current_depth[$aa] - 1 ];
4843 if ( $pdepth == $total_depth - 1 ) {
4845 $nested_ternary_flag[ $current_depth[$aa] - 1 ] = -1;
4850 $nested_statement_type[$aa][ $current_depth[$aa] ] = $statement_type;
4851 $statement_type = "";
4852 return ( $seqno, $indent );
4855 sub decrease_nesting_depth {
4857 my ( $aa, $pos ) = @_;
4859 # USES GLOBAL VARIABLES: $tokenizer_self, @current_depth,
4860 # @current_sequence_number, @depth_array, @starting_line_of_current_depth
4863 my $input_line_number = $tokenizer_self->{_last_line_number};
4864 my $input_line = $tokenizer_self->{_line_text};
4868 if ( $current_depth[$aa] > 0 ) {
4870 # set a flag for un-indenting after seeing a nested ternary statement
4871 $seqno = $current_sequence_number[$aa][ $current_depth[$aa] ];
4872 if ( $aa == QUESTION_COLON ) {
4873 $outdent = $nested_ternary_flag[ $current_depth[$aa] ];
4875 $statement_type = $nested_statement_type[$aa][ $current_depth[$aa] ];
4877 # check that any brace types $bb contained within are balanced
4878 for my $bb ( 0 .. @closing_brace_names - 1 ) {
4879 next if ( $bb == $aa );
4881 unless ( $depth_array[$aa][$bb][ $current_depth[$aa] ] ==
4882 $current_depth[$bb] )
4885 $current_depth[$bb] -
4886 $depth_array[$aa][$bb][ $current_depth[$aa] ];
4888 # don't whine too many times
4889 my $saw_brace_error = get_saw_brace_error();
4891 $saw_brace_error <= MAX_NAG_MESSAGES
4893 # if too many closing types have occurred, we probably
4894 # already caught this error
4895 && ( ( $diff > 0 ) || ( $saw_brace_error <= 0 ) )
4898 interrupt_logfile();
4900 $starting_line_of_current_depth[$aa]
4901 [ $current_depth[$aa] ];
4903 my $rel = [ $input_line_number, $input_line, $pos ];
4907 if ( $diff == 1 || $diff == -1 ) {
4915 ? $opening_brace_names[$bb]
4916 : $closing_brace_names[$bb];
4917 write_error_indicator_pair( @{$rsl}, '^' );
4919 Found $diff extra $bname$ess between $opening_brace_names[$aa] on line $sl and $closing_brace_names[$aa] on line $el
4924 $starting_line_of_current_depth[$bb]
4925 [ $current_depth[$bb] ];
4928 " The most recent un-matched $bname is on line $ml\n";
4929 write_error_indicator_pair( @{$rml}, '^' );
4931 write_error_indicator_pair( @{$rel}, '^' );
4935 increment_brace_error();
4938 $current_depth[$aa]--;
4942 my $saw_brace_error = get_saw_brace_error();
4943 if ( $saw_brace_error <= MAX_NAG_MESSAGES ) {
4945 There is no previous $opening_brace_names[$aa] to match a $closing_brace_names[$aa] on line $input_line_number
4947 indicate_error( $msg, $input_line_number, $input_line, $pos, '^' );
4949 increment_brace_error();
4951 return ( $seqno, $outdent );
4954 sub check_final_nesting_depths {
4956 # USES GLOBAL VARIABLES: @current_depth, @starting_line_of_current_depth
4958 for my $aa ( 0 .. @closing_brace_names - 1 ) {
4960 if ( $current_depth[$aa] ) {
4962 $starting_line_of_current_depth[$aa][ $current_depth[$aa] ];
4965 Final nesting depth of $opening_brace_names[$aa]s is $current_depth[$aa]
4966 The most recent un-matched $opening_brace_names[$aa] is on line $sl
4968 indicate_error( $msg, @{$rsl}, '^' );
4969 increment_brace_error();
4975 #########i#############################################################
4976 # Tokenizer routines for looking ahead in input stream
4977 #######################################################################
4979 sub peek_ahead_for_n_nonblank_pre_tokens {
4981 # returns next n pretokens if they exist
4982 # returns undef's if hits eof without seeing any pretokens
4983 # USES GLOBAL VARIABLES: $tokenizer_self
4984 my $max_pretokens = shift;
4987 my ( $rpre_tokens, $rmap, $rpre_types );
4989 while ( $line = $tokenizer_self->{_line_buffer_object}->peek_ahead( $i++ ) )
4991 $line =~ s/^\s*//; # trim leading blanks
4992 next if ( length($line) <= 0 ); # skip blank
4993 next if ( $line =~ /^#/ ); # skip comment
4994 ( $rpre_tokens, $rmap, $rpre_types ) =
4995 pre_tokenize( $line, $max_pretokens );
4998 return ( $rpre_tokens, $rpre_types );
5001 # look ahead for next non-blank, non-comment line of code
5002 sub peek_ahead_for_nonblank_token {
5004 # USES GLOBAL VARIABLES: $tokenizer_self
5005 my ( $rtokens, $max_token_index ) = @_;
5009 while ( $line = $tokenizer_self->{_line_buffer_object}->peek_ahead( $i++ ) )
5011 $line =~ s/^\s*//; # trim leading blanks
5012 next if ( length($line) <= 0 ); # skip blank
5013 next if ( $line =~ /^#/ ); # skip comment
5014 my ( $rtok, $rmap, $rtype ) =
5015 pre_tokenize( $line, 2 ); # only need 2 pre-tokens
5016 my $j = $max_token_index + 1;
5018 foreach my $tok ( @{$rtok} ) {
5019 last if ( $tok =~ "\n" );
5020 $rtokens->[ ++$j ] = $tok;
5027 #########i#############################################################
5028 # Tokenizer guessing routines for ambiguous situations
5029 #######################################################################
5031 sub guess_if_pattern_or_conditional {
5033 # this routine is called when we have encountered a ? following an
5034 # unknown bareword, and we must decide if it starts a pattern or not
5036 # $i - token index of the ? starting possible pattern
5037 # output parameters:
5038 # $is_pattern = 0 if probably not pattern, =1 if probably a pattern
5039 # msg = a warning or diagnostic message
5040 # USES GLOBAL VARIABLES: $last_nonblank_token
5042 # FIXME: this needs to be rewritten
5044 my ( $i, $rtokens, $rtoken_map, $max_token_index ) = @_;
5046 my $msg = "guessing that ? after $last_nonblank_token starts a ";
5048 if ( $i >= $max_token_index ) {
5049 $msg .= "conditional (no end to pattern found on the line)\n";
5054 my $next_token = $rtokens->[$i]; # first token after ?
5056 # look for a possible ending ? on this line..
5058 my $quote_depth = 0;
5059 my $quote_character = '';
5063 $i, $in_quote, $quote_character, $quote_pos, $quote_depth,
5066 = follow_quoted_string( $ibeg, $in_quote, $rtokens, $quote_character,
5067 $quote_pos, $quote_depth, $max_token_index );
5071 # we didn't find an ending ? on this line,
5072 # so we bias towards conditional
5074 $msg .= "conditional (no ending ? on this line)\n";
5076 # we found an ending ?, so we bias towards a pattern
5080 # Watch out for an ending ? in quotes, like this
5081 # my $case_flag = File::Spec->case_tolerant ? '(?i)' : '';
5085 foreach my $ii ( $ibeg + 1 .. $i - 1 ) {
5086 my $tok = $rtokens->[$ii];
5087 if ( $tok eq ":" ) { $colons++ }
5088 if ( $tok eq "'" ) { $s_quote++ }
5089 if ( $tok eq '"' ) { $d_quote++ }
5091 if ( $s_quote % 2 || $d_quote % 2 || $colons ) {
5093 $msg .= "found ending ? but unbalanced quote chars\n";
5095 elsif ( pattern_expected( $i, $rtokens, $max_token_index ) >= 0 ) {
5097 $msg .= "pattern (found ending ? and pattern expected)\n";
5100 $msg .= "pattern (uncertain, but found ending ?)\n";
5104 return ( $is_pattern, $msg );
5107 sub guess_if_pattern_or_division {
5109 # this routine is called when we have encountered a / following an
5110 # unknown bareword, and we must decide if it starts a pattern or is a
5113 # $i - token index of the / starting possible pattern
5114 # output parameters:
5115 # $is_pattern = 0 if probably division, =1 if probably a pattern
5116 # msg = a warning or diagnostic message
5117 # USES GLOBAL VARIABLES: $last_nonblank_token
5118 my ( $i, $rtokens, $rtoken_map, $max_token_index ) = @_;
5120 my $msg = "guessing that / after $last_nonblank_token starts a ";
5122 if ( $i >= $max_token_index ) {
5123 $msg .= "division (no end to pattern found on the line)\n";
5127 my $divide_expected =
5128 numerator_expected( $i, $rtokens, $max_token_index );
5130 my $next_token = $rtokens->[$i]; # first token after slash
5132 # look for a possible ending / on this line..
5134 my $quote_depth = 0;
5135 my $quote_character = '';
5139 $i, $in_quote, $quote_character, $quote_pos, $quote_depth,
5142 = follow_quoted_string( $ibeg, $in_quote, $rtokens, $quote_character,
5143 $quote_pos, $quote_depth, $max_token_index );
5147 # we didn't find an ending / on this line,
5148 # so we bias towards division
5149 if ( $divide_expected >= 0 ) {
5151 $msg .= "division (no ending / on this line)\n";
5154 $msg = "multi-line pattern (division not possible)\n";
5160 # we found an ending /, so we bias towards a pattern
5163 if ( pattern_expected( $i, $rtokens, $max_token_index ) >= 0 ) {
5165 if ( $divide_expected >= 0 ) {
5167 if ( $i - $ibeg > 60 ) {
5168 $msg .= "division (matching / too distant)\n";
5172 $msg .= "pattern (but division possible too)\n";
5178 $msg .= "pattern (division not possible)\n";
5183 if ( $divide_expected >= 0 ) {
5185 $msg .= "division (pattern not possible)\n";
5190 "pattern (uncertain, but division would not work here)\n";
5195 return ( $is_pattern, $msg );
5198 # try to resolve here-doc vs. shift by looking ahead for
5199 # non-code or the end token (currently only looks for end token)
5200 # returns 1 if it is probably a here doc, 0 if not
5201 sub guess_if_here_doc {
5203 # This is how many lines we will search for a target as part of the
5204 # guessing strategy. It is a constant because there is probably
5205 # little reason to change it.
5206 # USES GLOBAL VARIABLES: $tokenizer_self, $current_package
5208 my $HERE_DOC_WINDOW = 40;
5210 my $next_token = shift;
5211 my $here_doc_expected = 0;
5214 my $msg = "checking <<";
5216 while ( $line = $tokenizer_self->{_line_buffer_object}->peek_ahead( $k++ ) )
5220 if ( $line =~ /^$next_token$/ ) {
5221 $msg .= " -- found target $next_token ahead $k lines\n";
5222 $here_doc_expected = 1; # got it
5225 last if ( $k >= $HERE_DOC_WINDOW );
5228 unless ($here_doc_expected) {
5230 if ( !defined($line) ) {
5231 $here_doc_expected = -1; # hit eof without seeing target
5232 $msg .= " -- must be shift; target $next_token not in file\n";
5235 else { # still unsure..taking a wild guess
5237 if ( !$is_constant{$current_package}{$next_token} ) {
5238 $here_doc_expected = 1;
5240 " -- guessing it's a here-doc ($next_token not a constant)\n";
5244 " -- guessing it's a shift ($next_token is a constant)\n";
5248 write_logfile_entry($msg);
5249 return $here_doc_expected;
5252 #########i#############################################################
5253 # Tokenizer Routines for scanning identifiers and related items
5254 #######################################################################
5256 sub scan_bare_identifier_do {
5258 # this routine is called to scan a token starting with an alphanumeric
5259 # variable or package separator, :: or '.
5260 # USES GLOBAL VARIABLES: $current_package, $last_nonblank_token,
5261 # $last_nonblank_type,@paren_type, $paren_depth
5263 my ( $input_line, $i, $tok, $type, $prototype, $rtoken_map,
5267 my $package = undef;
5271 # we have to back up one pretoken at a :: since each : is one pretoken
5272 if ( $tok eq '::' ) { $i_beg-- }
5273 if ( $tok eq '->' ) { $i_beg-- }
5274 my $pos_beg = $rtoken_map->[$i_beg];
5275 pos($input_line) = $pos_beg;
5282 if ( $input_line =~ m/\G\s*((?:\w*(?:'|::)))*(?:(?:->)?(\w+))?/gc ) {
5284 my $pos = pos($input_line);
5285 my $numc = $pos - $pos_beg;
5286 $tok = substr( $input_line, $pos_beg, $numc );
5288 # type 'w' includes anything without leading type info
5289 # ($,%,@,*) including something like abc::def::ghi
5293 if ( defined($2) ) { $sub_name = $2; }
5294 if ( defined($1) ) {
5297 # patch: don't allow isolated package name which just ends
5298 # in the old style package separator (single quote). Example:
5300 if ( !($sub_name) && substr( $package, -1, 1 ) eq '\'' ) {
5304 $package =~ s/\'/::/g;
5305 if ( $package =~ /^\:/ ) { $package = 'main' . $package }
5306 $package =~ s/::$//;
5309 $package = $current_package;
5311 if ( $is_keyword{$tok} ) {
5316 # if it is a bareword..
5317 if ( $type eq 'w' ) {
5319 # check for v-string with leading 'v' type character
5320 # (This seems to have precedence over filehandle, type 'Y')
5321 if ( $tok =~ /^v\d[_\d]*$/ ) {
5323 # we only have the first part - something like 'v101' -
5325 if ( $input_line =~ m/\G(\.\d[_\d]*)+/gc ) {
5326 $pos = pos($input_line);
5327 $numc = $pos - $pos_beg;
5328 $tok = substr( $input_line, $pos_beg, $numc );
5332 # warn if this version can't handle v-strings
5333 report_v_string($tok);
5336 elsif ( $is_constant{$package}{$sub_name} ) {
5340 # bareword after sort has implied empty prototype; for example:
5341 # @sorted = sort numerically ( 53, 29, 11, 32, 7 );
5342 # This has priority over whatever the user has specified.
5343 elsif ($last_nonblank_token eq 'sort'
5344 && $last_nonblank_type eq 'k' )
5349 # Note: strangely, perl does not seem to really let you create
5350 # functions which act like eval and do, in the sense that eval
5351 # and do may have operators following the final }, but any operators
5352 # that you create with prototype (&) apparently do not allow
5353 # trailing operators, only terms. This seems strange.
5354 # If this ever changes, here is the update
5355 # to make perltidy behave accordingly:
5357 # elsif ( $is_block_function{$package}{$tok} ) {
5358 # $tok='eval'; # patch to do braces like eval - doesn't work
5361 # FIXME: This could become a separate type to allow for different
5363 elsif ( $is_block_function{$package}{$sub_name} ) {
5367 elsif ( $is_block_list_function{$package}{$sub_name} ) {
5370 elsif ( $is_user_function{$package}{$sub_name} ) {
5372 $prototype = $user_function_prototype{$package}{$sub_name};
5375 # check for indirect object
5378 # added 2001-03-27: must not be followed immediately by '('
5380 ( $input_line !~ m/\G\(/gc )
5385 # preceded by keyword like 'print', 'printf' and friends
5386 $is_indirect_object_taker{$last_nonblank_token}
5388 # or preceded by something like 'print(' or 'printf('
5390 ( $last_nonblank_token eq '(' )
5391 && $is_indirect_object_taker{ $paren_type[$paren_depth]
5399 # may not be indirect object unless followed by a space
5400 if ( $input_line =~ m/\G\s+/gc ) {
5404 # Perl's indirect object notation is a very bad
5405 # thing and can cause subtle bugs, especially for
5406 # beginning programmers. And I haven't even been
5407 # able to figure out a sane warning scheme which
5408 # doesn't get in the way of good scripts.
5410 # Complain if a filehandle has any lower case
5411 # letters. This is suggested good practice.
5412 # Use 'sub_name' because something like
5413 # main::MYHANDLE is ok for filehandle
5414 if ( $sub_name =~ /[a-z]/ ) {
5416 # could be bug caused by older perltidy if
5418 if ( $input_line =~ m/\G\s*\(/gc ) {
5420 "Caution: unknown word '$tok' in indirect object slot\n"
5426 # bareword not followed by a space -- may not be filehandle
5427 # (may be function call defined in a 'use' statement)
5434 # Now we must convert back from character position
5435 # to pre_token index.
5436 # I don't think an error flag can occur here ..but who knows
5439 inverse_pretoken_map( $i, $pos, $rtoken_map, $max_token_index );
5441 warning("scan_bare_identifier: Possibly invalid tokenization\n");
5445 # no match but line not blank - could be syntax error
5446 # perl will take '::' alone without complaint
5450 # change this warning to log message if it becomes annoying
5451 warning("didn't find identifier after leading ::\n");
5453 return ( $i, $tok, $type, $prototype );
5458 # This is the new scanner and will eventually replace scan_identifier.
5459 # Only type 'sub' and 'package' are implemented.
5460 # Token types $ * % @ & -> are not yet implemented.
5462 # Scan identifier following a type token.
5463 # The type of call depends on $id_scan_state: $id_scan_state = ''
5464 # for starting call, in which case $tok must be the token defining
5467 # If the type token is the last nonblank token on the line, a value
5468 # of $id_scan_state = $tok is returned, indicating that further
5469 # calls must be made to get the identifier. If the type token is
5470 # not the last nonblank token on the line, the identifier is
5471 # scanned and handled and a value of '' is returned.
5472 # USES GLOBAL VARIABLES: $current_package, $last_nonblank_token, $in_attribute_list,
5473 # $statement_type, $tokenizer_self
5475 my ( $input_line, $i, $tok, $rtokens, $rtoken_map, $id_scan_state,
5479 my ( $i_beg, $pos_beg );
5481 #print "NSCAN:entering i=$i, tok=$tok, type=$type, state=$id_scan_state\n";
5482 #my ($a,$b,$c) = caller;
5483 #print "NSCAN: scan_id called with tok=$tok $a $b $c\n";
5485 # on re-entry, start scanning at first token on the line
5486 if ($id_scan_state) {
5491 # on initial entry, start scanning just after type token
5494 $id_scan_state = $tok;
5498 # find $i_beg = index of next nonblank token,
5499 # and handle empty lines
5501 my $next_nonblank_token = $rtokens->[$i_beg];
5502 if ( $i_beg > $max_token_index ) {
5507 # only a '#' immediately after a '$' is not a comment
5508 if ( $next_nonblank_token eq '#' ) {
5509 unless ( $tok eq '$' ) {
5514 if ( $next_nonblank_token =~ /^\s/ ) {
5515 ( $next_nonblank_token, $i_beg ) =
5516 find_next_nonblank_token_on_this_line( $i_beg, $rtokens,
5518 if ( $next_nonblank_token =~ /(^#|^\s*$)/ ) {
5524 # handle non-blank line; identifier, if any, must follow
5525 unless ($blank_line) {
5527 if ( $id_scan_state eq 'sub' ) {
5528 ( $i, $tok, $type, $id_scan_state ) = do_scan_sub(
5529 $input_line, $i, $i_beg,
5530 $tok, $type, $rtokens,
5531 $rtoken_map, $id_scan_state, $max_token_index
5535 elsif ( $id_scan_state eq 'package' ) {
5536 ( $i, $tok, $type ) =
5537 do_scan_package( $input_line, $i, $i_beg, $tok, $type, $rtokens,
5538 $rtoken_map, $max_token_index );
5539 $id_scan_state = '';
5543 warning("invalid token in scan_id: $tok\n");
5544 $id_scan_state = '';
5548 if ( $id_scan_state && ( !defined($type) || !$type ) ) {
5552 "Program bug in scan_id: undefined type but scan_state=$id_scan_state\n"
5554 report_definite_bug();
5557 TOKENIZER_DEBUG_FLAG_NSCAN && do {
5559 "NSCAN: returns i=$i, tok=$tok, type=$type, state=$id_scan_state\n";
5561 return ( $i, $tok, $type, $id_scan_state );
5564 sub check_prototype {
5565 my ( $proto, $package, $subname ) = @_;
5566 return unless ( defined($package) && defined($subname) );
5567 if ( defined($proto) ) {
5568 $proto =~ s/^\s*\(\s*//;
5569 $proto =~ s/\s*\)$//;
5571 $is_user_function{$package}{$subname} = 1;
5572 $user_function_prototype{$package}{$subname} = "($proto)";
5574 # prototypes containing '&' must be treated specially..
5575 if ( $proto =~ /\&/ ) {
5577 # right curly braces of prototypes ending in
5578 # '&' may be followed by an operator
5579 if ( $proto =~ /\&$/ ) {
5580 $is_block_function{$package}{$subname} = 1;
5583 # right curly braces of prototypes NOT ending in
5584 # '&' may NOT be followed by an operator
5585 elsif ( $proto !~ /\&$/ ) {
5586 $is_block_list_function{$package}{$subname} = 1;
5591 $is_constant{$package}{$subname} = 1;
5595 $is_user_function{$package}{$subname} = 1;
5600 sub do_scan_package {
5602 # do_scan_package parses a package name
5603 # it is called with $i_beg equal to the index of the first nonblank
5604 # token following a 'package' token.
5605 # USES GLOBAL VARIABLES: $current_package,
5608 # package NAMESPACE VERSION
5609 # package NAMESPACE BLOCK
5610 # package NAMESPACE VERSION BLOCK
5612 # If VERSION is provided, package sets the $VERSION variable in the given
5613 # namespace to a version object with the VERSION provided. VERSION must be
5614 # a "strict" style version number as defined by the version module: a
5615 # positive decimal number (integer or decimal-fraction) without
5616 # exponentiation or else a dotted-decimal v-string with a leading 'v'
5617 # character and at least three components.
5618 # reference http://perldoc.perl.org/functions/package.html
5620 my ( $input_line, $i, $i_beg, $tok, $type, $rtokens, $rtoken_map,
5623 my $package = undef;
5624 my $pos_beg = $rtoken_map->[$i_beg];
5625 pos($input_line) = $pos_beg;
5627 # handle non-blank line; package name, if any, must follow
5628 if ( $input_line =~ m/\G\s*((?:\w*(?:'|::))*\w+)/gc ) {
5630 $package = ( defined($1) && $1 ) ? $1 : 'main';
5631 $package =~ s/\'/::/g;
5632 if ( $package =~ /^\:/ ) { $package = 'main' . $package }
5633 $package =~ s/::$//;
5634 my $pos = pos($input_line);
5635 my $numc = $pos - $pos_beg;
5636 $tok = 'package ' . substr( $input_line, $pos_beg, $numc );
5639 # Now we must convert back from character position
5640 # to pre_token index.
5641 # I don't think an error flag can occur here ..but ?
5644 inverse_pretoken_map( $i, $pos, $rtoken_map, $max_token_index );
5645 if ($error) { warning("Possibly invalid package\n") }
5646 $current_package = $package;
5648 # we should now have package NAMESPACE
5649 # now expecting VERSION, BLOCK, or ; to follow ...
5650 # package NAMESPACE VERSION
5651 # package NAMESPACE BLOCK
5652 # package NAMESPACE VERSION BLOCK
5653 my ( $next_nonblank_token, $i_next ) =
5654 find_next_nonblank_token( $i, $rtokens, $max_token_index );
5656 # check that something recognizable follows, but do not parse.
5657 # A VERSION number will be parsed later as a number or v-string in the
5658 # normal way. What is important is to set the statement type if
5659 # everything looks okay so that the operator_expected() routine
5660 # knows that the number is in a package statement.
5661 # Examples of valid primitive tokens that might follow are:
5663 if ( $next_nonblank_token =~ /^([v\.\d;\{\}])|v\d|\d+$/ ) {
5664 $statement_type = $tok;
5668 "Unexpected '$next_nonblank_token' after package name '$tok'\n"
5673 # no match but line not blank --
5674 # could be a label with name package, like package: , for example.
5679 return ( $i, $tok, $type );
5682 sub scan_identifier_do {
5684 # This routine assembles tokens into identifiers. It maintains a
5685 # scan state, id_scan_state. It updates id_scan_state based upon
5686 # current id_scan_state and token, and returns an updated
5687 # id_scan_state and the next index after the identifier.
5688 # USES GLOBAL VARIABLES: $context, $last_nonblank_token,
5689 # $last_nonblank_type
5691 my ( $i, $id_scan_state, $identifier, $rtokens, $max_token_index,
5692 $expecting, $container_type )
5696 my $tok_begin = $rtokens->[$i_begin];
5697 if ( $tok_begin eq ':' ) { $tok_begin = '::' }
5698 my $id_scan_state_begin = $id_scan_state;
5699 my $identifier_begin = $identifier;
5700 my $tok = $tok_begin;
5703 my $in_prototype_or_signature = $container_type =~ /^sub/;
5705 # these flags will be used to help figure out the type:
5706 my $saw_alpha = ( $tok =~ /^[A-Za-z_]/ );
5709 # allow old package separator (') except in 'use' statement
5710 my $allow_tick = ( $last_nonblank_token ne 'use' );
5712 # get started by defining a type and a state if necessary
5713 unless ($id_scan_state) {
5714 $context = UNKNOWN_CONTEXT;
5717 if ( $tok eq '>' ) {
5723 if ( $tok eq '$' || $tok eq '*' ) {
5724 $id_scan_state = '$';
5725 $context = SCALAR_CONTEXT;
5727 elsif ( $tok eq '%' || $tok eq '@' ) {
5728 $id_scan_state = '$';
5729 $context = LIST_CONTEXT;
5731 elsif ( $tok eq '&' ) {
5732 $id_scan_state = '&';
5734 elsif ( $tok eq 'sub' or $tok eq 'package' ) {
5735 $saw_alpha = 0; # 'sub' is considered type info here
5736 $id_scan_state = '$';
5737 $identifier .= ' '; # need a space to separate sub from sub name
5739 elsif ( $tok eq '::' ) {
5740 $id_scan_state = 'A';
5742 elsif ( $tok =~ /^[A-Za-z_]/ ) {
5743 $id_scan_state = ':';
5745 elsif ( $tok eq '->' ) {
5746 $id_scan_state = '$';
5751 my ( $a, $b, $c ) = caller;
5752 warning("Program Bug: scan_identifier given bad token = $tok \n");
5753 warning(" called from sub $a line: $c\n");
5754 report_definite_bug();
5756 $saw_type = !$saw_alpha;
5760 $saw_type = ( $tok =~ /([\$\%\@\*\&])/ );
5763 # now loop to gather the identifier
5766 while ( $i < $max_token_index ) {
5767 $i_save = $i unless ( $tok =~ /^\s*$/ );
5768 $tok = $rtokens->[ ++$i ];
5770 if ( ( $tok eq ':' ) && ( $rtokens->[ $i + 1 ] eq ':' ) ) {
5775 if ( $id_scan_state eq '$' ) { # starting variable name
5777 if ( $tok eq '$' ) {
5779 $identifier .= $tok;
5781 # we've got a punctuation variable if end of line (punct.t)
5782 if ( $i == $max_token_index ) {
5784 $id_scan_state = '';
5789 # POSTDEFREF ->@ ->% ->& ->*
5790 elsif ( ( $tok =~ /^[\@\%\&\*]$/ ) && $identifier =~ /\-\>$/ ) {
5791 $identifier .= $tok;
5793 elsif ( $tok =~ /^[A-Za-z_]/ ) { # alphanumeric ..
5795 $id_scan_state = ':'; # now need ::
5796 $identifier .= $tok;
5798 elsif ( $tok eq "'" && $allow_tick ) { # alphanumeric ..
5800 $id_scan_state = ':'; # now need ::
5801 $identifier .= $tok;
5803 # Perl will accept leading digits in identifiers,
5804 # although they may not always produce useful results.
5805 # Something like $main::0 is ok. But this also works:
5807 # sub howdy::123::bubba{ print "bubba $54321!\n" }
5808 # howdy::123::bubba();
5811 elsif ( $tok =~ /^[0-9]/ ) { # numeric
5813 $id_scan_state = ':'; # now need ::
5814 $identifier .= $tok;
5816 elsif ( $tok eq '::' ) {
5817 $id_scan_state = 'A';
5818 $identifier .= $tok;
5821 # $# and POSTDEFREF ->$#
5822 elsif ( ( $tok eq '#' ) && ( $identifier =~ /\$$/ ) ) { # $#array
5823 $identifier .= $tok; # keep same state, a $ could follow
5825 elsif ( $tok eq '{' ) {
5827 # check for something like ${#} or ${©}
5831 || $identifier eq '@'
5832 || $identifier eq '$#'
5834 && $i + 2 <= $max_token_index
5835 && $rtokens->[ $i + 2 ] eq '}'
5836 && $rtokens->[ $i + 1 ] !~ /[\s\w]/
5839 my $next2 = $rtokens->[ $i + 2 ];
5840 my $next1 = $rtokens->[ $i + 1 ];
5841 $identifier .= $tok . $next1 . $next2;
5843 $id_scan_state = '';
5847 # skip something like ${xxx} or ->{
5848 $id_scan_state = '';
5850 # if this is the first token of a line, any tokens for this
5851 # identifier have already been accumulated
5852 if ( $identifier eq '$' || $i == 0 ) { $identifier = ''; }
5857 # space ok after leading $ % * & @
5858 elsif ( $tok =~ /^\s*$/ ) {
5860 if ( $identifier =~ /^[\$\%\*\&\@]/ ) {
5862 if ( length($identifier) > 1 ) {
5863 $id_scan_state = '';
5865 $type = 'i'; # probably punctuation variable
5870 # spaces after $'s are common, and space after @
5871 # is harmless, so only complain about space
5872 # after other type characters. Space after $ and
5873 # @ will be removed in formatting. Report space
5874 # after % and * because they might indicate a
5875 # parsing error. In other words '% ' might be a
5876 # modulo operator. Delete this warning if it
5878 if ( $identifier !~ /^[\@\$]$/ ) {
5880 "Space in identifier, following $identifier\n";
5886 # space after '->' is ok
5888 elsif ( $tok eq '^' ) {
5890 # check for some special variables like $^W
5891 if ( $identifier =~ /^[\$\*\@\%]$/ ) {
5892 $identifier .= $tok;
5893 $id_scan_state = 'A';
5895 # Perl accepts '$^]' or '@^]', but
5896 # there must not be a space before the ']'.
5897 my $next1 = $rtokens->[ $i + 1 ];
5898 if ( $next1 eq ']' ) {
5900 $identifier .= $next1;
5901 $id_scan_state = "";
5906 $id_scan_state = '';
5909 else { # something else
5911 if ( $in_prototype_or_signature && $tok =~ /^[\),=]/ ) {
5912 $id_scan_state = '';
5914 $type = 'i'; # probably punctuation variable
5918 # check for various punctuation variables
5919 if ( $identifier =~ /^[\$\*\@\%]$/ ) {
5920 $identifier .= $tok;
5923 # POSTDEFREF: Postfix reference ->$* ->%* ->@* ->** ->&* ->$#*
5924 elsif ( $tok eq '*' && $identifier =~ /([\@\%\$\*\&]|\$\#)$/ ) {
5925 $identifier .= $tok;
5928 elsif ( $identifier eq '$#' ) {
5930 if ( $tok eq '{' ) { $type = 'i'; $i = $i_save }
5932 # perl seems to allow just these: $#: $#- $#+
5933 elsif ( $tok =~ /^[\:\-\+]$/ ) {
5935 $identifier .= $tok;
5939 write_logfile_entry( 'Use of $# is deprecated' . "\n" );
5942 elsif ( $identifier eq '$$' ) {
5944 # perl does not allow references to punctuation
5945 # variables without braces. For example, this
5949 # You would have to use
5953 if ( $tok eq '{' ) { $type = 't' }
5954 else { $type = 'i' }
5956 elsif ( $identifier eq '->' ) {
5961 if ( length($identifier) == 1 ) { $identifier = ''; }
5963 $id_scan_state = '';
5967 elsif ( $id_scan_state eq '&' ) { # starting sub call?
5969 if ( $tok =~ /^[\$A-Za-z_]/ ) { # alphanumeric ..
5970 $id_scan_state = ':'; # now need ::
5972 $identifier .= $tok;
5974 elsif ( $tok eq "'" && $allow_tick ) { # alphanumeric ..
5975 $id_scan_state = ':'; # now need ::
5977 $identifier .= $tok;
5979 elsif ( $tok =~ /^[0-9]/ ) { # numeric..see comments above
5980 $id_scan_state = ':'; # now need ::
5982 $identifier .= $tok;
5984 elsif ( $tok =~ /^\s*$/ ) { # allow space
5986 elsif ( $tok eq '::' ) { # leading ::
5987 $id_scan_state = 'A'; # accept alpha next
5988 $identifier .= $tok;
5990 elsif ( $tok eq '{' ) {
5991 if ( $identifier eq '&' || $i == 0 ) { $identifier = ''; }
5993 $id_scan_state = '';
5998 # punctuation variable?
5999 # testfile: cunningham4.pl
6001 # We have to be careful here. If we are in an unknown state,
6002 # we will reject the punctuation variable. In the following
6003 # example the '&' is a binary operator but we are in an unknown
6004 # state because there is no sigil on 'Prima', so we don't
6005 # know what it is. But it is a bad guess that
6006 # '&~' is a function variable.
6007 # $self->{text}->{colorMap}->[
6008 # Prima::PodView::COLOR_CODE_FOREGROUND
6009 # & ~tb::COLOR_INDEX ] =
6011 if ( $identifier eq '&' && $expecting ) {
6012 $identifier .= $tok;
6019 $id_scan_state = '';
6023 elsif ( $id_scan_state eq 'A' ) { # looking for alpha (after ::)
6025 if ( $tok =~ /^[A-Za-z_]/ ) { # found it
6026 $identifier .= $tok;
6027 $id_scan_state = ':'; # now need ::
6030 elsif ( $tok eq "'" && $allow_tick ) {
6031 $identifier .= $tok;
6032 $id_scan_state = ':'; # now need ::
6035 elsif ( $tok =~ /^[0-9]/ ) { # numeric..see comments above
6036 $identifier .= $tok;
6037 $id_scan_state = ':'; # now need ::
6040 elsif ( ( $identifier =~ /^sub / ) && ( $tok =~ /^\s*$/ ) ) {
6041 $id_scan_state = '(';
6042 $identifier .= $tok;
6044 elsif ( ( $identifier =~ /^sub / ) && ( $tok eq '(' ) ) {
6045 $id_scan_state = ')';
6046 $identifier .= $tok;
6049 $id_scan_state = '';
6054 elsif ( $id_scan_state eq ':' ) { # looking for :: after alpha
6056 if ( $tok eq '::' ) { # got it
6057 $identifier .= $tok;
6058 $id_scan_state = 'A'; # now require alpha
6060 elsif ( $tok =~ /^[A-Za-z_]/ ) { # more alphanumeric is ok here
6061 $identifier .= $tok;
6062 $id_scan_state = ':'; # now need ::
6065 elsif ( $tok =~ /^[0-9]/ ) { # numeric..see comments above
6066 $identifier .= $tok;
6067 $id_scan_state = ':'; # now need ::
6070 elsif ( $tok eq "'" && $allow_tick ) { # tick
6072 if ( $is_keyword{$identifier} ) {
6073 $id_scan_state = ''; # that's all
6077 $identifier .= $tok;
6080 elsif ( ( $identifier =~ /^sub / ) && ( $tok =~ /^\s*$/ ) ) {
6081 $id_scan_state = '(';
6082 $identifier .= $tok;
6084 elsif ( ( $identifier =~ /^sub / ) && ( $tok eq '(' ) ) {
6085 $id_scan_state = ')';
6086 $identifier .= $tok;
6089 $id_scan_state = ''; # that's all
6094 elsif ( $id_scan_state eq '(' ) { # looking for ( of prototype
6096 if ( $tok eq '(' ) { # got it
6097 $identifier .= $tok;
6098 $id_scan_state = ')'; # now find the end of it
6100 elsif ( $tok =~ /^\s*$/ ) { # blank - keep going
6101 $identifier .= $tok;
6104 $id_scan_state = ''; # that's all - no prototype
6109 elsif ( $id_scan_state eq ')' ) { # looking for ) to end
6111 if ( $tok eq ')' ) { # got it
6112 $identifier .= $tok;
6113 $id_scan_state = ''; # all done
6116 elsif ( $tok =~ /^[\s\$\%\\\*\@\&\;]/ ) {
6117 $identifier .= $tok;
6119 else { # probable error in script, but keep going
6120 warning("Unexpected '$tok' while seeking end of prototype\n");
6121 $identifier .= $tok;
6124 else { # can get here due to error in initialization
6125 $id_scan_state = '';
6131 if ( $id_scan_state eq ')' ) {
6132 warning("Hit end of line while seeking ) to end prototype\n");
6135 # once we enter the actual identifier, it may not extend beyond
6136 # the end of the current line
6137 if ( $id_scan_state =~ /^[A\:\(\)]/ ) {
6138 $id_scan_state = '';
6140 if ( $i < 0 ) { $i = 0 }
6147 if ( $identifier =~ /^->/ && $last_nonblank_type eq 'w' ) {
6150 else { $type = 'i' }
6152 elsif ( $identifier eq '->' ) {
6156 ( length($identifier) > 1 )
6158 # In something like '@$=' we have an identifier '@$'
6159 # In something like '$${' we have type '$$' (and only
6160 # part of an identifier)
6161 && !( $identifier =~ /\$$/ && $tok eq '{' )
6162 && ( $identifier !~ /^(sub |package )$/ )
6167 else { $type = 't' }
6169 elsif ($saw_alpha) {
6171 # type 'w' includes anything without leading type info
6172 # ($,%,@,*) including something like abc::def::ghi
6177 } # this can happen on a restart
6182 if ($message) { write_logfile_entry($message) }
6189 TOKENIZER_DEBUG_FLAG_SCAN_ID && do {
6190 my ( $a, $b, $c ) = caller;
6192 "SCANID: called from $a $b $c with tok, i, state, identifier =$tok_begin, $i_begin, $id_scan_state_begin, $identifier_begin\n";
6194 "SCANID: returned with tok, i, state, identifier =$tok, $i, $id_scan_state, $identifier\n";
6196 return ( $i, $tok, $type, $id_scan_state, $identifier );
6201 # saved package and subnames in case prototype is on separate line
6202 my ( $package_saved, $subname_saved );
6206 # do_scan_sub parses a sub name and prototype
6207 # it is called with $i_beg equal to the index of the first nonblank
6208 # token following a 'sub' token.
6210 # TODO: add future error checks to be sure we have a valid
6211 # sub name. For example, 'sub &doit' is wrong. Also, be sure
6212 # a name is given if and only if a non-anonymous sub is
6214 # USES GLOBAL VARS: $current_package, $last_nonblank_token,
6215 # $in_attribute_list, %saw_function_definition,
6219 $input_line, $i, $i_beg,
6220 $tok, $type, $rtokens,
6221 $rtoken_map, $id_scan_state, $max_token_index
6223 $id_scan_state = ""; # normally we get everything in one call
6224 my $subname = undef;
6225 my $package = undef;
6230 my $pos_beg = $rtoken_map->[$i_beg];
6231 pos($input_line) = $pos_beg;
6233 # Look for the sub NAME
6235 $input_line =~ m/\G\s*
6236 ((?:\w*(?:'|::))*) # package - something that ends in :: or '
6237 (\w+) # NAME - required
6244 $package = ( defined($1) && $1 ) ? $1 : $current_package;
6245 $package =~ s/\'/::/g;
6246 if ( $package =~ /^\:/ ) { $package = 'main' . $package }
6247 $package =~ s/::$//;
6248 my $pos = pos($input_line);
6249 my $numc = $pos - $pos_beg;
6250 $tok = 'sub ' . substr( $input_line, $pos_beg, $numc );
6254 # Now look for PROTO ATTRS
6255 # Look for prototype/attributes which are usually on the same
6256 # line as the sub name but which might be on a separate line.
6257 # For example, we might have an anonymous sub with attributes,
6258 # or a prototype on a separate line from its sub name
6260 # NOTE: We only want to parse PROTOTYPES here. If we see anything that
6261 # does not look like a prototype, we assume it is a SIGNATURE and we
6262 # will stop and let the the standard tokenizer handle it. In
6263 # particular, we stop if we see any nested parens, braces, or commas.
6264 my $saw_opening_paren = $input_line =~ /\G\s*\(/;
6266 $input_line =~ m/\G(\s*\([^\)\(\}\{\,]*\))? # PROTO
6267 (\s*:)? # ATTRS leading ':'
6275 # If we also found the sub name on this call then append PROTO.
6276 # This is not necessary but for compatability with previous
6277 # versions when the -csc flag is used:
6278 if ( $match && $proto ) {
6283 # Handle prototype on separate line from subname
6284 if ($subname_saved) {
6285 $package = $package_saved;
6286 $subname = $subname_saved;
6287 $tok = $last_nonblank_token;
6294 # ATTRS: if there are attributes, back up and let the ':' be
6295 # found later by the scanner.
6296 my $pos = pos($input_line);
6298 $pos -= length($attrs);
6301 my $next_nonblank_token = $tok;
6303 # catch case of line with leading ATTR ':' after anonymous sub
6304 if ( $pos == $pos_beg && $tok eq ':' ) {
6306 $in_attribute_list = 1;
6309 # Otherwise, if we found a match we must convert back from
6310 # string position to the pre_token index for continued parsing.
6313 # I don't think an error flag can occur here ..but ?
6315 ( $i, $error ) = inverse_pretoken_map( $i, $pos, $rtoken_map,
6317 if ($error) { warning("Possibly invalid sub\n") }
6319 # check for multiple definitions of a sub
6320 ( $next_nonblank_token, my $i_next ) =
6321 find_next_nonblank_token_on_this_line( $i, $rtokens,
6325 if ( $next_nonblank_token =~ /^(\s*|#)$/ )
6326 { # skip blank or side comment
6327 my ( $rpre_tokens, $rpre_types ) =
6328 peek_ahead_for_n_nonblank_pre_tokens(1);
6329 if ( defined($rpre_tokens) && @{$rpre_tokens} ) {
6330 $next_nonblank_token = $rpre_tokens->[0];
6333 $next_nonblank_token = '}';
6336 $package_saved = "";
6337 $subname_saved = "";
6339 # See what's next...
6340 if ( $next_nonblank_token eq '{' ) {
6343 # Check for multiple definitions of a sub, but
6344 # it is ok to have multiple sub BEGIN, etc,
6345 # so we do not complain if name is all caps
6346 if ( $saw_function_definition{$package}{$subname}
6347 && $subname !~ /^[A-Z]+$/ )
6349 my $lno = $saw_function_definition{$package}{$subname};
6351 "already saw definition of 'sub $subname' in package '$package' at line $lno\n"
6354 $saw_function_definition{$package}{$subname} =
6355 $tokenizer_self->{_last_line_number};
6358 elsif ( $next_nonblank_token eq ';' ) {
6360 elsif ( $next_nonblank_token eq '}' ) {
6363 # ATTRS - if an attribute list follows, remember the name
6364 # of the sub so the next opening brace can be labeled.
6365 # Setting 'statement_type' causes any ':'s to introduce
6367 elsif ( $next_nonblank_token eq ':' ) {
6368 $statement_type = $tok;
6371 # if we stopped before an open paren ...
6372 elsif ( $next_nonblank_token eq '(' ) {
6374 # If we DID NOT see this paren above then it must be on the
6375 # next line so we will set a flag to come back here and see if
6378 # Otherwise, we assume it is a SIGNATURE rather than a
6379 # PROTOTYPE and let the normal tokenizer handle it as a list
6380 if ( !$saw_opening_paren ) {
6381 $id_scan_state = 'sub'; # we must come back to get proto
6382 $package_saved = $package;
6383 $subname_saved = $subname;
6385 $statement_type = $tok;
6387 elsif ($next_nonblank_token) { # EOF technically ok
6389 "expecting ':' or ';' or '{' after definition or declaration of sub '$subname' but saw '$next_nonblank_token'\n"
6392 check_prototype( $proto, $package, $subname );
6395 # no match but line not blank
6398 return ( $i, $tok, $type, $id_scan_state );
6402 #########i###############################################################
6403 # Tokenizer utility routines which may use CONSTANTS but no other GLOBALS
6404 #########################################################################
6406 sub find_next_nonblank_token {
6407 my ( $i, $rtokens, $max_token_index ) = @_;
6409 if ( $i >= $max_token_index ) {
6410 if ( !peeked_ahead() ) {
6413 peek_ahead_for_nonblank_token( $rtokens, $max_token_index );
6416 my $next_nonblank_token = $rtokens->[ ++$i ];
6418 if ( $next_nonblank_token =~ /^\s*$/ ) {
6419 $next_nonblank_token = $rtokens->[ ++$i ];
6421 return ( $next_nonblank_token, $i );
6424 sub numerator_expected {
6426 # this is a filter for a possible numerator, in support of guessing
6427 # for the / pattern delimiter token.
6432 # Note: I am using the convention that variables ending in
6433 # _expected have these 3 possible values.
6434 my ( $i, $rtokens, $max_token_index ) = @_;
6435 my $numerator_expected = 0;
6437 my $next_token = $rtokens->[ $i + 1 ];
6438 if ( $next_token eq '=' ) { $i++; } # handle /=
6439 my ( $next_nonblank_token, $i_next ) =
6440 find_next_nonblank_token( $i, $rtokens, $max_token_index );
6442 if ( $next_nonblank_token =~ /(\(|\$|\w|\.|\@)/ ) {
6443 $numerator_expected = 1;
6447 if ( $next_nonblank_token =~ /^\s*$/ ) {
6448 $numerator_expected = 0;
6451 $numerator_expected = -1;
6454 return $numerator_expected;
6457 sub pattern_expected {
6459 # This is the start of a filter for a possible pattern.
6460 # It looks at the token after a possible pattern and tries to
6461 # determine if that token could end a pattern.
6466 my ( $i, $rtokens, $max_token_index ) = @_;
6469 my $next_token = $rtokens->[ $i + 1 ];
6470 if ( $next_token =~ /^[msixpodualgc]/ ) { $i++; } # skip possible modifier
6471 my ( $next_nonblank_token, $i_next ) =
6472 find_next_nonblank_token( $i, $rtokens, $max_token_index );
6474 # list of tokens which may follow a pattern
6475 # (can probably be expanded)
6476 if ( $next_nonblank_token =~ /(\)|\}|\;|\&\&|\|\||and|or|while|if|unless)/ )
6482 if ( $next_nonblank_token =~ /^\s*$/ ) {
6492 sub find_next_nonblank_token_on_this_line {
6493 my ( $i, $rtokens, $max_token_index ) = @_;
6494 my $next_nonblank_token;
6496 if ( $i < $max_token_index ) {
6497 $next_nonblank_token = $rtokens->[ ++$i ];
6499 if ( $next_nonblank_token =~ /^\s*$/ ) {
6501 if ( $i < $max_token_index ) {
6502 $next_nonblank_token = $rtokens->[ ++$i ];
6507 $next_nonblank_token = "";
6509 return ( $next_nonblank_token, $i );
6512 sub find_angle_operator_termination {
6514 # We are looking at a '<' and want to know if it is an angle operator.
6516 # $i = pretoken index of ending '>' if found, current $i otherwise
6517 # $type = 'Q' if found, '>' otherwise
6518 my ( $input_line, $i_beg, $rtoken_map, $expecting, $max_token_index ) = @_;
6521 pos($input_line) = 1 + $rtoken_map->[$i];
6525 # we just have to find the next '>' if a term is expected
6526 if ( $expecting == TERM ) { $filter = '[\>]' }
6528 # we have to guess if we don't know what is expected
6529 elsif ( $expecting == UNKNOWN ) { $filter = '[\>\;\=\#\|\<]' }
6531 # shouldn't happen - we shouldn't be here if operator is expected
6532 else { warning("Program Bug in find_angle_operator_termination\n") }
6534 # To illustrate what we might be looking at, in case we are
6535 # guessing, here are some examples of valid angle operators
6542 # <jskdfjskdfj* op/* jskdjfjkosvk*> ( glob.t)
6543 # <${PREFIX}*img*.$IMAGE_TYPE>
6544 # <img*.$IMAGE_TYPE>
6545 # <Timg*.$IMAGE_TYPE>
6546 # <$LATEX2HTMLVERSIONS${dd}html[1-9].[0-9].pl>
6548 # Here are some examples of lines which do not have angle operators:
6549 # return unless $self->[2]++ < $#{$self->[1]};
6552 # the following line from dlister.pl caused trouble:
6553 # print'~'x79,"\n",$D<1024?"0.$D":$D>>10,"K, $C files\n\n\n";
6555 # If the '<' starts an angle operator, it must end on this line and
6556 # it must not have certain characters like ';' and '=' in it. I use
6557 # this to limit the testing. This filter should be improved if
6560 if ( $input_line =~ /($filter)/g ) {
6564 # We MAY have found an angle operator termination if we get
6565 # here, but we need to do more to be sure we haven't been
6567 my $pos = pos($input_line);
6569 my $pos_beg = $rtoken_map->[$i];
6570 my $str = substr( $input_line, $pos_beg, ( $pos - $pos_beg ) );
6572 # Reject if the closing '>' follows a '-' as in:
6573 # if ( VERSION < 5.009 && $op-> name eq 'assign' ) { }
6574 if ( $expecting eq UNKNOWN ) {
6575 my $check = substr( $input_line, $pos - 2, 1 );
6576 if ( $check eq '-' ) {
6577 return ( $i, $type );
6581 ######################################debug#####
6582 #write_diagnostics( "ANGLE? :$str\n");
6583 #print "ANGLE: found $1 at pos=$pos str=$str check=$check\n";
6584 ######################################debug#####
6588 inverse_pretoken_map( $i, $pos, $rtoken_map, $max_token_index );
6590 # It may be possible that a quote ends midway in a pretoken.
6591 # If this happens, it may be necessary to split the pretoken.
6594 "Possible tokinization error..please check this line\n");
6595 report_possible_bug();
6598 # Now let's see where we stand....
6599 # OK if math op not possible
6600 if ( $expecting == TERM ) {
6603 # OK if there are no more than 2 pre-tokens inside
6604 # (not possible to write 2 token math between < and >)
6605 # This catches most common cases
6606 elsif ( $i <= $i_beg + 3 ) {
6607 write_diagnostics("ANGLE(1 or 2 tokens): $str\n");
6613 # Let's try a Brace Test: any braces inside must balance
6615 while ( $str =~ /\{/g ) { $br++ }
6616 while ( $str =~ /\}/g ) { $br-- }
6618 while ( $str =~ /\[/g ) { $sb++ }
6619 while ( $str =~ /\]/g ) { $sb-- }
6621 while ( $str =~ /\(/g ) { $pr++ }
6622 while ( $str =~ /\)/g ) { $pr-- }
6624 # if braces do not balance - not angle operator
6625 if ( $br || $sb || $pr ) {
6629 "NOT ANGLE (BRACE={$br ($pr [$sb ):$str\n");
6632 # we should keep doing more checks here...to be continued
6633 # Tentatively accepting this as a valid angle operator.
6634 # There are lots more things that can be checked.
6637 "ANGLE-Guessing yes: $str expecting=$expecting\n");
6638 write_logfile_entry("Guessing angle operator here: $str\n");
6643 # didn't find ending >
6645 if ( $expecting == TERM ) {
6646 warning("No ending > for angle operator\n");
6650 return ( $i, $type );
6653 sub scan_number_do {
6655 # scan a number in any of the formats that Perl accepts
6656 # Underbars (_) are allowed in decimal numbers.
6657 # input parameters -
6658 # $input_line - the string to scan
6659 # $i - pre_token index to start scanning
6660 # $rtoken_map - reference to the pre_token map giving starting
6661 # character position in $input_line of token $i
6662 # output parameters -
6663 # $i - last pre_token index of the number just scanned
6664 # number - the number (characters); or undef if not a number
6666 my ( $input_line, $i, $rtoken_map, $input_type, $max_token_index ) = @_;
6667 my $pos_beg = $rtoken_map->[$i];
6671 my $type = $input_type;
6673 my $first_char = substr( $input_line, $pos_beg, 1 );
6675 # Look for bad starting characters; Shouldn't happen..
6676 if ( $first_char !~ /[\d\.\+\-Ee]/ ) {
6677 warning("Program bug - scan_number given character $first_char\n");
6678 report_definite_bug();
6679 return ( $i, $type, $number );
6682 # handle v-string without leading 'v' character ('Two Dot' rule)
6684 # TODO: v-strings may contain underscores
6685 pos($input_line) = $pos_beg;
6686 if ( $input_line =~ /\G((\d+)?\.\d+(\.\d+)+)/g ) {
6687 $pos = pos($input_line);
6688 my $numc = $pos - $pos_beg;
6689 $number = substr( $input_line, $pos_beg, $numc );
6691 report_v_string($number);
6694 # handle octal, hex, binary
6695 if ( !defined($number) ) {
6696 pos($input_line) = $pos_beg;
6698 /\G[+-]?0(([xX][0-9a-fA-F_]+)|([0-7_]+)|([bB][01_]+))/g )
6700 $pos = pos($input_line);
6701 my $numc = $pos - $pos_beg;
6702 $number = substr( $input_line, $pos_beg, $numc );
6708 if ( !defined($number) ) {
6709 pos($input_line) = $pos_beg;
6711 if ( $input_line =~ /\G([+-]?[\d_]*(\.[\d_]*)?([Ee][+-]?(\d+))?)/g ) {
6712 $pos = pos($input_line);
6714 # watch out for things like 0..40 which would give 0. by this;
6715 if ( ( substr( $input_line, $pos - 1, 1 ) eq '.' )
6716 && ( substr( $input_line, $pos, 1 ) eq '.' ) )
6720 my $numc = $pos - $pos_beg;
6721 $number = substr( $input_line, $pos_beg, $numc );
6726 # filter out non-numbers like e + - . e2 .e3 +e6
6727 # the rule: at least one digit, and any 'e' must be preceded by a digit
6729 $number !~ /\d/ # no digits
6730 || ( $number =~ /^(.*)[eE]/
6731 && $1 !~ /\d/ ) # or no digits before the 'e'
6735 $type = $input_type;
6736 return ( $i, $type, $number );
6739 # Found a number; now we must convert back from character position
6740 # to pre_token index. An error here implies user syntax error.
6741 # An example would be an invalid octal number like '009'.
6744 inverse_pretoken_map( $i, $pos, $rtoken_map, $max_token_index );
6745 if ($error) { warning("Possibly invalid number\n") }
6747 return ( $i, $type, $number );
6750 sub inverse_pretoken_map {
6752 # Starting with the current pre_token index $i, scan forward until
6753 # finding the index of the next pre_token whose position is $pos.
6754 my ( $i, $pos, $rtoken_map, $max_token_index ) = @_;
6757 while ( ++$i <= $max_token_index ) {
6759 if ( $pos <= $rtoken_map->[$i] ) {
6761 # Let the calling routine handle errors in which we do not
6762 # land on a pre-token boundary. It can happen by running
6763 # perltidy on some non-perl scripts, for example.
6764 if ( $pos < $rtoken_map->[$i] ) { $error = 1 }
6769 return ( $i, $error );
6774 # find the target of a here document, if any
6776 # $i - token index of the second < of <<
6777 # ($i must be less than the last token index if this is called)
6778 # output parameters:
6779 # $found_target = 0 didn't find target; =1 found target
6780 # HERE_TARGET - the target string (may be empty string)
6781 # $i - unchanged if not here doc,
6782 # or index of the last token of the here target
6783 # $saw_error - flag noting unbalanced quote on here target
6784 my ( $expecting, $i, $rtokens, $rtoken_map, $max_token_index ) = @_;
6786 my $found_target = 0;
6787 my $here_doc_target = '';
6788 my $here_quote_character = '';
6790 my ( $next_nonblank_token, $i_next_nonblank, $next_token );
6791 $next_token = $rtokens->[ $i + 1 ];
6793 # perl allows a backslash before the target string (heredoc.t)
6795 if ( $next_token eq '\\' ) {
6797 $next_token = $rtokens->[ $i + 2 ];
6800 ( $next_nonblank_token, $i_next_nonblank ) =
6801 find_next_nonblank_token_on_this_line( $i, $rtokens, $max_token_index );
6803 if ( $next_nonblank_token =~ /[\'\"\`]/ ) {
6806 my $quote_depth = 0;
6811 $i, $in_quote, $here_quote_character, $quote_pos, $quote_depth,
6814 = follow_quoted_string( $i_next_nonblank, $in_quote, $rtokens,
6815 $here_quote_character, $quote_pos, $quote_depth, $max_token_index );
6817 if ($in_quote) { # didn't find end of quote, so no target found
6819 if ( $expecting == TERM ) {
6821 "Did not find here-doc string terminator ($here_quote_character) before end of line \n"
6826 else { # found ending quote
6830 foreach my $j ( $i_next_nonblank + 1 .. $i - 1 ) {
6831 $tokj = $rtokens->[$j];
6833 # we have to remove any backslash before the quote character
6834 # so that the here-doc-target exactly matches this string
6838 && $rtokens->[ $j + 1 ] eq $here_quote_character );
6839 $here_doc_target .= $tokj;
6844 elsif ( ( $next_token =~ /^\s*$/ ) and ( $expecting == TERM ) ) {
6846 write_logfile_entry(
6847 "found blank here-target after <<; suggest using \"\"\n");
6850 elsif ( $next_token =~ /^\w/ ) { # simple bareword or integer after <<
6852 my $here_doc_expected;
6853 if ( $expecting == UNKNOWN ) {
6854 $here_doc_expected = guess_if_here_doc($next_token);
6857 $here_doc_expected = 1;
6860 if ($here_doc_expected) {
6862 $here_doc_target = $next_token;
6869 if ( $expecting == TERM ) {
6871 write_logfile_entry("Note: bare here-doc operator <<\n");
6878 # patch to neglect any prepended backslash
6879 if ( $found_target && $backslash ) { $i++ }
6881 return ( $found_target, $here_doc_target, $here_quote_character, $i,
6887 # follow (or continue following) quoted string(s)
6888 # $in_quote return code:
6890 # 1 - still must find end of quote whose target is $quote_character
6891 # 2 - still looking for end of first of two quotes
6893 # Returns updated strings:
6894 # $quoted_string_1 = quoted string seen while in_quote=1
6895 # $quoted_string_2 = quoted string seen while in_quote=2
6897 $i, $in_quote, $quote_character,
6898 $quote_pos, $quote_depth, $quoted_string_1,
6899 $quoted_string_2, $rtokens, $rtoken_map,
6903 my $in_quote_starting = $in_quote;
6906 if ( $in_quote == 2 ) { # two quotes/quoted_string_1s to follow
6909 $i, $in_quote, $quote_character, $quote_pos, $quote_depth,
6912 = follow_quoted_string( $i, $in_quote, $rtokens, $quote_character,
6913 $quote_pos, $quote_depth, $max_token_index );
6914 $quoted_string_2 .= $quoted_string;
6915 if ( $in_quote == 1 ) {
6916 if ( $quote_character =~ /[\{\[\<\(]/ ) { $i++; }
6917 $quote_character = '';
6920 $quoted_string_2 .= "\n";
6924 if ( $in_quote == 1 ) { # one (more) quote to follow
6927 $i, $in_quote, $quote_character, $quote_pos, $quote_depth,
6930 = follow_quoted_string( $ibeg, $in_quote, $rtokens, $quote_character,
6931 $quote_pos, $quote_depth, $max_token_index );
6932 $quoted_string_1 .= $quoted_string;
6933 if ( $in_quote == 1 ) {
6934 $quoted_string_1 .= "\n";
6937 return ( $i, $in_quote, $quote_character, $quote_pos, $quote_depth,
6938 $quoted_string_1, $quoted_string_2 );
6941 sub follow_quoted_string {
6943 # scan for a specific token, skipping escaped characters
6944 # if the quote character is blank, use the first non-blank character
6946 # $rtokens = reference to the array of tokens
6947 # $i = the token index of the first character to search
6948 # $in_quote = number of quoted strings being followed
6949 # $beginning_tok = the starting quote character
6950 # $quote_pos = index to check next for alphanumeric delimiter
6951 # output parameters:
6952 # $i = the token index of the ending quote character
6953 # $in_quote = decremented if found end, unchanged if not
6954 # $beginning_tok = the starting quote character
6955 # $quote_pos = index to check next for alphanumeric delimiter
6956 # $quote_depth = nesting depth, since delimiters '{ ( [ <' can be nested.
6957 # $quoted_string = the text of the quote (without quotation tokens)
6958 my ( $i_beg, $in_quote, $rtokens, $beginning_tok, $quote_pos, $quote_depth,
6961 my ( $tok, $end_tok );
6963 my $quoted_string = "";
6965 TOKENIZER_DEBUG_FLAG_QUOTE && do {
6967 "QUOTE entering with quote_pos = $quote_pos i=$i beginning_tok =$beginning_tok\n";
6970 # get the corresponding end token
6971 if ( $beginning_tok !~ /^\s*$/ ) {
6972 $end_tok = matching_end_token($beginning_tok);
6975 # a blank token means we must find and use the first non-blank one
6977 my $allow_quote_comments = ( $i < 0 ) ? 1 : 0; # i<0 means we saw a <cr>
6979 while ( $i < $max_token_index ) {
6980 $tok = $rtokens->[ ++$i ];
6982 if ( $tok !~ /^\s*$/ ) {
6984 if ( ( $tok eq '#' ) && ($allow_quote_comments) ) {
6985 $i = $max_token_index;
6989 if ( length($tok) > 1 ) {
6990 if ( $quote_pos <= 0 ) { $quote_pos = 1 }
6991 $beginning_tok = substr( $tok, $quote_pos - 1, 1 );
6994 $beginning_tok = $tok;
6997 $end_tok = matching_end_token($beginning_tok);
7003 $allow_quote_comments = 1;
7008 # There are two different loops which search for the ending quote
7009 # character. In the rare case of an alphanumeric quote delimiter, we
7010 # have to look through alphanumeric tokens character-by-character, since
7011 # the pre-tokenization process combines multiple alphanumeric
7012 # characters, whereas for a non-alphanumeric delimiter, only tokens of
7013 # length 1 can match.
7015 ###################################################################
7016 # Case 1 (rare): loop for case of alphanumeric quote delimiter..
7017 # "quote_pos" is the position the current word to begin searching
7018 ###################################################################
7019 if ( $beginning_tok =~ /\w/ ) {
7021 # Note this because it is not recommended practice except
7022 # for obfuscated perl contests
7023 if ( $in_quote == 1 ) {
7024 write_logfile_entry(
7025 "Note: alphanumeric quote delimiter ($beginning_tok) \n");
7028 while ( $i < $max_token_index ) {
7030 if ( $quote_pos == 0 || ( $i < 0 ) ) {
7031 $tok = $rtokens->[ ++$i ];
7033 if ( $tok eq '\\' ) {
7035 # retain backslash unless it hides the end token
7036 $quoted_string .= $tok
7037 unless $rtokens->[ $i + 1 ] eq $end_tok;
7039 last if ( $i >= $max_token_index );
7040 $tok = $rtokens->[ ++$i ];
7043 my $old_pos = $quote_pos;
7045 unless ( defined($tok) && defined($end_tok) && defined($quote_pos) )
7049 $quote_pos = 1 + index( $tok, $end_tok, $quote_pos );
7051 if ( $quote_pos > 0 ) {
7054 substr( $tok, $old_pos, $quote_pos - $old_pos - 1 );
7058 if ( $quote_depth == 0 ) {
7064 $quoted_string .= substr( $tok, $old_pos );
7069 ########################################################################
7070 # Case 2 (normal): loop for case of a non-alphanumeric quote delimiter..
7071 ########################################################################
7074 while ( $i < $max_token_index ) {
7075 $tok = $rtokens->[ ++$i ];
7077 if ( $tok eq $end_tok ) {
7080 if ( $quote_depth == 0 ) {
7085 elsif ( $tok eq $beginning_tok ) {
7088 elsif ( $tok eq '\\' ) {
7090 # retain backslash unless it hides the beginning or end token
7091 $tok = $rtokens->[ ++$i ];
7092 $quoted_string .= '\\'
7093 unless ( $tok eq $end_tok || $tok eq $beginning_tok );
7095 $quoted_string .= $tok;
7098 if ( $i > $max_token_index ) { $i = $max_token_index }
7099 return ( $i, $in_quote, $beginning_tok, $quote_pos, $quote_depth,
7103 sub indicate_error {
7104 my ( $msg, $line_number, $input_line, $pos, $carrat ) = @_;
7105 interrupt_logfile();
7107 write_error_indicator_pair( $line_number, $input_line, $pos, $carrat );
7112 sub write_error_indicator_pair {
7113 my ( $line_number, $input_line, $pos, $carrat ) = @_;
7114 my ( $offset, $numbered_line, $underline ) =
7115 make_numbered_line( $line_number, $input_line, $pos );
7116 $underline = write_on_underline( $underline, $pos - $offset, $carrat );
7117 warning( $numbered_line . "\n" );
7118 $underline =~ s/\s*$//;
7119 warning( $underline . "\n" );
7123 sub make_numbered_line {
7125 # Given an input line, its line number, and a character position of
7126 # interest, create a string not longer than 80 characters of the form
7127 # $lineno: sub_string
7128 # such that the sub_string of $str contains the position of interest
7130 # Here is an example of what we want, in this case we add trailing
7131 # '...' because the line is long.
7133 # 2: (One of QAML 2.0's authors is a member of the World Wide Web Con ...
7135 # Here is another example, this time in which we used leading '...'
7136 # because of excessive length:
7138 # 2: ... er of the World Wide Web Consortium's
7140 # input parameters are:
7141 # $lineno = line number
7142 # $str = the text of the line
7143 # $pos = position of interest (the error) : 0 = first character
7146 # - $offset = an offset which corrects the position in case we only
7147 # display part of a line, such that $pos-$offset is the effective
7148 # position from the start of the displayed line.
7149 # - $numbered_line = the numbered line as above,
7150 # - $underline = a blank 'underline' which is all spaces with the same
7151 # number of characters as the numbered line.
7153 my ( $lineno, $str, $pos ) = @_;
7154 my $offset = ( $pos < 60 ) ? 0 : $pos - 40;
7155 my $excess = length($str) - $offset - 68;
7156 my $numc = ( $excess > 0 ) ? 68 : undef;
7158 if ( defined($numc) ) {
7159 if ( $offset == 0 ) {
7160 $str = substr( $str, $offset, $numc - 4 ) . " ...";
7163 $str = "... " . substr( $str, $offset + 4, $numc - 4 ) . " ...";
7168 if ( $offset == 0 ) {
7171 $str = "... " . substr( $str, $offset + 4 );
7175 my $numbered_line = sprintf( "%d: ", $lineno );
7176 $offset -= length($numbered_line);
7177 $numbered_line .= $str;
7178 my $underline = " " x length($numbered_line);
7179 return ( $offset, $numbered_line, $underline );
7182 sub write_on_underline {
7184 # The "underline" is a string that shows where an error is; it starts
7185 # out as a string of blanks with the same length as the numbered line of
7186 # code above it, and we have to add marking to show where an error is.
7187 # In the example below, we want to write the string '--^' just below
7188 # the line of bad code:
7190 # 2: (One of QAML 2.0's authors is a member of the World Wide Web Con ...
7192 # We are given the current underline string, plus a position and a
7193 # string to write on it.
7195 # In the above example, there will be 2 calls to do this:
7196 # First call: $pos=19, pos_chr=^
7197 # Second call: $pos=16, pos_chr=---
7199 # This is a trivial thing to do with substr, but there is some
7202 my ( $underline, $pos, $pos_chr ) = @_;
7204 # check for error..shouldn't happen
7205 unless ( ( $pos >= 0 ) && ( $pos <= length($underline) ) ) {
7208 my $excess = length($pos_chr) + $pos - length($underline);
7209 if ( $excess > 0 ) {
7210 $pos_chr = substr( $pos_chr, 0, length($pos_chr) - $excess );
7212 substr( $underline, $pos, length($pos_chr) ) = $pos_chr;
7213 return ($underline);
7218 # Break a string, $str, into a sequence of preliminary tokens. We
7219 # are interested in these types of tokens:
7220 # words (type='w'), example: 'max_tokens_wanted'
7221 # digits (type = 'd'), example: '0755'
7222 # whitespace (type = 'b'), example: ' '
7223 # any other single character (i.e. punct; type = the character itself).
7224 # We cannot do better than this yet because we might be in a quoted
7225 # string or pattern. Caller sets $max_tokens_wanted to 0 to get all
7227 my ( $str, $max_tokens_wanted ) = @_;
7229 # we return references to these 3 arrays:
7230 my @tokens = (); # array of the tokens themselves
7231 my @token_map = (0); # string position of start of each token
7232 my @type = (); # 'b'=whitespace, 'd'=digits, 'w'=alpha, or punct
7237 if ( $str =~ /\G(\s+)/gc ) { push @type, 'b'; }
7240 # note that this must come before words!
7241 elsif ( $str =~ /\G(\d+)/gc ) { push @type, 'd'; }
7244 elsif ( $str =~ /\G(\w+)/gc ) { push @type, 'w'; }
7246 # single-character punctuation
7247 elsif ( $str =~ /\G(\W)/gc ) { push @type, $1; }
7251 return ( \@tokens, \@token_map, \@type );
7255 push @token_map, pos($str);
7257 } while ( --$max_tokens_wanted != 0 );
7259 return ( \@tokens, \@token_map, \@type );
7264 # this is an old debug routine
7265 # not called, but saved for reference
7266 my ( $rtokens, $rtoken_map ) = @_;
7267 my $num = scalar( @{$rtokens} );
7269 foreach my $i ( 0 .. $num - 1 ) {
7270 my $len = length( $rtokens->[$i] );
7271 print STDOUT "$i:$len:$rtoken_map->[$i]:$rtokens->[$i]:\n";
7277 my %matching_end_token;
7280 %matching_end_token = (
7288 sub matching_end_token {
7290 # return closing character for a pattern
7291 my $beginning_token = shift;
7292 if ( $matching_end_token{$beginning_token} ) {
7293 return $matching_end_token{$beginning_token};
7295 return ($beginning_token);
7299 sub dump_token_types {
7300 my ( $class, $fh ) = @_;
7302 # This should be the latest list of token types in use
7303 # adding NEW_TOKENS: add a comment here
7304 print $fh <<'END_OF_LIST';
7306 Here is a list of the token types currently used for lines of type 'CODE'.
7307 For the following tokens, the "type" of a token is just the token itself.
7309 .. :: << >> ** && .. || // -> => += -= .= %= &= |= ^= *= <>
7310 ( ) <= >= == =~ !~ != ++ -- /= x=
7311 ... **= <<= >>= &&= ||= //= <=>
7312 , + - / * | % ! x ~ = \ ? : . < > ^ &
7314 The following additional token types are defined:
7317 b blank (white space)
7318 { indent: opening structural curly brace or square bracket or paren
7319 (code block, anonymous hash reference, or anonymous array reference)
7320 } outdent: right structural curly brace or square bracket or paren
7321 [ left non-structural square bracket (enclosing an array index)
7322 ] right non-structural square bracket
7323 ( left non-structural paren (all but a list right of an =)
7324 ) right non-structural paren
7325 L left non-structural curly brace (enclosing a key)
7326 R right non-structural curly brace
7327 ; terminal semicolon
7328 f indicates a semicolon in a "for" statement
7329 h here_doc operator <<
7331 Q indicates a quote or pattern
7332 q indicates a qw quote block
7334 C user-defined constant or constant function (with void prototype = ())
7335 U user-defined function taking parameters
7336 G user-defined function taking block parameter (like grep/map/eval)
7337 M (unused, but reserved for subroutine definition name)
7338 P (unused, but -html uses it to label pod text)
7339 t type indicater such as %,$,@,*,&,sub
7340 w bare word (perhaps a subroutine call)
7341 i identifier of some type (with leading %, $, @, *, &, sub, -> )
7344 F a file test operator (like -e)
7346 Z identifier in indirect object slot: may be file handle, object
7347 J LABEL: code block label
7348 j LABEL after next, last, redo, goto
7351 pp pre-increment operator ++
7352 mm pre-decrement operator --
7353 A : used as attribute separator
7355 Here are the '_line_type' codes used internally:
7356 SYSTEM - system-specific code before hash-bang line
7357 CODE - line of perl code (including comments)
7358 POD_START - line starting pod, such as '=head'
7359 POD - pod documentation text
7360 POD_END - last line of pod section, '=cut'
7361 HERE - text of here-document
7362 HERE_END - last line of here-doc (target word)
7363 FORMAT - format section
7364 FORMAT_END - last line of format section, '.'
7365 DATA_START - __DATA__ line
7366 DATA - unidentified text following __DATA__
7367 END_START - __END__ line
7368 END - unidentified text following __END__
7369 ERROR - we are in big trouble, probably not a perl script
7377 # These names are used in error messages
7378 @opening_brace_names = qw# '{' '[' '(' '?' #;
7379 @closing_brace_names = qw# '}' ']' ')' ':' #;
7384 .. :: << >> ** && .. || // -> => += -= .= %= &= |= ^= *= <>
7385 <= >= == =~ !~ != ++ -- /= x= ~~ ~. |. &. ^.
7387 @is_digraph{@digraphs} = (1) x scalar(@digraphs);
7389 my @trigraphs = qw( ... **= <<= >>= &&= ||= //= <=> !~~ &.= |.= ^.= <<~);
7390 @is_trigraph{@trigraphs} = (1) x scalar(@trigraphs);
7392 my @tetragraphs = qw( <<>> );
7393 @is_tetragraph{@tetragraphs} = (1) x scalar(@tetragraphs);
7395 # make a hash of all valid token types for self-checking the tokenizer
7396 # (adding NEW_TOKENS : select a new character and add to this list)
7397 my @valid_token_types = qw#
7398 A b C G L R f h Q k t w i q n p m F pp mm U j J Y Z v
7399 { } ( ) [ ] ; + - / * | % ! x ~ = \ ? : . < > ^ &
7401 push( @valid_token_types, @digraphs );
7402 push( @valid_token_types, @trigraphs );
7403 push( @valid_token_types, @tetragraphs );
7404 push( @valid_token_types, ( '#', ',', 'CORE::' ) );
7405 @is_valid_token_type{@valid_token_types} = (1) x scalar(@valid_token_types);
7407 # a list of file test letters, as in -e (Table 3-4 of 'camel 3')
7408 my @file_test_operators =
7409 qw( A B C M O R S T W X b c d e f g k l o p r s t u w x z);
7410 @is_file_test_operator{@file_test_operators} =
7411 (1) x scalar(@file_test_operators);
7413 # these functions have prototypes of the form (&), so when they are
7414 # followed by a block, that block MAY BE followed by an operator.
7415 # Smartmatch operator ~~ may be followed by anonymous hash or array ref
7417 @is_block_operator{@q} = (1) x scalar(@q);
7419 # these functions allow an identifier in the indirect object slot
7420 @q = qw( print printf sort exec system say);
7421 @is_indirect_object_taker{@q} = (1) x scalar(@q);
7423 # These tokens may precede a code block
7424 # patched for SWITCH/CASE/CATCH. Actually these could be removed
7425 # now and we could let the extended-syntax coding handle them
7427 qw( BEGIN END CHECK INIT AUTOLOAD DESTROY UNITCHECK continue if elsif else
7428 unless do while until eval for foreach map grep sort
7429 switch case given when catch try finally);
7430 @is_code_block_token{@q} = (1) x scalar(@q);
7432 # I'll build the list of keywords incrementally
7435 # keywords and tokens after which a value or pattern is expected,
7436 # but not an operator. In other words, these should consume terms
7437 # to their right, or at least they are not expected to be followed
7438 # immediately by operators.
7439 my @value_requestor = qw(
7662 # patched above for SWITCH/CASE given/when err say
7663 # 'err' is a fairly safe addition.
7664 # TODO: 'default' still needed if appropriate
7665 # 'use feature' seen, but perltidy works ok without it.
7666 # Concerned that 'default' could break code.
7667 push( @Keywords, @value_requestor );
7669 # These are treated the same but are not keywords:
7674 push( @value_requestor, @extra_vr );
7676 @expecting_term_token{@value_requestor} = (1) x scalar(@value_requestor);
7678 # this list contains keywords which do not look for arguments,
7679 # so that they might be followed by an operator, or at least
7681 my @operator_requestor = qw(
7705 push( @Keywords, @operator_requestor );
7707 # These are treated the same but are not considered keywords:
7714 push( @operator_requestor, @extra_or );
7716 @expecting_operator_token{@operator_requestor} =
7717 (1) x scalar(@operator_requestor);
7719 # these token TYPES expect trailing operator but not a term
7720 # note: ++ and -- are post-increment and decrement, 'C' = constant
7721 my @operator_requestor_types = qw( ++ -- C <> q );
7722 @expecting_operator_types{@operator_requestor_types} =
7723 (1) x scalar(@operator_requestor_types);
7725 # these token TYPES consume values (terms)
7726 # note: pp and mm are pre-increment and decrement
7727 # f=semicolon in for, F=file test operator
7728 my @value_requestor_type = qw#
7729 L { ( [ ~ !~ =~ ; . .. ... A : && ! || // = + - x
7730 **= += -= .= /= *= %= x= &= |= ^= <<= >>= &&= ||= //=
7731 <= >= == != => \ > < % * / ? & | ** <=> ~~ !~~
7732 f F pp mm Y p m U J G j >> << ^ t
7733 ~. ^. |. &. ^.= |.= &.=
7735 push( @value_requestor_type, ',' )
7736 ; # (perl doesn't like a ',' in a qw block)
7737 @expecting_term_types{@value_requestor_type} =
7738 (1) x scalar(@value_requestor_type);
7740 # Note: the following valid token types are not assigned here to
7741 # hashes requesting to be followed by values or terms, but are
7742 # instead currently hard-coded into sub operator_expected:
7743 # ) -> :: Q R Z ] b h i k n v w } #
7745 # For simple syntax checking, it is nice to have a list of operators which
7746 # will really be unhappy if not followed by a term. This includes most
7748 %really_want_term = %expecting_term_types;
7750 # with these exceptions...
7751 delete $really_want_term{'U'}; # user sub, depends on prototype
7752 delete $really_want_term{'F'}; # file test works on $_ if no following term
7753 delete $really_want_term{'Y'}; # indirect object, too risky to check syntax;
7756 @q = qw(q qq qw qx qr s y tr m);
7757 @is_q_qq_qw_qx_qr_s_y_tr_m{@q} = (1) x scalar(@q);
7759 # These keywords are handled specially in the tokenizer code:
7760 my @special_keywords = qw(
7776 push( @Keywords, @special_keywords );
7778 # Keywords after which list formatting may be used
7779 # WARNING: do not include |map|grep|eval or perl may die on
7780 # syntax errors (map1.t).
7781 my @keyword_taking_list = qw(
7855 @is_keyword_taking_list{@keyword_taking_list} =
7856 (1) x scalar(@keyword_taking_list);
7858 # perl functions which may be unary operators
7859 my @keyword_taking_optional_args = qw(
7869 @is_keyword_taking_optional_args{@keyword_taking_optional_args} =
7870 (1) x scalar(@keyword_taking_optional_args);
7872 # These are not used in any way yet
7873 # my @unused_keywords = qw(
7879 # The list of keywords was originally extracted from function 'keyword' in
7880 # perl file toke.c version 5.005.03, using this utility, plus a
7881 # little editing: (file getkwd.pl):
7882 # while (<>) { while (/\"(.*)\"/g) { print "$1\n"; } }
7883 # Add 'get' prefix where necessary, then split into the above lists.
7884 # This list should be updated as necessary.
7885 # The list should not contain these special variables:
7886 # ARGV DATA ENV SIG STDERR STDIN STDOUT
7889 @is_keyword{@Keywords} = (1) x scalar(@Keywords);