This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fixed repeated words
[perl5.git] / pod / perlreguts.pod
index 4ee2be1..ec1c243 100644 (file)
@@ -12,14 +12,15 @@ author's experience, comments in the source code, other papers on the
 regex engine, feedback on the perl5-porters mail list, and no doubt other
 places as well.
 
-B<WARNING!> It should be clearly understood that this document
-represents the state of the regex engine as the author understands it at
-the time of writing. It is B<NOT> an API definition; it is purely an
-internals guide for those who want to hack the regex engine, or
-understand how the regex engine works. Readers of this document are
-expected to understand perl's regex syntax and its usage in detail. If
-you want to learn about the basics of Perl's regular expressions, see
-L<perlre>.
+B<NOTICE!> It should be clearly understood that the behavior and
+structures discussed in this represents the state of the engine as the
+author understood it at the time of writing. It is B<NOT> an API
+definition, it is purely an internals guide for those who want to hack
+the regex engine, or understand how the regex engine works. Readers of
+this document are expected to understand perl's regex syntax and its
+usage in detail. If you want to learn about the basics of Perl's
+regular expressions, see L<perlre>. And if you want to replace the
+regex engine with your own, see L<perlreapi>.
 
 =head1 OVERVIEW
 
@@ -31,7 +32,7 @@ not to, in which case we will explain why.
 
 When speaking about regexes we need to distinguish between their source
 code form and their internal form. In this document we will use the term
-"pattern" when we speak of their textual, source code form, the term
+"pattern" when we speak of their textual, source code form, and the term
 "program" when we speak of their internal representation. These
 correspond to the terms I<S-regex> and I<B-regex> that Mark Jason
 Dominus employs in his paper on "Rx" ([1] in L</REFERENCES>).
@@ -43,7 +44,7 @@ specified in a mini-language, and then applies those constraints to a
 target string, and determines whether or not the string satisfies the
 constraints. See L<perlre> for a full definition of the language.
 
-So in less grandiose terms the first part of the job is to turn a pattern into
+In less grandiose terms, the first part of the job is to turn a pattern into
 something the computer can efficiently use to find the matching point in
 the string, and the second part is performing the search itself.
 
@@ -178,7 +179,7 @@ indicating which characters are included in the class.
 
 There is also a larger form of a char class structure used to represent
 POSIX char classes called C<regnode_charclass_class> which has an
-additional 4-byte (32-bit) bitmap indicating which POSIX char class
+additional 4-byte (32-bit) bitmap indicating which POSIX char classes
 have been included.
 
     regnode_charclass_class  U32 arg1;
@@ -221,7 +222,7 @@ always be so.
 =item *
 
 There is the "next regop" from a given regop/regnode. This is the
-regop physically located after the the current one, as determined by
+regop physically located after the current one, as determined by
 the size of the current regop. This is often useful, such as when
 dumping the structure we use this order to traverse. Sometimes the code
 assumes that the "next regnode" is the same as the "next regop", or in
@@ -332,12 +333,12 @@ first C<|> symbol it sees.
 
 C<regbranch()> in turn calls C<regpiece()> which
 handles "things" followed by a quantifier. In order to parse the
-"things", C<regatom()> is called. This is the lowest level routine which
+"things", C<regatom()> is called. This is the lowest level routine, which
 parses out constant strings, character classes, and the
 various special symbols like C<$>. If C<regatom()> encounters a "("
 character it in turn calls C<reg()>.
 
-The routine C<regtail()> is called by both C<reg()>, C<regbranch()>
+The routine C<regtail()> is called by both C<reg()> and C<regbranch()>
 in order to "set the tail pointer" correctly. When executing and
 we get to the end of a branch, we need to go to the node following the
 grouping parens. When parsing, however, we don't know where the end will
@@ -384,9 +385,9 @@ A grammar form might be something like this:
 
 =head3 Debug Output
 
