github的一些开源项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

853 lines
39 KiB

  1. Technical notes about PCRE2
  2. ---------------------------
  3. These are very rough technical notes that record potentially useful information
  4. about PCRE2 internals. PCRE2 is a library based on the original PCRE library,
  5. but with a revised (and incompatible) API. To avoid confusion, the original
  6. library is referred to as PCRE1 below. For information about testing PCRE2, see
  7. the pcre2test documentation and the comment at the head of the RunTest file.
  8. PCRE1 releases were up to 8.3x when PCRE2 was developed, and later bug fix
  9. releases carried on the 8.xx series, up to the final 8.45 release. PCRE2
  10. releases started at 10.00 to avoid confusion with PCRE1.
  11. Historical note 1
  12. -----------------
  13. Many years ago I implemented some regular expression functions to an algorithm
  14. suggested by Martin Richards. The rather simple patterns were not Unix-like in
  15. form, and were quite restricted in what they could do by comparison with Perl.
  16. The interesting part about the algorithm was that the amount of space required
  17. to hold the compiled form of an expression was known in advance. The code to
  18. apply an expression did not operate by backtracking, as the original Henry
  19. Spencer code and current PCRE2 and Perl code does, but instead checked all
  20. possibilities simultaneously by keeping a list of current states and checking
  21. all of them as it advanced through the subject string. In the terminology of
  22. Jeffrey Friedl's book, it was a "DFA algorithm", though it was not a
  23. traditional Finite State Machine (FSM). When the pattern was all used up, all
  24. remaining states were possible matches, and the one matching the longest subset
  25. of the subject string was chosen. This did not necessarily maximize the
  26. individual wild portions of the pattern, as is expected in Unix and Perl-style
  27. regular expressions.
  28. Historical note 2
  29. -----------------
  30. By contrast, the code originally written by Henry Spencer (which was
  31. subsequently heavily modified for Perl) compiles the expression twice: once in
  32. a dummy mode in order to find out how much store will be needed, and then for
  33. real. (The Perl version may or may not still do this; I'm talking about the
  34. original library.) The execution function operates by backtracking and
  35. maximizing (or, optionally, minimizing, in Perl) the amount of the subject that
  36. matches individual wild portions of the pattern. This is an "NFA algorithm" in
  37. Friedl's terminology.
  38. OK, here's the real stuff
  39. -------------------------
  40. For the set of functions that formed the original PCRE1 library in 1997 (which
  41. are unrelated to those mentioned above), I tried at first to invent an
  42. algorithm that used an amount of store bounded by a multiple of the number of
  43. characters in the pattern, to save on compiling time. However, because of the
  44. greater complexity in Perl regular expressions, I couldn't do this, even though
  45. the then current Perl 5.004 patterns were much simpler than those supported
  46. nowadays. In any case, a first pass through the pattern is helpful for other
  47. reasons.
  48. Support for 16-bit and 32-bit data strings
  49. -------------------------------------------
  50. The PCRE2 library can be compiled in any combination of 8-bit, 16-bit or 32-bit
  51. modes, creating up to three different libraries. In the description that
  52. follows, the word "short" is used for a 16-bit data quantity, and the phrase
  53. "code unit" is used for a quantity that is a byte in 8-bit mode, a short in
  54. 16-bit mode and a 32-bit word in 32-bit mode. The names of PCRE2 functions are
  55. given in generic form, without the _8, _16, or _32 suffix.
  56. Computing the memory requirement: how it was
  57. --------------------------------------------
  58. Up to and including release 6.7, PCRE1 worked by running a very degenerate
  59. first pass to calculate a maximum memory requirement, and then a second pass to
  60. do the real compile - which might use a bit less than the predicted amount of
  61. memory. The idea was that this would turn out faster than the Henry Spencer
  62. code because the first pass is degenerate and the second pass can just store
  63. stuff straight into memory, which it knows is big enough.
  64. Computing the memory requirement: how it is
  65. -------------------------------------------
  66. By the time I was working on a potential 6.8 release, the degenerate first pass
  67. had become very complicated and hard to maintain. Indeed one of the early
  68. things I did for 6.8 was to fix Yet Another Bug in the memory computation. Then
  69. I had a flash of inspiration as to how I could run the real compile function in
  70. a "fake" mode that enables it to compute how much memory it would need, while
  71. in most cases only ever using a small amount of working memory, and without too
  72. many tests of the mode that might slow it down. So I refactored the compiling
  73. functions to work this way. This got rid of about 600 lines of source and made
  74. further maintenance and development easier. As this was such a major change, I
  75. never released 6.8, instead upping the number to 7.0 (other quite major changes
  76. were also present in the 7.0 release).
  77. A side effect of this work was that the previous limit of 200 on the nesting
  78. depth of parentheses was removed. However, there was a downside: compiling ran
  79. more slowly than before (30% or more, depending on the pattern) because it now
  80. did a full analysis of the pattern. My hope was that this would not be a big
  81. issue, and in the event, nobody has commented on it.
  82. At release 8.34, a limit on the nesting depth of parentheses was re-introduced
  83. (default 250, settable at build time) so as to put a limit on the amount of
  84. system stack used by the compile function, which uses recursive function calls
  85. for nested parenthesized groups. This is a safety feature for environments with
  86. small stacks where the patterns are provided by users.
  87. Yet another pattern scan
  88. ------------------------
  89. History repeated itself for PCRE2 release 10.20. A number of bugs relating to
  90. named subpatterns had been discovered by fuzzers. Most of these were related to
  91. the handling of forward references when it was not known if the named group was
  92. unique. (References to non-unique names use a different opcode and more
  93. memory.) The use of duplicate group numbers (the (?| facility) also caused
  94. issues.
  95. To get around these problems I adopted a new approach by adding a third pass
  96. over the pattern (really a "pre-pass"), which did nothing other than identify
  97. all the named subpatterns and their corresponding group numbers. This means
  98. that the actual compile (both the memory-computing dummy run and the real
  99. compile) has full knowledge of group names and numbers throughout. Several
  100. dozen lines of messy code were eliminated, though the new pre-pass was not
  101. short. In particular, parsing and skipping over [] classes is complicated.
  102. While working on 10.22 I realized that I could simplify yet again by moving
  103. more of the parsing into the pre-pass, thus avoiding doing it in two places, so
  104. after 10.22 was released, the code underwent yet another big refactoring. This
  105. is how it is from 10.23 onwards:
  106. The function called parse_regex() scans the pattern characters, parsing them
  107. into literal data and meta characters. It converts escapes such as \x{123}
  108. into literals, handles \Q...\E, and skips over comments and non-significant
  109. white space. The result of the scanning is put into a vector of 32-bit unsigned
  110. integers. Values less than 0x80000000 are literal data. Higher values represent
  111. meta-characters. The top 16-bits of such values identify the meta-character,
  112. and these are given names such as META_CAPTURE. The lower 16-bits are available
  113. for data, for example, the capturing group number. The only situation in which
  114. literal data values greater than 0x7fffffff can appear is when the 32-bit
  115. library is running in non-UTF mode. This is handled by having a special
  116. meta-character that is followed by the 32-bit data value.
  117. The size of the parsed pattern vector, when auto-callouts are not enabled, is
  118. bounded by the length of the pattern (with one exception). The code is written
  119. so that each item in the pattern uses no more vector elements than the number
  120. of code units in the item itself. The exception is the aforementioned large
  121. 32-bit number handling. For this reason, 32-bit non-UTF patterns are scanned in
  122. advance to check for such values. When auto-callouts are enabled, the generous
  123. assumption is made that there will be a callout for each pattern code unit
  124. (which of course is only actually true if all code units are literals) plus one
  125. at the end. A default parsed pattern vector is defined on the system stack, to
  126. minimize memory handling, but if this is not big enough, heap memory is used.
  127. As before, the actual compiling function is run twice, the first time to
  128. determine the amount of memory needed for the final compiled pattern. It
  129. now processes the parsed pattern vector, not the pattern itself, although some
  130. of the parsed items refer to strings in the pattern - for example, group
  131. names. As escapes and comments have already been processed, the code is a bit
  132. simpler than before.
  133. Most errors can be diagnosed during the parsing scan. For those that cannot
  134. (for example, "lookbehind assertion is not fixed length"), the parsed code
  135. contains offsets into the pattern so that the actual compiling code can
  136. report where errors are.
  137. The elements of the parsed pattern vector
  138. -----------------------------------------
  139. The word "offset" below means a code unit offset into the pattern. When
  140. PCRE2_SIZE (which is usually size_t) is no bigger than uint32_t, an offset is
  141. stored in a single parsed pattern element. Otherwise (typically on 64-bit
  142. systems) it occupies two elements. The following meta items occupy just one
  143. element, with no data:
  144. META_ACCEPT (*ACCEPT)
  145. META_ASTERISK *
  146. META_ASTERISK_PLUS *+
  147. META_ASTERISK_QUERY *?
  148. META_ATOMIC (?> start of atomic group
  149. META_CIRCUMFLEX ^ metacharacter
  150. META_CLASS [ start of non-empty class
  151. META_CLASS_EMPTY [] empty class - only with PCRE2_ALLOW_EMPTY_CLASS
  152. META_CLASS_EMPTY_NOT [^] negative empty class - ditto
  153. META_CLASS_END ] end of non-empty class
  154. META_CLASS_NOT [^ start non-empty negative class
  155. META_COMMIT (*COMMIT) - no argument (see below for with argument)
  156. META_COND_ASSERT (?(?assertion)
  157. META_DOLLAR $ metacharacter
  158. META_DOT . metacharacter
  159. META_END End of pattern (this value is 0x80000000)
  160. META_FAIL (*FAIL)
  161. META_KET ) closing parenthesis
  162. META_LOOKAHEAD (?= start of lookahead
  163. META_LOOKAHEAD_NA (*napla: start of non-atomic lookahead
  164. META_LOOKAHEADNOT (?! start of negative lookahead
  165. META_NOCAPTURE (?: no capture parens
  166. META_PLUS +
  167. META_PLUS_PLUS ++
  168. META_PLUS_QUERY +?
  169. META_PRUNE (*PRUNE) - no argument (see below for with argument)
  170. META_QUERY ?
  171. META_QUERY_PLUS ?+
  172. META_QUERY_QUERY ??
  173. META_RANGE_ESCAPED hyphen in class range with at least one escape
  174. META_RANGE_LITERAL hyphen in class range defined literally
  175. META_SKIP (*SKIP) - no argument (see below for with argument)
  176. META_THEN (*THEN) - no argument (see below for with argument)
  177. The two RANGE values occur only in character classes. They are positioned
  178. between two literals that define the start and end of the range. In an EBCDIC
  179. environment it is necessary to know whether either of the range values was
  180. specified as an escape. In an ASCII/Unicode environment the distinction is not
  181. relevant.
  182. The following have data in the lower 16 bits, and may be followed by other data
  183. elements:
  184. META_ALT | alternation
  185. META_BACKREF back reference
  186. META_CAPTURE start of capturing group
  187. META_ESCAPE non-literal escape sequence
  188. META_RECURSE recursion call
  189. If the data for META_ALT is non-zero, it is inside a lookbehind, and the data
  190. is the maximum length of its branch (see META_LOOKBEHIND below for more
  191. detail).
  192. META_BACKREF, META_CAPTURE, and META_RECURSE have the capture group number as
  193. their data in the lower 16 bits of the element. META_RECURSE is followed by an
  194. offset, for use in error messages.
  195. META_BACKREF is followed by an offset if the back reference group number is 10
  196. or more. The offsets of the first occurrences of references to groups whose
  197. numbers are less than 10 are put in cb->small_ref_offset[] (only the first
  198. occurrence is useful). On 64-bit systems this avoids using more than two parsed
  199. pattern elements for items such as \3. The offset is used when an error occurs
  200. because the reference is to a non-existent group.
  201. META_ESCAPE has an ESC_xxx value as its data. For ESC_P and ESC_p, the next
  202. element contains the 16-bit type and data property values, packed together.
  203. ESC_g and ESC_k are used only for named references - numerical ones are turned
  204. into META_RECURSE or META_BACKREF as appropriate. ESC_g and ESC_k are followed
  205. by a length and an offset into the pattern to specify the name.
  206. The following have one data item that follows in the next vector element:
  207. META_BIGVALUE Next is a literal >= META_END
  208. META_POSIX POSIX class item (data identifies the class)
  209. META_POSIX_NEG negative POSIX class item (ditto)
  210. The following are followed by a length element, then a number of character code
  211. values (which should match with the length):
  212. META_MARK (*MARK:xxxx)
  213. META_COMMIT_ARG )*COMMIT:xxxx)
  214. META_PRUNE_ARG (*PRUNE:xxx)
  215. META_SKIP_ARG (*SKIP:xxxx)
  216. META_THEN_ARG (*THEN:xxxx)
  217. The following are followed by a length element, then an offset in the pattern
  218. that identifies the name:
  219. META_COND_NAME (?(<name>) or (?('name') or (?(name)
  220. META_COND_RNAME (?(R&name)
  221. META_COND_RNUMBER (?(Rdigits)
  222. META_RECURSE_BYNAME (?&name)
  223. META_BACKREF_BYNAME \k'name'
  224. META_COND_RNUMBER is used for names that start with R and continue with digits,
  225. because this is an ambiguous case. It could be a back reference to a group with
  226. that name, or it could be a recursion test on a numbered group.
  227. This one is followed by an offset, for use in error messages, then a number:
  228. META_COND_NUMBER (?([+-]digits)
  229. The following is followed just by an offset, for use in error messages:
  230. META_COND_DEFINE (?(DEFINE)
  231. The following are at first also followed just by an offset for use in error
  232. messages. After the lengths of the branches of a lookbehind group have been
  233. checked the error offset is no longer needed. The lower 16 bits of the main
  234. word are now set to the maximum length of the first branch of the lookbehind
  235. group, and the second word is set to the mimimum matching length for a
  236. variable-length lookbehind group, or to LOOKBEHIND_MAX for a group whose
  237. branches are all of fixed length. These values are used when generating
  238. OP_REVERSE or OP_VREVERSE for the first branch. The miminum value is also used
  239. for any subsequent branches because there is only room for one value (the
  240. branch maximum length) in a META_ALT item.
  241. META_LOOKBEHIND (?<= start of lookbehind
  242. META_LOOKBEHIND_NA (*naplb: start of non-atomic lookbehind
  243. META_LOOKBEHINDNOT (?<! start of negative lookbehind
  244. The following are followed by two elements, the minimum and maximum. The
  245. maximum value is limited to 65535 (MAX_REPEAT_COUNT). A maximum value of
  246. "unlimited" is represented by REPEAT_UNLIMITED, which is bigger than it:
  247. META_MINMAX {n,m} repeat
  248. META_MINMAX_PLUS {n,m}+ repeat
  249. META_MINMAX_QUERY {n,m}? repeat
  250. This one is followed by two elements, giving the new option settings for the
  251. main and extra options, respectively.
  252. META_OPTIONS (?i) and friends
  253. This one is followed by three elements. The first is 0 for '>' and 1 for '>=';
  254. the next two are the major and minor numbers:
  255. META_COND_VERSION (?(VERSION<op>x.y)
  256. Callouts are converted into one of two items:
  257. META_CALLOUT_NUMBER (?C with numerical argument
  258. META_CALLOUT_STRING (?C with string argument
  259. In both cases, the next two elements contain the offset and length of the next
  260. item in the pattern. Then there is either one callout number, or a length and
  261. an offset for the string argument. The length includes both delimiters.
  262. Traditional matching function
  263. -----------------------------
  264. The "traditional", and original, matching function is called pcre2_match(), and
  265. it implements an NFA algorithm, similar to the original Henry Spencer algorithm
  266. and the way that Perl works. This is not surprising, since it is intended to be
  267. as compatible with Perl as possible. This is the function most users of PCRE2
  268. will use most of the time. If PCRE2 is compiled with just-in-time (JIT)
  269. support, and studying a compiled pattern with JIT is successful, the JIT code
  270. is run instead of the normal pcre2_match() code, but the result is the same.
  271. Supplementary matching function
  272. -------------------------------
  273. There is also a supplementary matching function called pcre2_dfa_match(). This
  274. implements a DFA matching algorithm that searches simultaneously for all
  275. possible matches that start at one point in the subject string. (Going back to
  276. my roots: see Historical Note 1 above.) This function intreprets the same
  277. compiled pattern data as pcre2_match(); however, not all the facilities are
  278. available, and those that are do not always work in quite the same way. See the
  279. user documentation for details.
  280. The algorithm that is used for pcre2_dfa_match() is not a traditional FSM,
  281. because it may have a number of states active at one time. More work would be
  282. needed at compile time to produce a traditional FSM where only one state is
  283. ever active at once. I believe some other regex matchers work this way. JIT
  284. support is not available for this kind of matching.
  285. Changeable options
  286. ------------------
  287. The /i, /m, or /s options (PCRE2_CASELESS, PCRE2_MULTILINE, PCRE2_DOTALL) and
  288. some others may be changed in the middle of patterns by items such as (?i).
  289. Their processing is handled entirely at compile time by generating different
  290. opcodes for the different settings. The runtime functions do not need to keep
  291. track of an option's state.
  292. PCRE2_DUPNAMES, PCRE2_EXTENDED, PCRE2_EXTENDED_MORE, and PCRE2_NO_AUTO_CAPTURE
  293. are tracked and processed during the parsing pre-pass. The others are handled
  294. from META_OPTIONS items during the main compile phase.
  295. Format of compiled patterns
  296. ---------------------------
  297. The compiled form of a pattern is a vector of unsigned code units (bytes in
  298. 8-bit mode, shorts in 16-bit mode, 32-bit words in 32-bit mode), containing
  299. items of variable length. The first code unit in an item contains an opcode,
  300. and the length of the item is either implicit in the opcode or contained in the
  301. data that follows it.
  302. In many cases listed below, LINK_SIZE data values are specified for offsets
  303. within the compiled pattern. LINK_SIZE always specifies a number of bytes. The
  304. default value for LINK_SIZE is 2, except for the 32-bit library, where it can
  305. only be 4. The 8-bit library can be compiled to use 3-byte or 4-byte values,
  306. and the 16-bit library can be compiled to use 4-byte values, though this
  307. impairs performance. Specifying a LINK_SIZE larger than 2 for these libraries is
  308. necessary only when patterns whose compiled length is greater than 65535 code
  309. units are going to be processed. When a LINK_SIZE value uses more than one code
  310. unit, the most significant unit is first.
  311. In this description, we assume the "normal" compilation options. Data values
  312. that are counts (e.g. quantifiers) are always two bytes long in 8-bit mode
  313. (most significant byte first), and one code unit in 16-bit and 32-bit modes.
  314. Opcodes with no following data
  315. ------------------------------
  316. These items are all just one unit long:
  317. OP_END end of pattern
  318. OP_ANY match any one character other than newline
  319. OP_ALLANY match any one character, including newline
  320. OP_ANYBYTE match any single code unit, even in UTF-8/16 mode
  321. OP_SOD match start of data: \A
  322. OP_SOM, start of match (subject + offset): \G
  323. OP_SET_SOM, set start of match (\K)
  324. OP_CIRC ^ (start of data)
  325. OP_CIRCM ^ multiline mode (start of data or after newline)
  326. OP_NOT_WORD_BOUNDARY \W
  327. OP_WORD_BOUNDARY \w
  328. OP_NOT_DIGIT \D
  329. OP_DIGIT \d
  330. OP_NOT_HSPACE \H
  331. OP_HSPACE \h
  332. OP_NOT_WHITESPACE \S
  333. OP_WHITESPACE \s
  334. OP_NOT_VSPACE \V
  335. OP_VSPACE \v
  336. OP_NOT_WORDCHAR \W
  337. OP_WORDCHAR \w
  338. OP_EODN match end of data or newline at end: \Z
  339. OP_EOD match end of data: \z
  340. OP_DOLL $ (end of data, or before final newline)
  341. OP_DOLLM $ multiline mode (end of data or before newline)
  342. OP_EXTUNI match an extended Unicode grapheme cluster
  343. OP_ANYNL match any Unicode newline sequence
  344. OP_ASSERT_ACCEPT )
  345. OP_ACCEPT ) These are Perl 5.10's "backtracking control
  346. OP_COMMIT ) verbs". If OP_ACCEPT is inside capturing
  347. OP_FAIL ) parentheses, it may be preceded by one or more
  348. OP_PRUNE ) OP_CLOSE, each followed by a number that
  349. OP_SKIP ) indicates which parentheses must be closed.
  350. OP_THEN )
  351. OP_ASSERT_ACCEPT is used when (*ACCEPT) is encountered within an assertion.
  352. This ends the assertion, not the entire pattern match. The assertion (?!) is
  353. always optimized to OP_FAIL.
  354. OP_ALLANY is used for '.' when PCRE2_DOTALL is set. It is also used for \C in
  355. non-UTF modes and in UTF-32 mode (since one code unit still equals one
  356. character). Another use is for [^] when empty classes are permitted
  357. (PCRE2_ALLOW_EMPTY_CLASS is set).
  358. Backtracking control verbs
  359. --------------------------
  360. Verbs with no arguments generate opcodes with no following data (as listed
  361. in the section above).
  362. (*MARK:NAME) generates OP_MARK followed by the mark name, preceded by a
  363. length in one code unit, and followed by a binary zero. The name length is
  364. limited by the size of the code unit.
  365. (*ACCEPT:NAME) and (*FAIL:NAME) are compiled as (*MARK:NAME)(*ACCEPT) and
  366. (*MARK:NAME)(*FAIL) respectively.
  367. For (*COMMIT:NAME), (*PRUNE:NAME), (*SKIP:NAME), and (*THEN:NAME), the opcodes
  368. OP_COMMIT_ARG, OP_PRUNE_ARG, OP_SKIP_ARG, and OP_THEN_ARG are used, with the
  369. name following in the same format as for OP_MARK.
  370. Matching literal characters
  371. ---------------------------
  372. The OP_CHAR opcode is followed by a single character that is to be matched
  373. casefully. For caseless matching of characters that have at most two
  374. case-equivalent code points, OP_CHARI is used. In UTF-8 or UTF-16 modes, the
  375. character may be more than one code unit long. In UTF-32 mode, characters are
  376. always exactly one code unit long.
  377. If there is only one character in a character class, OP_CHAR or OP_CHARI is
  378. used for a positive class, and OP_NOT or OP_NOTI for a negative one (that is,
  379. for something like [^a]).
  380. Caseless matching (positive or negative) of characters that have more than two
  381. case-equivalent code points (which is possible only in UTF mode) is handled by
  382. compiling a Unicode property item (see below), with the pseudo-property
  383. PT_CLIST. The value of this property is an offset in a vector called
  384. "ucd_caseless_sets" which identifies the start of a short list of case
  385. equivalent characters, terminated by the value NOTACHAR (0xffffffff).
  386. Repeating single characters
  387. ---------------------------
  388. The common repeats (*, +, ?), when applied to a single character, use the
  389. following opcodes, which come in caseful and caseless versions:
  390. Caseful Caseless
  391. OP_STAR OP_STARI
  392. OP_MINSTAR OP_MINSTARI
  393. OP_POSSTAR OP_POSSTARI
  394. OP_PLUS OP_PLUSI
  395. OP_MINPLUS OP_MINPLUSI
  396. OP_POSPLUS OP_POSPLUSI
  397. OP_QUERY OP_QUERYI
  398. OP_MINQUERY OP_MINQUERYI
  399. OP_POSQUERY OP_POSQUERYI
  400. Each opcode is followed by the character that is to be repeated. In ASCII or
  401. UTF-32 modes, these are two-code-unit items; in UTF-8 or UTF-16 modes, the
  402. length is variable. Those with "MIN" in their names are the minimizing
  403. versions. Those with "POS" in their names are possessive versions. Other kinds
  404. of repeat make use of these opcodes:
  405. Caseful Caseless
  406. OP_UPTO OP_UPTOI
  407. OP_MINUPTO OP_MINUPTOI
  408. OP_POSUPTO OP_POSUPTOI
  409. OP_EXACT OP_EXACTI
  410. Each of these is followed by a count and then the repeated character. The count
  411. is two bytes long in 8-bit mode (most significant byte first), or one code unit
  412. in 16-bit and 32-bit modes.
  413. OP_UPTO matches from 0 to the given number. A repeat with a non-zero minimum
  414. and a fixed maximum is coded as an OP_EXACT followed by an OP_UPTO (or
  415. OP_MINUPTO or OPT_POSUPTO).
  416. Another set of matching repeating opcodes (called OP_NOTSTAR, OP_NOTSTARI,
  417. etc.) are used for repeated, negated, single-character classes such as [^a]*.
  418. The normal single-character opcodes (OP_STAR, etc.) are used for repeated
  419. positive single-character classes.
  420. Repeating character types
  421. -------------------------
  422. Repeats of things like \d are done exactly as for single characters, except
  423. that instead of a character, the opcode for the type (e.g. OP_DIGIT) is stored
  424. in the next code unit. The opcodes are:
  425. OP_TYPESTAR
  426. OP_TYPEMINSTAR
  427. OP_TYPEPOSSTAR
  428. OP_TYPEPLUS
  429. OP_TYPEMINPLUS
  430. OP_TYPEPOSPLUS
  431. OP_TYPEQUERY
  432. OP_TYPEMINQUERY
  433. OP_TYPEPOSQUERY
  434. OP_TYPEUPTO
  435. OP_TYPEMINUPTO
  436. OP_TYPEPOSUPTO
  437. OP_TYPEEXACT
  438. Match by Unicode property
  439. -------------------------
  440. OP_PROP and OP_NOTPROP are used for positive and negative matches of a
  441. character by testing its Unicode property (the \p and \P escape sequences).
  442. Each is followed by two code units that encode the desired property as a type
  443. and a value. The types are a set of #defines of the form PT_xxx, and the values
  444. are enumerations of the form ucp_xx, defined in the pcre2_ucp.h source file.
  445. The value is relevant only for PT_GC (General Category), PT_PC (Particular
  446. Category), PT_SC (Script), PT_BIDICL (Bidi Class), PT_BOOL (Boolean property),
  447. and the pseudo-property PT_CLIST, which is used to identify a list of
  448. case-equivalent characters when there are three or more (see above).
  449. Repeats of these items use the OP_TYPESTAR etc. set of opcodes, followed by
  450. three code units: OP_PROP or OP_NOTPROP, and then the desired property type and
  451. value.
  452. Character classes
  453. -----------------
  454. If there is only one character in a class, OP_CHAR or OP_CHARI is used for a
  455. positive class, and OP_NOT or OP_NOTI for a negative one (that is, for
  456. something like [^a]), except when caselessly matching a character that has more
  457. than two case-equivalent code points (which can happen only in UTF mode). In
  458. this case a Unicode property item is used, as described above in "Matching
  459. literal characters".
  460. A set of repeating opcodes (called OP_NOTSTAR etc.) are used for repeated,
  461. negated, single-character classes. The normal single-character opcodes
  462. (OP_STAR, etc.) are used for repeated positive single-character classes.
  463. When there is more than one character in a class, and all the code points are
  464. less than 256, OP_CLASS is used for a positive class, and OP_NCLASS for a
  465. negative one. In either case, the opcode is followed by a 32-byte (16-short,
  466. 8-word) bit map containing a 1 bit for every character that is acceptable. The
  467. bits are counted from the least significant end of each unit. In caseless mode,
  468. bits for both cases are set.
  469. The reason for having both OP_CLASS and OP_NCLASS is so that, in UTF-8 and
  470. 16-bit and 32-bit modes, subject characters with values greater than 255 can be
  471. handled correctly. For OP_CLASS they do not match, whereas for OP_NCLASS they
  472. do.
  473. For classes containing characters with values greater than 255 or that contain
  474. \p or \P, OP_XCLASS is used. It optionally uses a bit map if any acceptable
  475. code points are less than 256, followed by a list of pairs (for a range) and/or
  476. single characters and/or properties. In caseless mode, all equivalent
  477. characters are explicitly listed.
  478. OP_XCLASS is followed by a LINK_SIZE value containing the total length of the
  479. opcode and its data. This is followed by a code unit containing flag bits:
  480. XCL_NOT indicates that this is a negative class, and XCL_MAP indicates that a
  481. bit map is present. There follows the bit map, if XCL_MAP is set, and then a
  482. sequence of items coded as follows:
  483. XCL_END marks the end of the list
  484. XCL_SINGLE one character follows
  485. XCL_RANGE two characters follow
  486. XCL_PROP a Unicode property (type, value) follows
  487. XCL_NOTPROP a Unicode property (type, value) follows
  488. If a range starts with a code point less than 256 and ends with one greater
  489. than 255, it is split into two ranges, with characters less than 256 being
  490. indicated in the bit map, and the rest with XCL_RANGE.
  491. When XCL_NOT is set, the bit map, if present, contains bits for characters that
  492. are allowed (exactly as for OP_NCLASS), but the list of items that follow it
  493. specifies characters and properties that are not allowed.
  494. Back references
  495. ---------------
  496. OP_REF (caseful) or OP_REFI (caseless) is followed by a count containing the
  497. reference number when the reference is to a unique capturing group (either by
  498. number or by name). When named groups are used, there may be more than one
  499. group with the same name. In this case, a reference to such a group by name
  500. generates OP_DNREF or OP_DNREFI. These are followed by two counts: the index
  501. (not the byte offset) in the group name table of the first entry for the
  502. required name, followed by the number of groups with the same name. The
  503. matching code can then search for the first one that is set.
  504. Repeating character classes and back references
  505. -----------------------------------------------
  506. Single-character classes are handled specially (see above). This section
  507. applies to other classes and also to back references. In both cases, the repeat
  508. information follows the base item. The matching code looks at the following
  509. opcode to see if it is one of these:
  510. OP_CRSTAR
  511. OP_CRMINSTAR
  512. OP_CRPOSSTAR
  513. OP_CRPLUS
  514. OP_CRMINPLUS
  515. OP_CRPOSPLUS
  516. OP_CRQUERY
  517. OP_CRMINQUERY
  518. OP_CRPOSQUERY
  519. OP_CRRANGE
  520. OP_CRMINRANGE
  521. OP_CRPOSRANGE
  522. All but the last three are single-code-unit items, with no data. The range
  523. opcodes are followed by the minimum and maximum repeat counts.
  524. Brackets and alternation
  525. ------------------------
  526. A pair of non-capturing round brackets is wrapped round each expression at
  527. compile time, so alternation always happens in the context of brackets.
  528. [Note for North Americans: "bracket" to some English speakers, including
  529. myself, can be round, square, curly, or pointy. Hence this usage rather than
  530. "parentheses".]
  531. Non-capturing brackets use the opcode OP_BRA, capturing brackets use OP_CBRA. A
  532. bracket opcode is followed by a LINK_SIZE value which gives the offset to the
  533. next alternative OP_ALT or, if there aren't any branches, to the terminating
  534. opcode. Each OP_ALT is followed by a LINK_SIZE value giving the offset to the
  535. next one, or to the final opcode. For capturing brackets, the bracket number is
  536. a count that immediately follows the offset.
  537. There are several opcodes that mark the end of a subpattern group. OP_KET is
  538. used for subpatterns that do not repeat indefinitely, OP_KETRMIN and
  539. OP_KETRMAX are used for indefinite repetitions, minimally or maximally
  540. respectively, and OP_KETRPOS for possessive repetitions (see below for more
  541. details). All four are followed by a LINK_SIZE value giving (as a positive
  542. number) the offset back to the matching opening bracket opcode.
  543. If a subpattern is quantified such that it is permitted to match zero times, it
  544. is preceded by one of OP_BRAZERO, OP_BRAMINZERO, or OP_SKIPZERO. These are
  545. single-unit opcodes that tell the matcher that skipping the following
  546. subpattern entirely is a valid match. In the case of the first two, not
  547. skipping the pattern is also valid (greedy and non-greedy). The third is used
  548. when a pattern has the quantifier {0,0}. It cannot be entirely discarded,
  549. because it may be called as a subroutine from elsewhere in the pattern.
  550. A subpattern with an indefinite maximum repetition is replicated in the
  551. compiled data its minimum number of times (or once with OP_BRAZERO if the
  552. minimum is zero), with the final copy terminating with OP_KETRMIN or OP_KETRMAX
  553. as appropriate.
  554. A subpattern with a bounded maximum repetition is replicated in a nested
  555. fashion up to the maximum number of times, with OP_BRAZERO or OP_BRAMINZERO
  556. before each replication after the minimum, so that, for example, (abc){2,5} is
  557. compiled as (abc)(abc)((abc)((abc)(abc)?)?)?, except that each bracketed group
  558. has the same number.
  559. When a repeated subpattern has an unbounded upper limit, it is checked to see
  560. whether it could match an empty string. If this is the case, the opcode in the
  561. final replication is changed to OP_SBRA or OP_SCBRA. This tells the matcher
  562. that it needs to check for matching an empty string when it hits OP_KETRMIN or
  563. OP_KETRMAX, and if so, to break the loop.
  564. Possessive brackets
  565. -------------------
  566. When a repeated group (capturing or non-capturing) is marked as possessive by
  567. the "+" notation, e.g. (abc)++, different opcodes are used. Their names all
  568. have POS on the end, e.g. OP_BRAPOS instead of OP_BRA and OP_SCBRAPOS instead
  569. of OP_SCBRA. The end of such a group is marked by OP_KETRPOS. If the minimum
  570. repetition is zero, the group is preceded by OP_BRAPOSZERO.
  571. Once-only (atomic) groups
  572. -------------------------
  573. These are just like other subpatterns, but they start with the opcode OP_ONCE.
  574. The check for matching an empty string in an unbounded repeat is handled
  575. entirely at runtime, so there is just this one opcode for atomic groups.
  576. Assertions
  577. ----------
  578. Forward assertions are also just like other subpatterns, but starting with one
  579. of the opcodes OP_ASSERT, OP_ASSERT_NA (non-atomic assertion), or
  580. OP_ASSERT_NOT.
  581. Backward assertions use the opcodes OP_ASSERTBACK, OP_ASSERTBACK_NA, and
  582. OP_ASSERTBACK_NOT. If all the branches of a backward assertion are of fixed
  583. length (not necessarily the same), the first opcode inside each branch is
  584. OP_REVERSE, followed by an IMM2_SIZE count of the number of characters to move
  585. back the pointer in the subject string, thus allowing each branch to have a
  586. different (but fixed) length.
  587. Variable-length backward assertions whose maximum matching length is limited
  588. are also supported. For such assertions, the first opcode inside each branch is
  589. OP_VREVERSE, followed by the minimum and maximum lengths for that branch,
  590. unless these happen to be equal, in which case OP_REVERSE is used. These
  591. IMM2_SIZE values occupy two code units each in 8-bit mode, and 1 code unit in
  592. 16/32 bit modes.
  593. In ASCII or UTF-32 mode, the character counts in OP_REVERSE and OP_VREVERSE are
  594. also the number of code units, but in UTF-8/16 mode each character may occupy
  595. more than one code unit.
  596. Conditional subpatterns
  597. -----------------------
  598. These are like other subpatterns, but they start with the opcode OP_COND, or
  599. OP_SCOND for one that might match an empty string in an unbounded repeat.
  600. If the condition is a back reference, this is stored at the start of the
  601. subpattern using the opcode OP_CREF followed by a count containing the
  602. reference number, provided that the reference is to a unique capturing group.
  603. If the reference was by name and there is more than one group with that name,
  604. OP_DNCREF is used instead. It is followed by two counts: the index in the group
  605. names table, and the number of groups with the same name. The allows the
  606. matcher to check if any group with the given name is set.
  607. If the condition is "in recursion" (coded as "(?(R)"), or "in recursion of
  608. group x" (coded as "(?(Rx)"), the group number is stored at the start of the
  609. subpattern using the opcode OP_RREF (with a value of RREF_ANY (0xffff) for "the
  610. whole pattern") or OP_DNRREF (with data as for OP_DNCREF).
  611. For a DEFINE condition, OP_FALSE is used (with no associated data). During
  612. compilation, however, a DEFINE condition is coded as OP_DEFINE so that, when
  613. the conditional group is complete, there can be a check to ensure that it
  614. contains only one top-level branch. Once this has happened, the opcode is
  615. changed to OP_FALSE, so the matcher never sees OP_DEFINE.
  616. There is a special PCRE2-specific condition of the form (VERSION[>]=x.y), which
  617. tests the PCRE2 version number. This compiles into one of the opcodes OP_TRUE
  618. or OP_FALSE.
  619. If a condition is not a back reference, recursion test, DEFINE, or VERSION, it
  620. must start with a parenthesized atomic assertion, whose opcode normally
  621. immediately follows OP_COND or OP_SCOND. However, if automatic callouts are
  622. enabled, a callout is inserted immediately before the assertion. It is also
  623. possible to insert a manual callout at this point. Only assertion conditions
  624. may have callouts preceding the condition.
  625. A condition that is the negative assertion (?!) is optimized to OP_FAIL in all
  626. parts of the pattern, so this is another opcode that may appear as a condition.
  627. It is treated the same as OP_FALSE.
  628. Recursion
  629. ---------
  630. Recursion either matches the current pattern, or some subexpression. The opcode
  631. OP_RECURSE is followed by a LINK_SIZE value that is the offset to the starting
  632. bracket from the start of the whole pattern. OP_RECURSE is also used for
  633. "subroutine" calls, even though they are not strictly a recursion. Up till
  634. release 10.30 recursions were treated as atomic groups, making them
  635. incompatible with Perl (but PCRE had them well before Perl did). From 10.30,
  636. backtracking into recursions is supported.
  637. Repeated recursions used to be wrapped inside OP_ONCE brackets, which not only
  638. forced no backtracking, but also allowed repetition to be handled as for other
  639. bracketed groups. From 10.30 onwards, repeated recursions are duplicated for
  640. their minimum repetitions, and then wrapped in non-capturing brackets for the
  641. remainder. For example, (?1){3} is treated as (?1)(?1)(?1), and (?1){2,4} is
  642. treated as (?1)(?1)(?:(?1)){0,2}.
  643. Callouts
  644. --------
  645. A callout may have either a numerical argument or a string argument. These use
  646. OP_CALLOUT or OP_CALLOUT_STR, respectively. In each case these are followed by
  647. two LINK_SIZE values giving the offset in the pattern string to the start of
  648. the following item, and another count giving the length of this item. These
  649. values make it possible for pcre2test to output useful tracing information
  650. using callouts.
  651. In the case of a numeric callout, after these two values there is a single code
  652. unit containing the callout number, in the range 0-255, with 255 being used for
  653. callouts that are automatically inserted as a result of the PCRE2_AUTO_CALLOUT
  654. option. Thus, this opcode item is of fixed length:
  655. [OP_CALLOUT] [PATTERN_OFFSET] [PATTERN_LENGTH] [NUMBER]
  656. For callouts with string arguments, OP_CALLOUT_STR has three more data items:
  657. a LINK_SIZE value giving the complete length of the entire opcode item, a
  658. LINK_SIZE item containing the offset within the pattern string to the start of
  659. the string argument, and the string itself, preceded by its starting delimiter
  660. and followed by a binary zero. When a callout function is called, a pointer to
  661. the actual string is passed, but the delimiter can be accessed as string[-1] if
  662. the application needs it. In the 8-bit library, the callout in /X(?C'abc')Y/ is
  663. compiled as the following bytes (decimal numbers represent binary values):
  664. [OP_CALLOUT_STR] [0] [10] [0] [1] [0] [14] [0] [5] ['] [a] [b] [c] [0]
  665. -------- ------- -------- -------
  666. | | | |
  667. ------- LINK_SIZE items ------
  668. Opcode table checking
  669. ---------------------
  670. The last opcode that is defined in pcre2_internal.h is OP_TABLE_LENGTH. This is
  671. not a real opcode, but is used to check at compile time that tables indexed by
  672. opcode are the correct length, in order to catch updating errors.
  673. Philip Hazel
  674. November 2023