.\" Automatically generated by Pod::Man 4.10 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "PPI::Tokenizer 3pm" .TH PPI::Tokenizer 3pm "2019-07-21" "perl v5.28.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" PPI::Tokenizer \- The Perl Document Tokenizer .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 4 \& # Create a tokenizer for a file, array or string \& $Tokenizer = PPI::Tokenizer\->new( \*(Aqfilename.pl\*(Aq ); \& $Tokenizer = PPI::Tokenizer\->new( \e@lines ); \& $Tokenizer = PPI::Tokenizer\->new( \e$source ); \& \& # Return all the tokens for the document \& my $tokens = $Tokenizer\->all_tokens; \& \& # Or we can use it as an iterator \& while ( my $Token = $Tokenizer\->get_token ) { \& print "Found token \*(Aq$Token\*(Aq\en"; \& } \& \& # If we REALLY need to manually nudge the cursor, you \& # can do that to (The lexer needs this ability to do rollbacks) \& $is_incremented = $Tokenizer\->increment_cursor; \& $is_decremented = $Tokenizer\->decrement_cursor; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" PPI::Tokenizer is the class that provides Tokenizer objects for use in breaking strings of Perl source code into Tokens. .PP By the time you are reading this, you probably need to know a little about the difference between how perl parses Perl \*(L"code\*(R" and how \s-1PPI\s0 parsers Perl \*(L"documents\*(R". .PP \&\*(L"perl\*(R" itself (the interpreter) uses a heavily modified lex specification to specify its parsing logic, maintains several types of state as it goes, and incrementally tokenizes, lexes \s-1AND EXECUTES\s0 at the same time. .PP In fact, it is provably impossible to use perl's parsing method without simultaneously executing code. A formal mathematical proof has been published demonstrating the method. .PP This is where the truism \*(L"Only perl can parse Perl\*(R" comes from. .PP \&\s-1PPI\s0 uses a completely different approach by abandoning the (impossible) ability to parse Perl the same way that the interpreter does, and instead parsing the source as a document, using a document structure independently derived from the Perl documentation and approximating the perl interpreter interpretation as closely as possible. .PP It was touch and go for a long time whether we could get it close enough, but in the end it turned out that it could be done. .PP In this approach, the tokenizer \f(CW\*(C`PPI::Tokenizer\*(C'\fR is implemented separately from the lexer PPI::Lexer. .PP The job of \f(CW\*(C`PPI::Tokenizer\*(C'\fR is to take pure source as a string and break it up into a stream/set of tokens, and contains most of the \*(L"black magic\*(R" used in \s-1PPI.\s0 By comparison, the lexer implements a relatively straight forward tree structure, and has an implementation that is uncomplicated (compared to the insanity in the tokenizer at least). .PP The Tokenizer uses an immense amount of heuristics, guessing and cruft, supported by a very \fB\s-1VERY\s0\fR flexible internal \s-1API,\s0 but fortunately it was possible to largely encapsulate the black magic, so there is not a lot that gets exposed to people using the \f(CW\*(C`PPI::Tokenizer\*(C'\fR itself. .SH "METHODS" .IX Header "METHODS" Despite the incredible complexity, the Tokenizer itself only exposes a relatively small number of methods, with most of the complexity implemented in private methods. .ie n .SS "new $file | \e@lines | \e$source" .el .SS "new \f(CW$file\fP | \e@lines | \e$source" .IX Subsection "new $file | @lines | $source" The main \f(CW\*(C`new\*(C'\fR constructor creates a new Tokenizer object. These objects have no configuration parameters, and can only be used once, to tokenize a single perl source file. .PP It takes as argument either a normal scalar containing source code, a reference to a scalar containing source code, or a reference to an \&\s-1ARRAY\s0 containing newline-terminated lines of source code. .PP Returns a new \f(CW\*(C`PPI::Tokenizer\*(C'\fR object on success, or throws a PPI::Exception exception on error. .SS "get_token" .IX Subsection "get_token" When using the PPI::Tokenizer object as an iterator, the \f(CW\*(C`get_token\*(C'\fR method is the primary method that is used. It increments the cursor and returns the next Token in the output array. .PP The actual parsing of the file is done only as-needed, and a line at a time. When \f(CW\*(C`get_token\*(C'\fR hits the end of the token array, it will cause the parser to pull in the next line and parse it, continuing as needed until there are more tokens on the output array that get_token can then return. .PP This means that a number of Tokenizer objects can be created, and won't consume significant \s-1CPU\s0 until you actually begin to pull tokens from it. .PP Return a PPI::Token object on success, \f(CW0\fR if the Tokenizer had reached the end of the file, or \f(CW\*(C`undef\*(C'\fR on error. .SS "all_tokens" .IX Subsection "all_tokens" When not being used as an iterator, the \f(CW\*(C`all_tokens\*(C'\fR method tells the Tokenizer to parse the entire file and return all of the tokens in a single \s-1ARRAY\s0 reference. .PP It should be noted that \f(CW\*(C`all_tokens\*(C'\fR does \fB\s-1NOT\s0\fR interfere with the use of the Tokenizer object as an iterator (does not modify the token cursor) and use of the two different mechanisms can be mixed safely. .PP Returns a reference to an \s-1ARRAY\s0 of PPI::Token objects on success or throws an exception on error. .SS "increment_cursor" .IX Subsection "increment_cursor" Although exposed as a public method, \f(CW\*(C`increment_cursor\*(C'\fR is implemented for expert use only, when writing lexers or other components that work directly on token streams. .PP It manually increments the token cursor forward through the file, in effect \&\*(L"skipping\*(R" the next token. .PP Return true if the cursor is incremented, \f(CW0\fR if already at the end of the file, or \f(CW\*(C`undef\*(C'\fR on error. .SS "decrement_cursor" .IX Subsection "decrement_cursor" Although exposed as a public method, \f(CW\*(C`decrement_cursor\*(C'\fR is implemented for expert use only, when writing lexers or other components that work directly on token streams. .PP It manually decrements the token cursor backwards through the file, in effect \*(L"rolling back\*(R" the token stream. And indeed that is what it is primarily intended for, when the component that is consuming the token stream needs to implement some sort of \*(L"roll back\*(R" feature in its use of the token stream. .PP Return true if the cursor is decremented, \f(CW0\fR if already at the beginning of the file, or \f(CW\*(C`undef\*(C'\fR on error. .SH "NOTES" .IX Header "NOTES" .SS "How the Tokenizer Works" .IX Subsection "How the Tokenizer Works" Understanding the Tokenizer is not for the faint-hearted. It is by far the most complex and twisty piece of perl I've ever written that is actually still built properly and isn't a terrible spaghetti-like mess. In fact, you probably want to skip this section. .PP But if you really want to understand, well then here goes. .SS "Source Input and Clean Up" .IX Subsection "Source Input and Clean Up" The Tokenizer starts by taking source in a variety of forms, sucking it all in and merging into one big string, and doing our own internal line split, using a \*(L"universal line separator\*(R" which allows the Tokenizer to take source for any platform (and even supports a few known types of broken newlines caused by mixed mac/pc/*nix editor screw ups). .PP The resulting array of lines is used to feed the tokenizer, and is also accessed directly by the heredoc-logic to do the line-oriented part of here-doc support. .SS "Doing Things the Old Fashioned Way" .IX Subsection "Doing Things the Old Fashioned Way" Due to the complexity of perl, and after 2 previously aborted parser attempts, in the end the tokenizer was fashioned around a line-buffered character-by-character method. .PP That is, the Tokenizer pulls and holds a line at a time into a line buffer, and then iterates a cursor along it. At each cursor position, a method is called in whatever token class we are currently in, which will examine the character at the current position, and handle it. .PP As the handler methods in the various token classes are called, they build up an output token array for the source code. .PP Various parts of the Tokenizer use look-ahead, arbitrary-distance look-behind (although currently the maximum is three significant tokens), or both, and various other heuristic guesses. .PP I've been told it is officially termed a \fI\*(L"backtracking parser with infinite lookaheads\*(R"\fR. .SS "State Variables" .IX Subsection "State Variables" Aside from the current line and the character cursor, the Tokenizer maintains a number of different state variables. .IP "Current Class" 4 .IX Item "Current Class" The Tokenizer maintains the current token class at all times. Much of the time is just going to be the \*(L"Whitespace\*(R" class, which is what the base of a document is. As the tokenizer executes the various character handlers, the class changes a lot as it moves a long. In fact, in some instances, the character handler may not handle the character directly itself, but rather change the \*(L"current class\*(R" and then hand off to the character handler for the new class. .Sp Because of this, and some other things I'll deal with later, the number of times the character handlers are called does not in fact have a direct relationship to the number of actual characters in the document. .IP "Current Zone" 4 .IX Item "Current Zone" Rather than create a class stack to allow for infinitely nested layers of classes, the Tokenizer recognises just a single layer. .Sp To put it a different way, in various parts of the file, the Tokenizer will recognise different \*(L"base\*(R" or \*(L"substrate\*(R" classes. When a Token such as a comment or a number is finalised by the tokenizer, it \*(L"falls back\*(R" to the base state. .Sp This allows proper tokenization of special areas such as _\|_DATA_\|_ and _\|_END_\|_ blocks, which also contain things like comments and \s-1POD,\s0 without allowing the creation of any significant Tokens inside these areas. .Sp For the main part of a document we use PPI::Token::Whitespace for this, with the idea being that code is \*(L"floating in a sea of whitespace\*(R". .IP "Current Token" 4 .IX Item "Current Token" The final main state variable is the \*(L"current token\*(R". This is the Token that is currently being built by the Tokenizer. For certain types, it can be manipulated and morphed and change class quite a bit while being assembled, as the Tokenizer's understanding of the token content changes. .Sp When the Tokenizer is confident that it has seen the end of the Token, it will be \*(L"finalized\*(R", which adds it to the output token array and resets the current class to that of the zone that we are currently in. .Sp I should also note at this point that the \*(L"current token\*(R" variable is optional. The Tokenizer is capable of knowing what class it is currently set to, without actually having accumulated any characters in the Token. .SS "Making It Faster" .IX Subsection "Making It Faster" As I'm sure you can imagine, calling several different methods for each character and running regexes and other complex heuristics made the first fully working version of the tokenizer extremely slow. .PP During testing, I created a metric to measure parsing speed called \&\s-1LPGC,\s0 or \*(L"lines per gigacycle\*(R" . A gigacycle is simple a billion \s-1CPU\s0 cycles on a typical single-core \s-1CPU,\s0 and so a Tokenizer running at \&\*(L"1000 lines per gigacycle\*(R" should generate around 1200 lines of tokenized code when running on a 1200 MHz processor. .PP The first working version of the tokenizer ran at only 350 \s-1LPGC,\s0 so to tokenize a typical large module such as ExtUtils::MakeMaker took 10\-15 seconds. This sluggishness made it unpractical for many uses. .PP So in the current parser, there are multiple layers of optimisation very carefully built in to the basic. This has brought the tokenizer up to a more reasonable 1000 \s-1LPGC,\s0 at the expense of making the code quite a bit twistier. .SS "Making It Faster \- Whole Line Classification" .IX Subsection "Making It Faster - Whole Line Classification" The first step in the optimisation process was to add a hew handler to enable several of the more basic classes (whitespace, comments) to be able to be parsed a line at a time. At the start of each line, a special optional handler (only supported by a few classes) is called to check and see if the entire line can be parsed in one go. .PP This is used mainly to handle things like \s-1POD,\s0 comments, empty lines, and a few other minor special cases. .SS "Making It Faster \- Inlining" .IX Subsection "Making It Faster - Inlining" The second stage of the optimisation involved inlining a small number of critical methods that were repeated an extremely high number of times. Profiling suggested that there were about 1,000,000 individual method calls per gigacycle, and by cutting these by two thirds a significant speed improvement was gained, in the order of about 50%. .PP You may notice that many methods in the \f(CW\*(C`PPI::Tokenizer\*(C'\fR code look very nested and long hand. This is primarily due to this inlining. .PP At around this time, some statistics code that existed in the early versions of the parser was also removed, as it was determined that it was consuming around 15% of the \s-1CPU\s0 for the entire parser, while making the core more complicated. .PP A judgment call was made that with the difficulties likely to be encountered with future planned enhancements, and given the relatively high cost involved, the statistics features would be removed from the Tokenizer. .SS "Making It Faster \- Quote Engine" .IX Subsection "Making It Faster - Quote Engine" Once inlining had reached diminishing returns, it became obvious from the profiling results that a huge amount of time was being spent stepping a char at a time though long, simple and \*(L"syntactically boring\*(R" code such as comments and strings. .PP The existing regex engine was expanded to also encompass quotes and other quote-like things, and a special abstract base class was added that provided a number of specialised parsing methods that would \*(L"scan ahead\*(R", looking out ahead to find the end of a string, and updating the cursor to leave it in a valid position for the next call. .PP This is also the point at which the number of character handler calls began to greatly differ from the number of characters. But it has been done in a way that allows the parser to retain the power of the original version at the critical points, while skipping through the \*(L"boring bits\*(R" as needed for additional speed. .PP The addition of this feature allowed the tokenizer to exceed 1000 \s-1LPGC\s0 for the first time. .ie n .SS "Making It Faster \- The ""Complete"" Mechanism" .el .SS "Making It Faster \- The ``Complete'' Mechanism" .IX Subsection "Making It Faster - The Complete Mechanism" As it became evident that great speed increases were available by using this \*(L"skipping ahead\*(R" mechanism, a new handler method was added that explicitly handles the parsing of an entire token, where the structure of the token is relatively simple. Tokens such as symbols fit this case, as once we are passed the initial sigil and word char, we know that we can skip ahead and \*(L"complete\*(R" the rest of the token much more easily. .PP A number of these have been added for most or possibly all of the common cases, with most of these \*(L"complete\*(R" handlers implemented using regular expressions. .PP In fact, so many have been added that at this point, you could arguably reclassify the tokenizer as a \*(L"hybrid regex, char\-by=char heuristic tokenizer\*(R". More tokens are now consumed in \*(L"complete\*(R" methods in a typical program than are handled by the normal char-by-char methods. .PP Many of the these complete-handlers were implemented during the writing of the Lexer, and this has allowed the full parser to maintain around 1000 \s-1LPGC\s0 despite the increasing weight of the Lexer. .SS "Making It Faster \- Porting To C (In Progress)" .IX Subsection "Making It Faster - Porting To C (In Progress)" While it would be extraordinarily difficult to port all of the Tokenizer to C, work has started on a \s-1PPI::XS\s0 \*(L"accelerator\*(R" package which acts as a separate and automatically-detected add-on to the main \s-1PPI\s0 package. .PP \&\s-1PPI::XS\s0 implements faster versions of a variety of functions scattered over the entire \s-1PPI\s0 codebase, from the Tokenizer Core, Quote Engine, and various other places, and implements them identically in \s-1XS/C.\s0 .PP In particular, the skip-ahead methods from the Quote Engine would appear to be extremely amenable to being done in C, and a number of other functions could be cherry-picked one at a time and implemented in C. .PP Each method is heavily tested to ensure that the functionality is identical, and a versioning mechanism is included to ensure that if a function gets out of sync, \s-1PPI::XS\s0 will degrade gracefully and just not replace that single method. .SH "TO DO" .IX Header "TO DO" \&\- Add an option to reset or seek the token stream... .PP \&\- Implement more Tokenizer functions in \s-1PPI::XS\s0 .SH "SUPPORT" .IX Header "SUPPORT" See the support section in the main module. .SH "AUTHOR" .IX Header "AUTHOR" Adam Kennedy .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright 2001 \- 2011 Adam Kennedy. .PP This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. .PP The full text of the license can be found in the \&\s-1LICENSE\s0 file included with this module.