-In the 5.9.x development version of perl you can C<< use re Debug => 'PARSE'; >> to see some trace
-information about the parse process. We will start with some simple
-patterns and build up to more complex patterns.
+In the 5.9.x development version of perl you can C<< use re Debug => 'PARSE' >>
+to see some trace information about the parse process. We will start with some
+simple patterns and build up to more complex patterns.
 
 So when we parse C</foo/> we see something like the following table. The
 left shows what is being parsed, and the number indicates where the next regop
@@ -544,9 +545,9 @@ the C<$> symbol has been converted into an C<EOL> regop, a special piece of
 code that looks for C<\n> or the end of the string.
 
 The next pointer for C<BRANCH>es is interesting in that it points at where
-execution should go if the branch fails. When executing if the engine
+execution should go if the branch fails. When executing, if the engine
 tries to traverse from a branch to a C<regnext> that isn't a branch then
-the engine will know that the entire set of branches have failed.
+the engine will know that the entire set of branches has failed.
 
 =head3 Peep-hole Optimisation and Analysis
 
@@ -589,13 +590,13 @@ optimisations along these lines:
 
 =back
 
-Another form of optimisation that can occur is post-parse "peep-hole"
-optimisations, where inefficient constructs are replaced by
-more efficient constructs. An example of this are C<TAIL> regops which are used
-during parsing to mark the end of branches and the end of groups. These
-regops are used as place-holders during construction and "always match"
-so they can be "optimised away" by making the things that point to the
-C<TAIL> point to thing that the C<TAIL> points to, thus "skipping" the node.
+Another form of optimisation that can occur is the post-parse "peep-hole"
+optimisation, where inefficient constructs are replaced by more efficient
+constructs. The C<TAIL> regops which are used during parsing to mark the end
+of branches and the end of groups are examples of this. These regops are used
+as place-holders during construction and "always match" so they can be
+"optimised away" by making the things that point to the C<TAIL> point to the
+thing that C<TAIL> points to, thus "skipping" the node.
 
 Another optimisation that can occur is that of "C<EXACT> merging" which is
 where two consecutive C<EXACT> nodes are merged into a single
@@ -623,13 +624,13 @@ interpreter.
 The two entry points are C<re_intuit_start()> and C<pregexec()>. These routines
 have a somewhat incestuous relationship with overlap between their functions,
 and C<pregexec()> may even call C<re_intuit_start()> on its own. Nevertheless
-other parts of the the perl source code may call into either, or both.
+other parts of the perl source code may call into either, or both.
 
-Execution of the interpreter itself used to be recursive. Due to the
-efforts of Dave Mitchell in the 5.9.x development track, it is now iterative. Now an
+Execution of the interpreter itself used to be recursive, but thanks to the
+efforts of Dave Mitchell in the 5.9.x development track, that has changed: now an
 internal stack is maintained on the heap and the routine is fully
 iterative. This can make it tricky as the code is quite conservative
-about what state it stores, with the result that that two consecutive lines in the
+about what state it stores, with the result that two consecutive lines in the
 code can actually be running in totally different contexts due to the
 simulated recursion.
 
@@ -684,7 +685,7 @@ that is a permissive version of Unicode's UTF-8 encoding[2]. This uses single
 bytes to represent characters from the ASCII character set, and sequences
 of two or more bytes for all other characters. (See L<perlunitut>
 for more information about the relationship between UTF-8 and perl's
-encoding, utf8 -- the difference isn't important for this discussion.)
+encoding, utf8. The difference isn't important for this discussion.)
 
 No matter how you look at it, Unicode support is going to be a pain in a
 regex engine. Tricks that might be fine when you have 256 possible
@@ -694,8 +695,8 @@ Unicode. For instance, in ASCII, it is safe to assume that
 C<sizeof(char1) == sizeof(char2)>, but in UTF-8 it isn't. Unicode case folding is
 vastly more complex than the simple rules of ASCII, and even when not
 using Unicode but only localised single byte encodings, things can get
-tricky (for example, GERMAN-SHARP-ESS should match 'SS' in localised
-case-insensitive matching).
+tricky (for example, B<LATIN SMALL LETTER SHARP S> (U+00DF, E<szlig>)
+should match 'SS' in localised case-insensitive matching).
 
 Making things worse is that UTF-8 support was a later addition to the
 regex engine (as it was to perl) and this necessarily  made things a lot
@@ -740,94 +741,88 @@ tricky this can be:
     A sequence of valid UTF-8 bytes cannot be a subsequence of
     another valid sequence of UTF-8 bytes.
 
-=head2 Base Struct
-
-F<regexp.h> contains the base structure definition:
-
-    typedef struct regexp {
-        I32 *startp;
-        I32 *endp;
-        regnode *regstclass;
-        struct reg_substr_data *substrs;
-        char *precomp;          /* pre-compilation regular expression */
-        struct reg_data *data;  /* Additional data. */
-        char *subbeg;           /* saved or original string
-                                   so \digit works forever. */
-    #ifdef PERL_OLD_COPY_ON_WRITE
-        SV *saved_copy;         /* If non-NULL, SV which is COW from original */
-    #endif
-        U32 *offsets;           /* offset annotations 20001228 MJD */
-        I32 sublen;             /* Length of string pointed by subbeg */
-        I32 refcnt;
-        I32 minlen;             /* mininum possible length of $& */
-        I32 prelen;             /* length of precomp */
-        U32 nparens;            /* number of parentheses */
-        U32 lastparen;          /* last paren matched */
-        U32 lastcloseparen;     /* last paren matched */
-        U32 reganch;            /* Internal use only +
-                                   Tainted information used by regexec? */
-        HV *paren_names;        /* Paren names */
-        const struct regexp_engine* engine;
-        regnode program[1];     /* Unwarranted chumminess with compiler. */
-    } regexp;
 
-=over 5
-
-=item C<program>
-
-Compiled program. Inlined into the structure so the entire struct can be
-treated as a single blob.
-
-=item C<data>
-
-This field points at a reg_data structure, which is defined as follows
+=head2 Base Structures
+
+The C<regexp> structure described in L<perlreapi> is common to all
+regex engines. Two of its fields that are intended for the private use
+of the regex engine that compiled the pattern. These are the
+C<intflags> and pprivate members. The C<pprivate> is a void pointer to
+an arbitrary structure whose use and management is the responsibility
+of the compiling engine. perl will never modify either of these
+values. In the case of the stock engine the structure pointed to by
+C<pprivate> is called C<regexp_internal>.
+
+Its C<pprivate> and C<intflags> fields contain data
+specific to each engine.
+
+There are two structures used to store a compiled regular expression.
+One, the C<regexp> structure described in L<perlreapi> is populated by
+the engine currently being. used and some of its fields read by perl to
+implement things such as the stringification of C<qr//>.
+
+
+The other structure is pointed to be the C<regexp> struct's
+C<pprivate> and is in addition to C<intflags> in the same struct
+considered to be the property of the regex engine which compiled the
+regular expression; 
+
+The regexp structure contains all the data that perl needs to be aware of
+to properly work with the regular expression. It includes data about
+optimisations that perl can use to determine if the regex engine should
+really be used, and various other control info that is needed to properly
+execute patterns in various contexts such as is the pattern anchored in
+some way, or what flags were used during the compile, or whether the
+program contains special constructs that perl needs to be aware of.
+
+In addition it contains two fields that are intended for the private use
+of the regex engine that compiled the pattern. These are the C<intflags>
+and pprivate members. The C<pprivate> is a void pointer to an arbitrary
+structure whose use and management is the responsibility of the compiling
+engine. perl will never modify either of these values.
+
+As mentioned earlier, in the case of the default engines, the C<pprivate>
+will be a pointer to a regexp_internal structure which holds the compiled
+program and any additional data that is private to the regex engine
+implementation.
+
+=head3 Perl's C<pprivate> structure
+
+The following structure is used as the C<pprivate> struct by perl's
+regex engine. Since it is specific to perl it is only of curiosity
+value to other engine implementations.
+
+    typedef struct regexp_internal {
+            regexp_paren_ofs *swap; /* Swap copy of *startp / *endp */
+            U32 *offsets;           /* offset annotations 20001228 MJD 
+                                       data about mapping the program to the 
+                                       string*/
+            regnode *regstclass;    /* Optional startclass as identified or constructed
+                                       by the optimiser */
+            struct reg_data *data;  /* Additional miscellaneous data used by the program.
+                                       Used to make it easier to clone and free arbitrary
+                                       data that the regops need. Often the ARG field of
+                                       a regop is an index into this structure */
+            regnode program[1];     /* Unwarranted chumminess with compiler. */
+    } regexp_internal;
 
-    struct reg_data {
-        U32 count;
-        U8 *what;
-        void* data[1];
-    };
-
-This structure is used for handling data structures that the regex engine
-needs to handle specially during a clone or free operation on the compiled
-product. Each element in the data array has a corresponding element in the
-what array. During compilation regops that need special structures stored
-will add an element to each array using the add_data() routine and then store
-the index in the regop.
-
-=item C<nparens>, C<lasparen>, and C<lastcloseparen>
-
-These fields are used to keep track of how many paren groups could be matched
-in the pattern, which was the last open paren to be entered, and which was
-the last close paren to be entered.
-
-=item C<startp>, C<endp>
-
-These fields store arrays that are used to hold the offsets of the begining
-and end of each capture group that has matched. -1 is used to indicate no match.
-
-These are the source for @- and @+.
+=over 5
 
-=item C<subbeg> C<sublen> C<saved_copy>
+=item C<swap>
 
-These are used during execution phase for managing search and replace
-patterns.
+C<swap> formerly was an extra set of startp/endp stored in a
+C<regexp_paren_ofs> struct. This was used when the last successful match
+was from the same pattern as the current pattern, so that a partial
+match didn't overwrite the previous match's results, but it caused a
+problem with re-entrant code such as trying to build the UTF-8 swashes.
+Currently unused and left for backward compatibility with 5.10.0.
 
-=item C<precomp> C<prelen> C<offsets>
+=item C<offsets>
 
-Used for debugging purposes. C<precomp> holds a copy of the pattern
-that was compiled, offsets holds a mapping of offset in the C<program>
-to offset in the C<precomp> string. This is only used by ActiveStates
+Offsets holds a mapping of offset in the C<program>
+to offset in the C<precomp> string. This is only used by ActiveState's
 visual regex debugger.
 
-=item C<reg_substr_data>
-
-Holds information on the longest string that must occur at a fixed
-offset from the start of the pattern, and the longest string that must
-occur at a floating offset from the start of the pattern. Used to do
-Fast-Boyer-Moore searches on the string to find out if its worth using
-the regex engine at all, and if so where in the string to search.
-
 =item C<regstclass>
 
 Special regop that is used by C<re_intuit_start()> to check if a pattern
@@ -838,143 +833,34 @@ that handles this is called C<find_by_class()>. Sometimes this field
 points at a regop embedded in the program, and sometimes it points at
 an independent synthetic regop that has been constructed by the optimiser.
 
-=item C<minlen>
-
-The minimum possible length of the final matching string. This is used
-to prune the search space by not bothering to match any closer to the
-end of a string than would allow a match. For instance there is no point
-in even starting the regex engine if the minlen is 10 but the string
-is only 5 characters long. There is no way that the pattern can match.
-
-=item C<reganch>
-
-This is used to store various flags about the pattern, such as whether it
-contains a \G or a ^ or $ symbol.
-
-=item C<paren_names>
-
-This is a hash used internally to track named capture buffers and their
-offsets. The keys are the names of the buffers the values are dualvars,
-with the IV slot holding the number of buffers with the given name and the
-pv being an embedded array of I32.  The values may also be contained
-independently in the data array in cases where named backreferences are
-used.
-
-=item C<refcnt>
-
-The number of times the structure is referenced. When this falls to 0
-the regexp is automatically freed by a call to pregfree.
-
-=item C<engine>
-
-This field points at a regexp_engine structure which contains pointers
-to the subroutine that are to be used for performing a match. It
-is the compiling routines responsibility to populate this field before
-returning the regexp object.
-
-=back
-
-=head2 Pluggable Interface
-
-As of Perl 5.9.5 there is a new interface for using other regexp engines
-than the default one.  Each engine is supposed to provide access to
-a constant structure of the following format:
-
-    typedef struct regexp_engine {
-        regexp* (*comp) (pTHX_ char* exp, char* xend, PMOP* pm);
-        I32    (*exec) (pTHX_ regexp* prog, char* stringarg, char* strend,
-                           char* strbeg, I32 minend, SV* screamer,
-                           void* data, U32 flags);
-        char*   (*intuit) (pTHX_ regexp *prog, SV *sv, char *strpos,
-                           char *strend, U32 flags,
-                           struct re_scream_pos_data_s *data);
-        SV*    (*checkstr) (pTHX_ regexp *prog);
-        void    (*free) (pTHX_ struct regexp* r);
-    #ifdef USE_ITHREADS
-        regexp* (*dupe) (pTHX_ const regexp *r, CLONE_PARAMS *param);
-    #endif
-    } regexp_engine;
-
-When a regexp is compiled its C<engine> field is then set to point at
-the appropriate structure so that when it needs to be used it can find
-the right routines to do so.
-
-In order to install a new regexp handler, C<$^H{regcomp}> is set
-to an integer which (when casted appropriately) resolves to one of these
-structures. When compiling the C<comp> method is executed, and the
-resulting regexp structures engine field is expected to point back at
-the same structure.
-
-The pTHX_ symbol in the definition is a macro used by perl under threading
-to provide an extra argument to the routine holding a pointer back to
-the interpreter that is executing the regexp. So under threading all
-routines get an extra argument.
-
-The routines are as follows:
-
-=over 4
-
-=item comp
-
-    regexp* comp(char *exp, char *xend, PMOP pm);
-
-Compile the pattern between exp and xend using the flags contained in
-pm and return a pointer to a prepared regexp structure that can perform
-the match.
-
-=item exec
-
-    I32 exec(regexp* prog,
-             char *stringarg, char* strend, char* strbeg,
-             I32 minend, SV* screamer,
-             void* data, U32 flags);
-
-Execute a regexp.
-
-=item intuit
-
-    char* intuit( regexp *prog,
-                  SV *sv, char *strpos, char *strend,
-                  U32 flags, struct re_scream_pos_data_s *data);
-
-Find the start position where a regex match should be attempted,
-or possibly whether the regex engine should not be run because the
-pattern can't match.
-
-=item checkstr
-
-    SV*        checkstr(regexp *prog);
-
-Return a SV containing a string that must appear in the pattern. Used
-for optimising matches.
-
-=item free
+=item C<data>
 
-    void free(regexp *prog);
+This field points at a reg_data structure, which is defined as follows
 
-Release any resources allocated to store this pattern.  After this
-call prog is an invalid pointer.
+    struct reg_data {
+        U32 count;
+        U8 *what;
+        void* data[1];
+    };
 
-=item dupe
+This structure is used for handling data structures that the regex engine
+needs to handle specially during a clone or free operation on the compiled
+product. Each element in the data array has a corresponding element in the
+what array. During compilation regops that need special structures stored
+will add an element to each array using the add_data() routine and then store
+the index in the regop.
 
-    regexp* dupe(const regexp *r, CLONE_PARAMS *param);
+=item C<program>
 
-On threaded builds a regexp may need to be duplicated so that the pattern
-can be used by mutiple threads. This routine is expected to handle the
-duplication.  On unthreaded builds this field doesnt exist.
+Compiled program. Inlined into the structure so the entire struct can be
+treated as a single blob.
 
 =back
 
-
-=head2 De-allocation and Cloning
-
-Any patch that adds data items to the regexp will need to include
-changes to F<sv.c> (C<Perl_re_dup()>) and F<regcomp.c> (C<pregfree()>). This
-involves freeing or cloning items in the regexes data array based
-on the data item's type.
-
 =head1 SEE ALSO
 
+L<perlreapi>
+
 L<perlre>
 
 L<perlunitut>