robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
450.6 KiB16457 linesraw
1// Handling of regular expressions: vim_regcomp(), vim_regexec(), vim_regsub()
2
3// By default: do not create debugging logs or files related to regular
4// expressions, even when compiling with -DDEBUG.
5// Uncomment the second line to get the regexp debugging.
6// #undef REGEXP_DEBUG
7// #define REGEXP_DEBUG
8
9#include <assert.h>
10#include <ctype.h>
11#include <inttypes.h>
12#include <limits.h>
13#include <stdbool.h>
14#include <stddef.h>
15#include <stdlib.h>
16#include <string.h>
17#include <uv.h>
18
19#include "nvim/ascii_defs.h"
20#include "nvim/buffer_defs.h"
21#include "nvim/charset.h"
22#include "nvim/errors.h"
23#include "nvim/eval.h"
24#include "nvim/eval/typval.h"
25#include "nvim/eval/userfunc.h"
26#include "nvim/garray.h"
27#include "nvim/garray_defs.h"
28#include "nvim/gettext_defs.h"
29#include "nvim/globals.h"
30#include "nvim/keycodes.h"
31#include "nvim/macros_defs.h"
32#include "nvim/mark.h"
33#include "nvim/mark_defs.h"
34#include "nvim/mbyte.h"
35#include "nvim/mbyte_defs.h"
36#include "nvim/memline.h"
37#include "nvim/memory.h"
38#include "nvim/message.h"
39#include "nvim/option_vars.h"
40#include "nvim/os/input.h"
41#include "nvim/plines.h"
42#include "nvim/pos_defs.h"
43#include "nvim/profile.h"
44#include "nvim/regexp.h"
45#include "nvim/regexp_defs.h"
46#include "nvim/strings.h"
47#include "nvim/types_defs.h"
48#include "nvim/vim_defs.h"
49
50typedef enum {
51  RGLF_LINE = 0x01,
52  RGLF_LENGTH = 0x02,
53  RGLF_SUBMATCH = 0x04,
54} reg_getline_flags_T;
55
56enum {
57  /// In the NFA engine: how many states are allowed.
58  NFA_MAX_STATES = 100000,
59  NFA_TOO_EXPENSIVE = -1,
60};
61
62/// Which regexp engine to use? Needed for vim_regcomp().
63/// Must match with 'regexpengine'.
64enum {
65  AUTOMATIC_ENGINE    = 0,
66  BACKTRACKING_ENGINE = 1,
67  NFA_ENGINE          = 2,
68};
69
70/// Structure returned by vim_regcomp() to pass on to vim_regexec().
71/// This is the general structure. For the actual matcher, two specific
72/// structures are used. See code below.
73struct regprog {
74  regengine_T *engine;
75  unsigned regflags;
76  unsigned re_engine;  ///< Automatic, backtracking or NFA engine.
77  unsigned re_flags;   ///< Second argument for vim_regcomp().
78  bool re_in_use;      ///< prog is being executed
79};
80
81/// Structure used by the back track matcher.
82/// These fields are only to be used in regexp.c!
83/// See regexp.c for an explanation.
84typedef struct {
85  // These four members implement regprog_T.
86  regengine_T *engine;
87  unsigned regflags;
88  unsigned re_engine;
89  unsigned re_flags;
90  bool re_in_use;
91
92  int regstart;
93  uint8_t reganch;
94  uint8_t *regmust;
95  int regmlen;
96#ifdef REGEXP_DEBUG
97  int regsz;
98#endif
99  uint8_t reghasz;
100  uint8_t program[];
101} bt_regprog_T;
102
103/// Structure representing a NFA state.
104/// An NFA state may have no outgoing edge, when it is a NFA_MATCH state.
105typedef struct nfa_state nfa_state_T;
106struct nfa_state {
107  int c;
108  nfa_state_T *out;
109  nfa_state_T *out1;
110  int id;
111  int lastlist[2];  ///< 0: normal, 1: recursive
112  int val;
113};
114
115/// Structure used by the NFA matcher.
116typedef struct {
117  // These four members implement regprog_T.
118  regengine_T *engine;
119  unsigned regflags;
120  unsigned re_engine;
121  unsigned re_flags;
122  bool re_in_use;
123
124  nfa_state_T *start;   ///< points into state[]
125
126  int reganch;          ///< pattern starts with ^
127  int regstart;         ///< char at start of pattern
128  uint8_t *match_text;  ///< plain text to match with
129
130  int has_zend;         ///< pattern contains \ze
131  int has_backref;      ///< pattern contains \1 .. \9
132  int reghasz;
133  char *pattern;
134  int nsubexp;          ///< number of ()
135  int nstate;
136  void *listbuf[2];     ///< cached list buffers for nfa_regmatch()
137  nfa_state_T state[];
138} nfa_regprog_T;
139
140struct regengine {
141  /// bt_regcomp or nfa_regcomp
142  regprog_T *(*regcomp)(uint8_t *, int);
143  /// bt_regfree or nfa_regfree
144  void (*regfree)(regprog_T *);
145  /// bt_regexec_nl or nfa_regexec_nl
146  int (*regexec_nl)(regmatch_T *, uint8_t *, colnr_T, bool);
147  /// bt_regexec_mult or nfa_regexec_mult
148  int (*regexec_multi)(regmmatch_T *, win_T *, buf_T *, linenr_T, colnr_T, proftime_T *, int *);
149#ifdef REGEXP_DEBUG
150  uint8_t *expr;
151#endif
152};
153
154// Structure used to save the current input state, when it needs to be
155// restored after trying a match.  Used by reg_save() and reg_restore().
156// Also stores the length of "backpos".
157typedef struct {
158  union {
159    uint8_t *ptr;       // rex.input pointer, for single-line regexp
160    lpos_T pos;        // rex.input pos, for multi-line regexp
161  } rs_u;
162  int rs_len;
163} regsave_T;
164
165// struct to save start/end pointer/position in for \(\)
166typedef struct {
167  union {
168    uint8_t *ptr;
169    lpos_T pos;
170  } se_u;
171} save_se_T;
172
173// Values for rs_state in regitem_T.
174typedef enum regstate_E {
175  RS_NOPEN = 0,         // NOPEN and NCLOSE
176  RS_MOPEN,             // MOPEN + [0-9]
177  RS_MCLOSE,            // MCLOSE + [0-9]
178  RS_ZOPEN,             // ZOPEN + [0-9]
179  RS_ZCLOSE,            // ZCLOSE + [0-9]
180  RS_BRANCH,            // BRANCH
181  RS_BRCPLX_MORE,       // BRACE_COMPLEX and trying one more match
182  RS_BRCPLX_LONG,       // BRACE_COMPLEX and trying longest match
183  RS_BRCPLX_SHORT,      // BRACE_COMPLEX and trying shortest match
184  RS_NOMATCH,           // NOMATCH
185  RS_BEHIND1,           // BEHIND / NOBEHIND matching rest
186  RS_BEHIND2,           // BEHIND / NOBEHIND matching behind part
187  RS_STAR_LONG,         // STAR/PLUS/BRACE_SIMPLE longest match
188  RS_STAR_SHORT,  // STAR/PLUS/BRACE_SIMPLE shortest match
189} regstate_T;
190
191// When there are alternatives a regstate_T is put on the regstack to remember
192// what we are doing.
193// Before it may be another type of item, depending on rs_state, to remember
194// more things.
195typedef struct regitem_S {
196  regstate_T rs_state;         // what we are doing, one of RS_ above
197  int16_t rs_no;            // submatch nr or BEHIND/NOBEHIND
198  uint8_t *rs_scan;         // current node in program
199  union {
200    save_se_T sesave;
201    regsave_T regsave;
202  } rs_un;                      // room for saving rex.input
203} regitem_T;
204
205// used for BEHIND and NOBEHIND matching
206typedef struct regbehind_S {
207  regsave_T save_after;
208  regsave_T save_behind;
209  int save_need_clear_subexpr;
210  save_se_T save_start[NSUBEXP];
211  save_se_T save_end[NSUBEXP];
212} regbehind_T;
213
214// Since the out pointers in the list are always
215// uninitialized, we use the pointers themselves
216// as storage for the Ptrlists.
217typedef union Ptrlist Ptrlist;
218union Ptrlist {
219  Ptrlist *next;
220  nfa_state_T *s;
221};
222
223struct Frag {
224  nfa_state_T *start;
225  Ptrlist *out;
226};
227typedef struct Frag Frag_T;
228
229typedef struct {
230  int in_use;       ///< number of subexpr with useful info
231
232  // When REG_MULTI is true list.multi is used, otherwise list.line.
233  union {
234    struct multipos {
235      linenr_T start_lnum;
236      linenr_T end_lnum;
237      colnr_T start_col;
238      colnr_T end_col;
239    } multi[NSUBEXP];
240    struct linepos {
241      uint8_t *start;
242      uint8_t *end;
243    } line[NSUBEXP];
244  } list;
245  colnr_T orig_start_col;  // list.multi[0].start_col without \zs
246} regsub_T;
247
248typedef struct {
249  regsub_T norm;      // \( .. \) matches
250  regsub_T synt;      // \z( .. \) matches
251} regsubs_T;
252
253// nfa_pim_T stores a Postponed Invisible Match.
254typedef struct nfa_pim_S nfa_pim_T;
255struct nfa_pim_S {
256  int result;                   // NFA_PIM_*, see below
257  nfa_state_T *state;           // the invisible match start state
258  regsubs_T subs;               // submatch info, only party used
259  union {
260    lpos_T pos;
261    uint8_t *ptr;
262  } end;                        // where the match must end
263};
264
265// nfa_thread_T contains execution information of a NFA state
266typedef struct {
267  nfa_state_T *state;
268  int count;
269  nfa_pim_T pim;                // if pim.result != NFA_PIM_UNUSED: postponed
270                                // invisible match
271  regsubs_T subs;               // submatch info, only party used
272} nfa_thread_T;
273
274// nfa_list_T contains the alternative NFA execution states.
275typedef struct {
276  nfa_thread_T *t;           ///< allocated array of states
277  int n;                        ///< nr of states currently in "t"
278  int len;                      ///< max nr of states in "t"
279  int id;                       ///< ID of the list
280  int has_pim;                  ///< true when any state has a PIM
281} nfa_list_T;
282
283#ifdef REGEXP_DEBUG
284// show/save debugging data when BT engine is used
285# define BT_REGEXP_DUMP
286// save the debugging data to a file instead of displaying it
287# define BT_REGEXP_LOG
288# define BT_REGEXP_DEBUG_LOG
289# define BT_REGEXP_DEBUG_LOG_NAME       "bt_regexp_debug.log"
290#endif
291
292// Magic characters have a special meaning, they don't match literally.
293// Magic characters are negative.  This separates them from literal characters
294// (possibly multi-byte).  Only ASCII characters can be Magic.
295#define Magic(x)        ((int)(x) - 256)
296#define un_Magic(x)     ((x) + 256)
297#define is_Magic(x)     ((x) < 0)
298
299typedef void (*fptr_T)(int *, int);
300
301static int no_Magic(int x)
302{
303  if (is_Magic(x)) {
304    return un_Magic(x);
305  }
306  return x;
307}
308
309static int toggle_Magic(int x)
310{
311  if (is_Magic(x)) {
312    return un_Magic(x);
313  }
314  return Magic(x);
315}
316
317// The first byte of the BT regexp internal "program" is actually this magic
318// number; the start node begins in the second byte.  It's used to catch the
319// most severe mutilation of the program by the caller.
320#define REGMAGIC        0234
321
322// Utility definitions.
323#define UCHARAT(p)      ((int)(*(uint8_t *)(p)))
324
325// Used for an error (down from) vim_regcomp(): give the error message, set
326// rc_did_emsg and return NULL
327#define EMSG_RET_NULL(m) return (emsg(m), rc_did_emsg = true, (void *)NULL)
328#define IEMSG_RET_NULL(m) return (iemsg(m), rc_did_emsg = true, (void *)NULL)
329#define EMSG_RET_FAIL(m) return (emsg(m), rc_did_emsg = true, FAIL)
330#define EMSG2_RET_NULL(m, c) \
331  return (semsg((m), (c) ? "" : "\\"), rc_did_emsg = true, (void *)NULL)
332#define EMSG3_RET_NULL(m, c, a) \
333  return (semsg((m), (c) ? "" : "\\", (a)), rc_did_emsg = true, (void *)NULL)
334#define EMSG2_RET_FAIL(m, c) \
335  return (semsg((m), (c) ? "" : "\\"), rc_did_emsg = true, FAIL)
336#define EMSG_ONE_RET_NULL EMSG2_RET_NULL(_(e_invalid_item_in_str_brackets), reg_magic == MAGIC_ALL)
337
338#define MAX_LIMIT       (32767 << 16)
339
340static const char e_invalid_character_after_str_at[]
341  = N_("E59: Invalid character after %s@");
342static const char e_invalid_use_of_underscore[]
343  = N_("E63: Invalid use of \\_");
344static const char e_pattern_uses_more_memory_than_maxmempattern[]
345  = N_("E363: Pattern uses more memory than 'maxmempattern'");
346static const char e_invalid_item_in_str_brackets[]
347  = N_("E369: Invalid item in %s%%[]");
348static const char e_missing_delimiter_after_search_pattern_str[]
349  = N_("E654: Missing delimiter after search pattern: %s");
350static const char e_missingbracket[] = N_("E769: Missing ] after %s[");
351static const char e_reverse_range[] = N_("E944: Reverse range in character class");
352static const char e_large_class[] = N_("E945: Range too large in character class");
353static const char e_unmatched_z[] = N_("E52: Unmatched \\z(");
354static const char e_unmatched_str_percent_open[] = N_("E53: Unmatched %s%%(");
355static const char e_unmatched_str_open[] = N_("E54: Unmatched %s(");
356static const char e_unmatched_str_close[] = N_("E55: Unmatched %s)");
357static const char e_z_not_allowed[] = N_("E66: \\z( not allowed here");
358static const char e_z1_not_allowed[] = N_("E67: \\z1 - \\z9 not allowed here");
359static const char e_missing_sb[] = N_("E69: Missing ] after %s%%[");
360static const char e_empty_sb[] = N_("E70: Empty %s%%[]");
361static const char e_recursive[] = N_("E956: Cannot use pattern recursively");
362static const char e_regexp_number_after_dot_pos_search_chr[]
363  = N_("E1204: No Number allowed after .: '\\%%%c'");
364static const char e_nfa_regexp_missing_value_in_chr[]
365  = N_("E1273: (NFA regexp) missing value in '\\%%%c'");
366static const char e_atom_engine_must_be_at_start_of_pattern[]
367  = N_("E1281: Atom '\\%%#=%c' must be at the start of the pattern");
368static const char e_substitute_nesting_too_deep[] = N_("E1290: substitute nesting too deep");
369static const char e_unicode_val_too_large[]
370  = N_("E1541: Value too large, max Unicode codepoint is U+10FFFF");
371
372#define NOT_MULTI       0
373#define MULTI_ONE       1
374#define MULTI_MULT      2
375
376// return values for regmatch()
377#define RA_FAIL         1       // something failed, abort
378#define RA_CONT         2       // continue in inner loop
379#define RA_BREAK        3       // break inner loop
380#define RA_MATCH        4       // successful match
381#define RA_NOMATCH      5       // didn't match
382
383/// Return NOT_MULTI if c is not a "multi" operator.
384/// Return MULTI_ONE if c is a single "multi" operator.
385/// Return MULTI_MULT if c is a multi "multi" operator.
386static int re_multi_type(int c)
387{
388  if (c == Magic('@') || c == Magic('=') || c == Magic('?')) {
389    return MULTI_ONE;
390  }
391  if (c == Magic('*') || c == Magic('+') || c == Magic('{')) {
392    return MULTI_MULT;
393  }
394  return NOT_MULTI;
395}
396
397static char *reg_prev_sub = NULL;
398static size_t reg_prev_sublen = 0;
399
400// REGEXP_INRANGE contains all characters which are always special in a []
401// range after '\'.
402// REGEXP_ABBR contains all characters which act as abbreviations after '\'.
403// These are:
404//  \n  - New line (NL).
405//  \r  - Carriage Return (CR).
406//  \t  - Tab (TAB).
407//  \e  - Escape (ESC).
408//  \b  - Backspace (Ctrl_H).
409//  \d  - Character code in decimal, eg \d123
410//  \o  - Character code in octal, eg \o80
411//  \x  - Character code in hex, eg \x4a
412//  \u  - Multibyte character code, eg \u20ac
413//  \U  - Long multibyte character code, eg \U12345678
414static char REGEXP_INRANGE[] = "]^-n\\";
415static char REGEXP_ABBR[] = "nrtebdoxuU";
416
417// Translate '\x' to its control character, except "\n", which is Magic.
418static int backslash_trans(int c)
419{
420  switch (c) {
421  case 'r':
422    return CAR;
423  case 't':
424    return TAB;
425  case 'e':
426    return ESC;
427  case 'b':
428    return BS;
429  }
430  return c;
431}
432
433enum {
434  CLASS_ALNUM = 0,
435  CLASS_ALPHA,
436  CLASS_BLANK,
437  CLASS_CNTRL,
438  CLASS_DIGIT,
439  CLASS_GRAPH,
440  CLASS_LOWER,
441  CLASS_PRINT,
442  CLASS_PUNCT,
443  CLASS_SPACE,
444  CLASS_UPPER,
445  CLASS_XDIGIT,
446  CLASS_TAB,
447  CLASS_RETURN,
448  CLASS_BACKSPACE,
449  CLASS_ESCAPE,
450  CLASS_IDENT,
451  CLASS_KEYWORD,
452  CLASS_FNAME,
453  CLASS_NONE = 99,
454};
455
456/// Check for a character class name "[:name:]".  "pp" points to the '['.
457/// Returns one of the CLASS_ items. CLASS_NONE means that no item was
458/// recognized.  Otherwise "pp" is advanced to after the item.
459static int get_char_class(char **pp)
460{
461  // must be sorted by the 'value' field because it is used by bsearch()!
462  static keyvalue_T char_class_tab[] = {
463    KEYVALUE_ENTRY(CLASS_ALNUM, "alnum:]"),
464    KEYVALUE_ENTRY(CLASS_ALPHA, "alpha:]"),
465    KEYVALUE_ENTRY(CLASS_BACKSPACE, "backspace:]"),
466    KEYVALUE_ENTRY(CLASS_BLANK, "blank:]"),
467    KEYVALUE_ENTRY(CLASS_CNTRL, "cntrl:]"),
468    KEYVALUE_ENTRY(CLASS_DIGIT, "digit:]"),
469    KEYVALUE_ENTRY(CLASS_ESCAPE, "escape:]"),
470    KEYVALUE_ENTRY(CLASS_FNAME, "fname:]"),
471    KEYVALUE_ENTRY(CLASS_GRAPH, "graph:]"),
472    KEYVALUE_ENTRY(CLASS_IDENT, "ident:]"),
473    KEYVALUE_ENTRY(CLASS_KEYWORD, "keyword:]"),
474    KEYVALUE_ENTRY(CLASS_LOWER, "lower:]"),
475    KEYVALUE_ENTRY(CLASS_PRINT, "print:]"),
476    KEYVALUE_ENTRY(CLASS_PUNCT, "punct:]"),
477    KEYVALUE_ENTRY(CLASS_RETURN, "return:]"),
478    KEYVALUE_ENTRY(CLASS_SPACE, "space:]"),
479    KEYVALUE_ENTRY(CLASS_TAB, "tab:]"),
480    KEYVALUE_ENTRY(CLASS_UPPER, "upper:]"),
481    KEYVALUE_ENTRY(CLASS_XDIGIT, "xdigit:]")
482  };
483
484  // check that the value of "pp" has a chance of matching
485  if ((*pp)[1] == ':' && ASCII_ISLOWER((*pp)[2])
486      && ASCII_ISLOWER((*pp)[3]) && ASCII_ISLOWER((*pp)[4])) {
487    // this function can be called repeatedly with the same value for "pp"
488    // so we cache the last found entry.
489    static keyvalue_T *last_entry = NULL;
490
491    keyvalue_T target = {
492      .key = 0,
493      .value = *pp + 2,
494      .length = 0,  // not used, see cmp_keyvalue_value_n()
495    };
496
497    keyvalue_T *entry;
498    if (last_entry != NULL && cmp_keyvalue_value_n(&target, last_entry) == 0) {
499      entry = last_entry;
500    } else {
501      entry = (keyvalue_T *)bsearch(&target, &char_class_tab,
502                                    ARRAY_SIZE(char_class_tab),
503                                    sizeof(char_class_tab[0]), cmp_keyvalue_value_n);
504    }
505    if (entry != NULL) {
506      last_entry = entry;
507      *pp += entry->length + 2;
508      return entry->key;
509    }
510  }
511  return CLASS_NONE;
512}
513
514// Specific version of character class functions.
515// Using a table to keep this fast.
516static int16_t class_tab[256];
517
518#define     RI_DIGIT    0x01
519#define     RI_HEX      0x02
520#define     RI_OCTAL    0x04
521#define     RI_WORD     0x08
522#define     RI_HEAD     0x10
523#define     RI_ALPHA    0x20
524#define     RI_LOWER    0x40
525#define     RI_UPPER    0x80
526#define     RI_WHITE    0x100
527
528static void init_class_tab(void)
529{
530  int i;
531  static int done = false;
532
533  if (done) {
534    return;
535  }
536
537  for (i = 0; i < 256; i++) {
538    if (i >= '0' && i <= '7') {
539      class_tab[i] = RI_DIGIT + RI_HEX + RI_OCTAL + RI_WORD;
540    } else if (i >= '8' && i <= '9') {
541      class_tab[i] = RI_DIGIT + RI_HEX + RI_WORD;
542    } else if (i >= 'a' && i <= 'f') {
543      class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
544    } else if (i >= 'g' && i <= 'z') {
545      class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_LOWER;
546    } else if (i >= 'A' && i <= 'F') {
547      class_tab[i] = RI_HEX + RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
548    } else if (i >= 'G' && i <= 'Z') {
549      class_tab[i] = RI_WORD + RI_HEAD + RI_ALPHA + RI_UPPER;
550    } else if (i == '_') {
551      class_tab[i] = RI_WORD + RI_HEAD;
552    } else {
553      class_tab[i] = 0;
554    }
555  }
556  class_tab[' '] |= RI_WHITE;
557  class_tab['\t'] |= RI_WHITE;
558  done = true;
559}
560
561#define ri_digit(c)    ((c) < 0x100 && (class_tab[c] & RI_DIGIT))
562#define ri_hex(c)      ((c) < 0x100 && (class_tab[c] & RI_HEX))
563#define ri_octal(c)    ((c) < 0x100 && (class_tab[c] & RI_OCTAL))
564#define ri_word(c)     ((c) < 0x100 && (class_tab[c] & RI_WORD))
565#define ri_head(c)     ((c) < 0x100 && (class_tab[c] & RI_HEAD))
566#define ri_alpha(c)    ((c) < 0x100 && (class_tab[c] & RI_ALPHA))
567#define ri_lower(c)    ((c) < 0x100 && (class_tab[c] & RI_LOWER))
568#define ri_upper(c)    ((c) < 0x100 && (class_tab[c] & RI_UPPER))
569#define ri_white(c)    ((c) < 0x100 && (class_tab[c] & RI_WHITE))
570
571// flags for regflags
572#define RF_ICASE    1   // ignore case
573#define RF_NOICASE  2   // don't ignore case
574#define RF_HASNL    4   // can match a NL
575#define RF_ICOMBINE 8   // ignore combining characters
576#define RF_LOOKBH   16  // uses "\@<=" or "\@<!"
577
578// Global work variables for vim_regcomp().
579
580static char *regparse;          ///< Input-scan pointer.
581static int regnpar;             ///< () count.
582static bool wants_nfa;          ///< regex should use NFA engine
583static int regnzpar;            ///< \z() count.
584static int re_has_z;            ///< \z item detected
585static unsigned regflags;       ///< RF_ flags for prog
586static int had_eol;             ///< true when EOL found by vim_regcomp()
587
588static magic_T reg_magic;       ///< magicness of the pattern
589
590static int reg_string;          // matching with a string instead of a buffer
591                                // line
592static int reg_strict;          // "[abc" is illegal
593
594// META contains all characters that may be magic, except '^' and '$'.
595
596// uncrustify:off
597
598// META[] is used often enough to justify turning it into a table.
599static const uint8_t META_flags[] = {
600    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
601    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
602//                 %  &     (  )  *  +        .
603    0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
604//     1  2  3  4  5  6  7  8  9        <  =  >  ?
605    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
606//  @  A     C  D     F     H  I     K  L  M     O
607    1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1,
608//  P        S     U  V  W  X     Z  [           _
609    1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1,
610//     a     c  d     f     h  i     k  l  m  n  o
611    0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
612//  p        s     u  v  w  x     z  {  |     ~
613    1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
614};
615
616// uncrustify:on
617
618static int curchr;              // currently parsed character
619// Previous character.  Note: prevchr is sometimes -1 when we are not at the
620// start, eg in /[ ^I]^ the pattern was never found even if it existed,
621// because ^ was taken to be magic -- webb
622static int prevchr;
623static int prevprevchr;         // previous-previous character
624static int nextchr;             // used for ungetchr()
625
626// arguments for reg()
627#define REG_NOPAREN     0       // toplevel reg()
628#define REG_PAREN       1       // \(\)
629#define REG_ZPAREN      2       // \z(\)
630#define REG_NPAREN      3       // \%(\)
631
632// Limit recursive parsing of nested regexp atoms to avoid using up the C stack.
633#define REG_MAX_PAREN_DEPTH     1000
634
635typedef struct {
636  char *regparse;
637  int prevchr_len;
638  int curchr;
639  int prevchr;
640  int prevprevchr;
641  int nextchr;
642  int at_start;
643  int prev_at_start;
644  int regnpar;
645} parse_state_T;
646
647static regengine_T bt_regengine;
648static regengine_T nfa_regengine;
649
650#include "regexp.c.generated.h"
651
652// Return true if compiled regular expression "prog" can match a line break.
653int re_multiline(const regprog_T *prog)
654  FUNC_ATTR_NONNULL_ALL
655{
656  return prog->regflags & RF_HASNL;
657}
658
659// Check for an equivalence class name "[=a=]".  "pp" points to the '['.
660// Returns a character representing the class. Zero means that no item was
661// recognized.  Otherwise "pp" is advanced to after the item.
662static int get_equi_class(char **pp)
663{
664  int c;
665  int l = 1;
666  char *p = *pp;
667
668  if (p[1] == '=' && p[2] != NUL) {
669    l = utfc_ptr2len(p + 2);
670    if (p[l + 2] == '=' && p[l + 3] == ']') {
671      c = utf_ptr2char(p + 2);
672      *pp += l + 4;
673      return c;
674    }
675  }
676  return 0;
677}
678
679// Check for a collating element "[.a.]".  "pp" points to the '['.
680// Returns a character. Zero means that no item was recognized.  Otherwise
681// "pp" is advanced to after the item.
682// Currently only single characters are recognized!
683static int get_coll_element(char **pp)
684{
685  int c;
686  int l = 1;
687  char *p = *pp;
688
689  if (p[0] != NUL && p[1] == '.' && p[2] != NUL) {
690    l = utfc_ptr2len(p + 2);
691    if (p[l + 2] == '.' && p[l + 3] == ']') {
692      c = utf_ptr2char(p + 2);
693      *pp += l + 4;
694      return c;
695    }
696  }
697  return 0;
698}
699
700static int reg_cpo_lit;  // 'cpoptions' contains 'l' flag
701
702static void get_cpo_flags(void)
703{
704  reg_cpo_lit = vim_strchr(p_cpo, kCpoLiteral) != NULL;
705}
706
707/// Skip over a "[]" range.
708/// "p" must point to the character after the '['.
709/// The returned pointer is on the matching ']', or the terminating NUL.
710static char *skip_anyof(char *p)
711{
712  int l;
713
714  if (*p == '^') {  // Complement of range.
715    p++;
716  }
717  if (*p == ']' || *p == '-') {
718    p++;
719  }
720  while (*p != NUL && *p != ']') {
721    if ((l = utfc_ptr2len(p)) > 1) {
722      p += l;
723    } else if (*p == '-') {
724      p++;
725      if (*p != ']' && *p != NUL) {
726        MB_PTR_ADV(p);
727      }
728    } else if (*p == '\\'
729               && (vim_strchr(REGEXP_INRANGE, (uint8_t)p[1]) != NULL
730                   || (!reg_cpo_lit
731                       && vim_strchr(REGEXP_ABBR, (uint8_t)p[1]) != NULL))) {
732      p += 2;
733    } else if (*p == '[') {
734      if (get_char_class(&p) == CLASS_NONE
735          && get_equi_class(&p) == 0
736          && get_coll_element(&p) == 0
737          && *p != NUL) {
738        p++;          // It is not a class name and not NUL
739      }
740    } else {
741      p++;
742    }
743  }
744
745  return p;
746}
747
748/// Skip past regular expression.
749/// Stop at end of "startp" or where "delim" is found ('/', '?', etc).
750/// Take care of characters with a backslash in front of it.
751/// Skip strings inside [ and ].
752char *skip_regexp(char *startp, int delim, int magic)
753{
754  return skip_regexp_ex(startp, delim, magic, NULL, NULL, NULL);
755}
756
757/// Call skip_regexp() and when the delimiter does not match give an error and
758/// return NULL.
759char *skip_regexp_err(char *startp, int delim, int magic)
760{
761  char *p = skip_regexp(startp, delim, magic);
762
763  if (*p != delim) {
764    semsg(_(e_missing_delimiter_after_search_pattern_str), startp);
765    return NULL;
766  }
767  return p;
768}
769
770/// skip_regexp() with extra arguments:
771/// When "newp" is not NULL and "dirc" is '?', make an allocated copy of the
772/// expression and change "\?" to "?".  If "*newp" is not NULL the expression
773/// is changed in-place.
774/// If a "\?" is changed to "?" then "dropped" is incremented, unless NULL.
775/// If "magic_val" is not NULL, returns the effective magicness of the pattern
776char *skip_regexp_ex(char *startp, int dirc, int magic, char **newp, int *dropped,
777                     magic_T *magic_val)
778{
779  magic_T mymagic;
780  char *p = startp;
781  size_t startplen = 0;
782
783  if (magic) {
784    mymagic = MAGIC_ON;
785  } else {
786    mymagic = MAGIC_OFF;
787  }
788  get_cpo_flags();
789
790  for (; p[0] != NUL; MB_PTR_ADV(p)) {
791    if (p[0] == dirc) {         // found end of regexp
792      break;
793    }
794    if ((p[0] == '[' && mymagic >= MAGIC_ON)
795        || (p[0] == '\\' && p[1] == '[' && mymagic <= MAGIC_OFF)) {
796      p = skip_anyof(p + 1);
797      if (p[0] == NUL) {
798        break;
799      }
800    } else if (p[0] == '\\' && p[1] != NUL) {
801      if (dirc == '?' && newp != NULL && p[1] == '?') {
802        // change "\?" to "?", make a copy first.
803        if (startplen == 0) {
804          startplen = strlen(startp);
805        }
806        if (*newp == NULL) {
807          *newp = xstrnsave(startp, startplen);
808          p = *newp + (p - startp);
809          startp = *newp;
810        }
811        if (dropped != NULL) {
812          (*dropped)++;
813        }
814        memmove(p, p + 1, startplen - (size_t)((p + 1) - startp) + 1);
815      } else {
816        p++;            // skip next character
817      }
818      if (*p == 'v') {
819        mymagic = MAGIC_ALL;
820      } else if (*p == 'V') {
821        mymagic = MAGIC_NONE;
822      }
823    }
824  }
825  if (magic_val != NULL) {
826    *magic_val = mymagic;
827  }
828  return p;
829}
830
831// variables used for parsing
832static int prevchr_len;    // byte length of previous char
833static int at_start;       // True when on the first character
834static int prev_at_start;  // True when on the second character
835
836// Start parsing at "str".
837static void initchr(char *str)
838{
839  regparse = str;
840  prevchr_len = 0;
841  curchr = prevprevchr = prevchr = nextchr = -1;
842  at_start = true;
843  prev_at_start = false;
844}
845
846// Save the current parse state, so that it can be restored and parsing
847// starts in the same state again.
848static void save_parse_state(parse_state_T *ps)
849{
850  ps->regparse = regparse;
851  ps->prevchr_len = prevchr_len;
852  ps->curchr = curchr;
853  ps->prevchr = prevchr;
854  ps->prevprevchr = prevprevchr;
855  ps->nextchr = nextchr;
856  ps->at_start = at_start;
857  ps->prev_at_start = prev_at_start;
858  ps->regnpar = regnpar;
859}
860
861// Restore a previously saved parse state.
862static void restore_parse_state(parse_state_T *ps)
863{
864  regparse = ps->regparse;
865  prevchr_len = ps->prevchr_len;
866  curchr = ps->curchr;
867  prevchr = ps->prevchr;
868  prevprevchr = ps->prevprevchr;
869  nextchr = ps->nextchr;
870  at_start = ps->at_start;
871  prev_at_start = ps->prev_at_start;
872  regnpar = ps->regnpar;
873}
874
875// Get the next character without advancing.
876static int peekchr(void)
877{
878  static int after_slash = false;
879
880  if (curchr != -1) {
881    return curchr;
882  }
883
884  switch (curchr = (uint8_t)regparse[0]) {
885  case '.':
886  case '[':
887  case '~':
888    // magic when 'magic' is on
889    if (reg_magic >= MAGIC_ON) {
890      curchr = Magic(curchr);
891    }
892    break;
893  case '(':
894  case ')':
895  case '{':
896  case '%':
897  case '+':
898  case '=':
899  case '?':
900  case '@':
901  case '!':
902  case '&':
903  case '|':
904  case '<':
905  case '>':
906  case '#':           // future ext.
907  case '"':           // future ext.
908  case '\'':          // future ext.
909  case ',':           // future ext.
910  case '-':           // future ext.
911  case ':':           // future ext.
912  case ';':           // future ext.
913  case '`':           // future ext.
914  case '/':           // Can't be used in / command
915    // magic only after "\v"
916    if (reg_magic == MAGIC_ALL) {
917      curchr = Magic(curchr);
918    }
919    break;
920  case '*':
921    // * is not magic as the very first character, eg "?*ptr", when
922    // after '^', eg "/^*ptr" and when after "\(", "\|", "\&".  But
923    // "\(\*" is not magic, thus must be magic if "after_slash"
924    if (reg_magic >= MAGIC_ON
925        && !at_start
926        && !(prev_at_start && prevchr == Magic('^'))
927        && (after_slash
928            || (prevchr != Magic('(')
929                && prevchr != Magic('&')
930                && prevchr != Magic('|')))) {
931      curchr = Magic('*');
932    }
933    break;
934  case '^':
935    // '^' is only magic as the very first character and if it's after
936    // "\(", "\|", "\&' or "\n"
937    if (reg_magic >= MAGIC_OFF
938        && (at_start
939            || reg_magic == MAGIC_ALL
940            || prevchr == Magic('(')
941            || prevchr == Magic('|')
942            || prevchr == Magic('&')
943            || prevchr == Magic('n')
944            || (no_Magic(prevchr) == '('
945                && prevprevchr == Magic('%')))) {
946      curchr = Magic('^');
947      at_start = true;
948      prev_at_start = false;
949    }
950    break;
951  case '$':
952    // '$' is only magic as the very last char and if it's in front of
953    // either "\|", "\)", "\&", or "\n"
954    if (reg_magic >= MAGIC_OFF) {
955      uint8_t *p = (uint8_t *)regparse + 1;
956      bool is_magic_all = (reg_magic == MAGIC_ALL);
957
958      // ignore \c \C \m \M \v \V and \Z after '$'
959      while (p[0] == '\\' && (p[1] == 'c' || p[1] == 'C'
960                              || p[1] == 'm' || p[1] == 'M'
961                              || p[1] == 'v' || p[1] == 'V'
962                              || p[1] == 'Z')) {
963        if (p[1] == 'v') {
964          is_magic_all = true;
965        } else if (p[1] == 'm' || p[1] == 'M' || p[1] == 'V') {
966          is_magic_all = false;
967        }
968        p += 2;
969      }
970      if (p[0] == NUL
971          || (p[0] == '\\'
972              && (p[1] == '|' || p[1] == '&' || p[1] == ')'
973                  || p[1] == 'n'))
974          || (is_magic_all
975              && (p[0] == '|' || p[0] == '&' || p[0] == ')'))
976          || reg_magic == MAGIC_ALL) {
977        curchr = Magic('$');
978      }
979    }
980    break;
981  case '\\': {
982    int c = (uint8_t)regparse[1];
983
984    if (c == NUL) {
985      curchr = '\\';  // trailing '\'
986    } else if (c <= '~' && META_flags[c]) {
987      // META contains everything that may be magic sometimes,
988      // except ^ and $ ("\^" and "\$" are only magic after
989      // "\V").  We now fetch the next character and toggle its
990      // magicness.  Therefore, \ is so meta-magic that it is
991      // not in META.
992      curchr = -1;
993      prev_at_start = at_start;
994      at_start = false;  // be able to say "/\*ptr"
995      regparse++;
996      after_slash++;
997      (void)peekchr();
998      regparse--;
999      after_slash--;
1000      curchr = toggle_Magic(curchr);
1001    } else if (vim_strchr(REGEXP_ABBR, c)) {
1002      // Handle abbreviations, like "\t" for TAB -- webb
1003      curchr = backslash_trans(c);
1004    } else if (reg_magic == MAGIC_NONE && (c == '$' || c == '^')) {
1005      curchr = toggle_Magic(c);
1006    } else {
1007      // Next character can never be (made) magic?
1008      // Then backslashing it won't do anything.
1009      curchr = c >= 0x80 ? utf_ptr2char(regparse + 1) : c;
1010    }
1011    break;
1012  }
1013
1014  default:
1015    // curchr already holds regparse[0]; only a multi-byte lead byte needs decoding.
1016    if (curchr >= 0x80) {
1017      curchr = utf_ptr2char(regparse);
1018    }
1019  }
1020
1021  return curchr;
1022}
1023
1024// Eat one lexed character.  Do this in a way that we can undo it.
1025static void skipchr(void)
1026{
1027  // peekchr() eats a backslash, do the same here
1028  if (*regparse == '\\') {
1029    prevchr_len = 1;
1030  } else {
1031    prevchr_len = 0;
1032  }
1033  if (regparse[prevchr_len] != NUL) {
1034    // Exclude composing chars that utfc_ptr2len does include.  A byte
1035    // below 0x80 is always a single character.
1036    if ((uint8_t)regparse[prevchr_len] < 0x80) {
1037      prevchr_len++;
1038    } else {
1039      prevchr_len += utf_ptr2len(regparse + prevchr_len);
1040    }
1041  }
1042  regparse += prevchr_len;
1043  prev_at_start = at_start;
1044  at_start = false;
1045  prevprevchr = prevchr;
1046  prevchr = curchr;
1047  curchr = nextchr;         // use previously unget char, or -1
1048  nextchr = -1;
1049}
1050
1051// Skip a character while keeping the value of prev_at_start for at_start.
1052// prevchr and prevprevchr are also kept.
1053static void skipchr_keepstart(void)
1054{
1055  int as = prev_at_start;
1056  int pr = prevchr;
1057  int prpr = prevprevchr;
1058
1059  skipchr();
1060  at_start = as;
1061  prevchr = pr;
1062  prevprevchr = prpr;
1063}
1064
1065// Get the next character from the pattern. We know about magic and such, so
1066// therefore we need a lexical analyzer.
1067static int getchr(void)
1068{
1069  int chr = peekchr();
1070
1071  skipchr();
1072  return chr;
1073}
1074
1075// put character back.  Works only once!
1076static void ungetchr(void)
1077{
1078  nextchr = curchr;
1079  curchr = prevchr;
1080  prevchr = prevprevchr;
1081  at_start = prev_at_start;
1082  prev_at_start = false;
1083
1084  // Backup regparse, so that it's at the same position as before the
1085  // getchr().
1086  regparse -= prevchr_len;
1087}
1088
1089// Get and return the value of the hex string at the current position.
1090// Return -1 if there is no valid hex number.
1091// The position is updated:
1092//     blahblah\%x20asdf
1093//         before-^ ^-after
1094// The parameter controls the maximum number of input characters. This will be
1095// 2 when reading a \%x20 sequence and 4 when reading a \%u20AC sequence.
1096static int64_t gethexchrs(int maxinputlen)
1097{
1098  int64_t nr = 0;
1099  int c;
1100  int i;
1101
1102  for (i = 0; i < maxinputlen; i++) {
1103    c = (uint8_t)regparse[0];
1104    if (!ascii_isxdigit(c)) {
1105      break;
1106    }
1107    nr <<= 4;
1108    nr |= hex2nr(c);
1109    regparse++;
1110  }
1111
1112  if (i == 0) {
1113    return -1;
1114  }
1115  return nr;
1116}
1117
1118// Get and return the value of the decimal string immediately after the
1119// current position. Return -1 for invalid.  Consumes all digits.
1120static int64_t getdecchrs(void)
1121{
1122  int64_t nr = 0;
1123  int c;
1124  int i;
1125
1126  for (i = 0;; i++) {
1127    c = (uint8_t)regparse[0];
1128    if (c < '0' || c > '9') {
1129      break;
1130    }
1131    nr *= 10;
1132    nr += c - '0';
1133    regparse++;
1134    curchr = -1;     // no longer valid
1135  }
1136
1137  if (i == 0) {
1138    return -1;
1139  }
1140  return nr;
1141}
1142
1143// get and return the value of the octal string immediately after the current
1144// position. Return -1 for invalid, or 0-255 for valid. Smart enough to handle
1145// numbers > 377 correctly (for example, 400 is treated as 40) and doesn't
1146// treat 8 or 9 as recognised characters. Position is updated:
1147//     blahblah\%o210asdf
1148//         before-^  ^-after
1149static int64_t getoctchrs(void)
1150{
1151  int64_t nr = 0;
1152  int c;
1153  int i;
1154
1155  for (i = 0; i < 3 && nr < 040; i++) {
1156    c = (uint8_t)regparse[0];
1157    if (c < '0' || c > '7') {
1158      break;
1159    }
1160    nr <<= 3;
1161    nr |= hex2nr(c);
1162    regparse++;
1163  }
1164
1165  if (i == 0) {
1166    return -1;
1167  }
1168  return nr;
1169}
1170
1171// read_limits - Read two integers to be taken as a minimum and maximum.
1172// If the first character is '-', then the range is reversed.
1173// Should end with 'end'.  If minval is missing, zero is default, if maxval is
1174// missing, a very big number is the default.
1175static int read_limits(int *minval, int *maxval)
1176{
1177  int reverse = false;
1178  char *first_char;
1179  int tmp;
1180
1181  if (*regparse == '-') {
1182    // Starts with '-', so reverse the range later.
1183    regparse++;
1184    reverse = true;
1185  }
1186  first_char = regparse;
1187  *minval = getdigits_int(&regparse, false, 0);
1188  if (*regparse == ',') {           // There is a comma.
1189    if (ascii_isdigit(*++regparse)) {
1190      *maxval = getdigits_int(&regparse, false, MAX_LIMIT);
1191    } else {
1192      *maxval = MAX_LIMIT;
1193    }
1194  } else if (ascii_isdigit(*first_char)) {
1195    *maxval = *minval;              // It was \{n} or \{-n}
1196  } else {
1197    *maxval = MAX_LIMIT;            // It was \{} or \{-}
1198  }
1199  if (*regparse == '\\') {
1200    regparse++;         // Allow either \{...} or \{...\}
1201  }
1202  if (*regparse != '}') {
1203    EMSG2_RET_FAIL(_("E554: Syntax error in %s{...}"), reg_magic == MAGIC_ALL);
1204  }
1205
1206  // Reverse the range if there was a '-', or make sure it is in the right
1207  // order otherwise.
1208  if ((!reverse && *minval > *maxval) || (reverse && *minval < *maxval)) {
1209    tmp = *minval;
1210    *minval = *maxval;
1211    *maxval = tmp;
1212  }
1213  skipchr();            // let's be friends with the lexer again
1214  return OK;
1215}
1216
1217// vim_regexec and friends
1218
1219// Global work variables for vim_regexec().
1220
1221// Sometimes need to save a copy of a line.  Since alloc()/free() is very
1222// slow, we keep one allocated piece of memory and only re-allocate it when
1223// it's too small.  It's freed in bt_regexec_both() when finished.
1224static uint8_t *reg_tofree = NULL;
1225static unsigned reg_tofreelen;
1226
1227// Structure used to store the execution state of the regex engine.
1228// Which ones are set depends on whether a single-line or multi-line match is
1229// done:
1230//                      single-line             multi-line
1231// reg_match            &regmatch_T             NULL
1232// reg_mmatch           NULL                    &regmmatch_T
1233// reg_startp           reg_match->startp       <invalid>
1234// reg_endp             reg_match->endp         <invalid>
1235// reg_startpos         <invalid>               reg_mmatch->startpos
1236// reg_endpos           <invalid>               reg_mmatch->endpos
1237// reg_win              NULL                    window in which to search
1238// reg_buf              curbuf                  buffer in which to search
1239// reg_firstlnum        <invalid>               first line in which to search
1240// reg_maxline          0                       last line nr
1241// reg_line_lbr         false or true           false
1242typedef struct {
1243  regmatch_T *reg_match;
1244  regmmatch_T *reg_mmatch;
1245
1246  uint8_t **reg_startp;
1247  uint8_t **reg_endp;
1248  lpos_T *reg_startpos;
1249  lpos_T *reg_endpos;
1250
1251  win_T *reg_win;
1252  buf_T *reg_buf;
1253  linenr_T reg_firstlnum;
1254  linenr_T reg_maxline;
1255  bool reg_line_lbr;  // "\n" in string is line break
1256
1257  // The current match-position is remembered with these variables:
1258  linenr_T lnum;  ///< line number, relative to first line
1259  uint8_t *line;   ///< start of current line
1260  uint8_t *input;  ///< current input, points into "line"
1261
1262  int need_clear_subexpr;   ///< subexpressions still need to be cleared
1263  int need_clear_zsubexpr;  ///< extmatch subexpressions still need to be
1264                            ///< cleared
1265
1266  // Internal copy of 'ignorecase'.  It is set at each call to vim_regexec().
1267  // Normally it gets the value of "rm_ic" or "rmm_ic", but when the pattern
1268  // contains '\c' or '\C' the value is overruled.
1269  bool reg_ic;
1270
1271  // Similar to "reg_ic", but only for 'combining' characters.  Set with \Z
1272  // flag in the regexp.  Defaults to false, always.
1273  bool reg_icombine;
1274
1275  bool reg_nobreak;
1276
1277  // Copy of "rmm_maxcol": maximum column to search for a match.  Zero when
1278  // there is no maximum.
1279  colnr_T reg_maxcol;
1280
1281  // State for the NFA engine regexec.
1282  int nfa_has_zend;     ///< NFA regexp \ze operator encountered.
1283  int nfa_has_backref;  ///< NFA regexp \1 .. \9 encountered.
1284  int nfa_nsubexpr;     ///< Number of sub expressions actually being used
1285                        ///< during execution. 1 if only the whole match
1286                        ///< (subexpr 0) is used.
1287  // listid is global, so that it increases on recursive calls to
1288  // nfa_regmatch(), which means we don't have to clear the lastlist field of
1289  // all the states.
1290  int nfa_listid;
1291  int nfa_alt_listid;
1292
1293  int nfa_has_zsubexpr;  ///< NFA regexp has \z( ), set zsubexpr.
1294} regexec_T;
1295
1296static regexec_T rex;
1297static bool rex_in_use = false;
1298
1299static void reg_breakcheck(void)
1300{
1301  if (!rex.reg_nobreak) {
1302    fast_breakcheck();
1303  }
1304}
1305
1306// Return true if character 'c' is included in 'iskeyword' option for
1307// "reg_buf" buffer.
1308static bool reg_iswordc(int c)
1309{
1310  return vim_iswordc_buf(c, rex.reg_buf);
1311}
1312
1313static bool can_f_submatch = false;  ///< true when submatch() can be used
1314
1315/// These pointers are used for reg_submatch().  Needed for when the
1316/// substitution string is an expression that contains a call to substitute()
1317/// and submatch().
1318typedef struct {
1319  regmatch_T *sm_match;
1320  regmmatch_T *sm_mmatch;
1321  linenr_T sm_firstlnum;
1322  linenr_T sm_maxline;
1323  int sm_line_lbr;
1324} regsubmatch_T;
1325
1326static regsubmatch_T rsm;  ///< can only be used when can_f_submatch is true
1327
1328/// Common code for reg_getline(), reg_getline_len(), reg_getline_submatch() and
1329/// reg_getline_submatch_len().
1330///
1331/// @param flags  a bitmask that controls what info is to be returned
1332///               and whether or not submatch is in effect.
1333static void reg_getline_common(linenr_T lnum, reg_getline_flags_T flags, char **line,
1334                               colnr_T *length)
1335{
1336  bool get_line = flags & RGLF_LINE;
1337  bool get_length = flags & RGLF_LENGTH;
1338  linenr_T firstlnum;
1339  linenr_T maxline;
1340
1341  if (flags & RGLF_SUBMATCH) {
1342    firstlnum = rsm.sm_firstlnum + lnum;
1343    maxline = rsm.sm_maxline;
1344  } else {
1345    firstlnum = rex.reg_firstlnum + lnum;
1346    maxline = rex.reg_maxline;
1347  }
1348
1349  // when looking behind for a match/no-match lnum is negative. but we
1350  // can't go before line 1.
1351  if (firstlnum < 1) {
1352    if (get_line) {
1353      *line = NULL;
1354    }
1355    if (get_length) {
1356      *length = 0;
1357    }
1358
1359    return;
1360  }
1361
1362  if (lnum > maxline) {
1363    // must have matched the "\n" in the last line.
1364    if (get_line) {
1365      *line = "";
1366    }
1367    if (get_length) {
1368      *length = 0;
1369    }
1370
1371    return;
1372  }
1373
1374  if (get_line) {
1375    *line = ml_get_buf(rex.reg_buf, firstlnum);
1376  }
1377  if (get_length) {
1378    *length = ml_get_buf_len(rex.reg_buf, firstlnum);
1379  }
1380}
1381
1382/// Get pointer to the line "lnum", which is relative to "reg_firstlnum".
1383static char *reg_getline(linenr_T lnum)
1384{
1385  char *line;
1386  reg_getline_common(lnum, RGLF_LINE, &line, NULL);
1387  return line;
1388}
1389
1390/// Get length of line "lnum", which is relative to "reg_firstlnum".
1391static colnr_T reg_getline_len(linenr_T lnum)
1392{
1393  colnr_T length;
1394  reg_getline_common(lnum, RGLF_LENGTH, NULL, &length);
1395  return length;
1396}
1397
1398static uint8_t *reg_startzp[NSUBEXP];  // Workspace to mark beginning
1399static uint8_t *reg_endzp[NSUBEXP];    //   and end of \z(...\) matches
1400static lpos_T reg_startzpos[NSUBEXP];   // idem, beginning pos
1401static lpos_T reg_endzpos[NSUBEXP];     // idem, end pos
1402
1403// true if using multi-line regexp.
1404#define REG_MULTI       (rex.reg_match == NULL)
1405
1406// Create a new extmatch and mark it as referenced once.
1407static reg_extmatch_T *make_extmatch(void)
1408  FUNC_ATTR_NONNULL_RET
1409{
1410  reg_extmatch_T *em = xcalloc(1, sizeof(reg_extmatch_T));
1411  em->refcnt = 1;
1412  return em;
1413}
1414
1415// Add a reference to an extmatch.
1416reg_extmatch_T *ref_extmatch(reg_extmatch_T *em)
1417{
1418  if (em != NULL) {
1419    em->refcnt++;
1420  }
1421  return em;
1422}
1423
1424// Remove a reference to an extmatch.  If there are no references left, free
1425// the info.
1426void unref_extmatch(reg_extmatch_T *em)
1427{
1428  int i;
1429
1430  if (em != NULL && --em->refcnt <= 0) {
1431    for (i = 0; i < NSUBEXP; i++) {
1432      xfree(em->matches[i]);
1433    }
1434    xfree(em);
1435  }
1436}
1437
1438// Get class of previous character.
1439static int reg_prev_class(void)
1440{
1441  if (rex.input > rex.line) {
1442    return mb_get_class_tab((char *)rex.input - 1 -
1443                            utf_head_off((char *)rex.line, (char *)rex.input - 1),
1444                            rex.reg_buf->b_chartab);
1445  }
1446  return -1;
1447}
1448
1449// Return true if the current rex.input position matches the Visual area.
1450static bool reg_match_visual(void)
1451{
1452  pos_T top, bot;
1453  linenr_T lnum;
1454  colnr_T col;
1455  win_T *wp = rex.reg_win == NULL ? curwin : rex.reg_win;
1456  int mode;
1457  colnr_T start, end;
1458  colnr_T start2, end2;
1459  colnr_T curswant;
1460
1461  // Check if the buffer is the current buffer and not using a string.
1462  if (rex.reg_buf != curbuf || Visual.start.lnum == 0 || !REG_MULTI) {
1463    return false;
1464  }
1465
1466  if (Visual.active) {
1467    if (lt(Visual.start, wp->w_cursor)) {
1468      top = Visual.start;
1469      bot = wp->w_cursor;
1470    } else {
1471      top = wp->w_cursor;
1472      bot = Visual.start;
1473    }
1474    mode = Visual.mode;
1475    curswant = wp->w_curswant;
1476  } else {
1477    if (lt(curbuf->b_visual.vi_start, curbuf->b_visual.vi_end)) {
1478      top = curbuf->b_visual.vi_start;
1479      bot = curbuf->b_visual.vi_end;
1480    } else {
1481      top = curbuf->b_visual.vi_end;
1482      bot = curbuf->b_visual.vi_start;
1483    }
1484    // a substitute command may have removed some lines
1485    if (bot.lnum > curbuf->b_ml.ml_line_count) {
1486      bot.lnum = curbuf->b_ml.ml_line_count;
1487    }
1488    mode = curbuf->b_visual.vi_mode;
1489    curswant = curbuf->b_visual.vi_curswant;
1490  }
1491  lnum = rex.lnum + rex.reg_firstlnum;
1492  if (lnum < top.lnum || lnum > bot.lnum) {
1493    return false;
1494  }
1495
1496  col = (colnr_T)(rex.input - rex.line);
1497  if (mode == 'v') {
1498    if ((lnum == top.lnum && col < top.col)
1499        || (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e'))) {
1500      return false;
1501    }
1502  } else if (mode == Ctrl_V) {
1503    getvvcol(wp, &top, &start, NULL, &end, 0);
1504    getvvcol(wp, &bot, &start2, NULL, &end2, 0);
1505    if (start2 < start) {
1506      start = start2;
1507    }
1508    if (end2 > end) {
1509      end = end2;
1510    }
1511    if (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL) {
1512      end = MAXCOL;
1513    }
1514
1515    // getvvcol() flushes rex.line, need to get it again
1516    rex.line = (uint8_t *)reg_getline(rex.lnum);
1517    rex.input = rex.line + col;
1518
1519    colnr_T cols = win_linetabsize(wp, rex.reg_firstlnum + rex.lnum, (char *)rex.line, col);
1520    if (cols < start || cols > end - (*p_sel == 'e')) {
1521      return false;
1522    }
1523  }
1524  return true;
1525}
1526
1527// Check the regexp program for its magic number.
1528// Return true if it's wrong.
1529static int prog_magic_wrong(void)
1530{
1531  regprog_T *prog;
1532
1533  prog = REG_MULTI ? rex.reg_mmatch->regprog : rex.reg_match->regprog;
1534  if (prog->engine == &nfa_regengine) {
1535    // For NFA matcher we don't check the magic
1536    return false;
1537  }
1538
1539  if (UCHARAT(((bt_regprog_T *)prog)->program) != REGMAGIC) {
1540    emsg(_(e_re_corr));
1541    return true;
1542  }
1543  return false;
1544}
1545
1546// Cleanup the subexpressions, if this wasn't done yet.
1547// This construction is used to clear the subexpressions only when they are
1548// used (to increase speed).
1549static void cleanup_subexpr(void)
1550{
1551  if (!rex.need_clear_subexpr) {
1552    return;
1553  }
1554
1555  if (REG_MULTI) {
1556    // Use 0xff to set lnum to -1
1557    memset(rex.reg_startpos, 0xff, sizeof(lpos_T) * NSUBEXP);
1558    memset(rex.reg_endpos, 0xff, sizeof(lpos_T) * NSUBEXP);
1559  } else {
1560    memset(rex.reg_startp, 0, sizeof(char *) * NSUBEXP);
1561    memset(rex.reg_endp, 0, sizeof(char *) * NSUBEXP);
1562  }
1563  rex.need_clear_subexpr = false;
1564}
1565
1566static void cleanup_zsubexpr(void)
1567{
1568  if (!rex.need_clear_zsubexpr) {
1569    return;
1570  }
1571
1572  if (REG_MULTI) {
1573    // Use 0xff to set lnum to -1
1574    memset(reg_startzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
1575    memset(reg_endzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
1576  } else {
1577    memset(reg_startzp, 0, sizeof(char *) * NSUBEXP);
1578    memset(reg_endzp, 0, sizeof(char *) * NSUBEXP);
1579  }
1580  rex.need_clear_zsubexpr = false;
1581}
1582
1583// Advance rex.lnum, rex.line and rex.input to the next line.
1584static void reg_nextline(void)
1585{
1586  rex.line = (uint8_t *)reg_getline(++rex.lnum);
1587  rex.input = rex.line;
1588  reg_breakcheck();
1589}
1590
1591// Check whether a backreference matches.
1592// Returns RA_FAIL, RA_NOMATCH or RA_MATCH.
1593// If "bytelen" is not NULL, it is set to the byte length of the match in the
1594// last line.
1595// Optional: ignore case if rex.reg_ic is set.
1596static int match_with_backref(linenr_T start_lnum, colnr_T start_col, linenr_T end_lnum,
1597                              colnr_T end_col, int *bytelen)
1598{
1599  linenr_T clnum = start_lnum;
1600  colnr_T ccol = start_col;
1601  int len;
1602  char *p;
1603
1604  if (bytelen != NULL) {
1605    *bytelen = 0;
1606  }
1607  while (true) {
1608    // Since getting one line may invalidate the other, need to make copy.
1609    // Slow!
1610    if (rex.line != reg_tofree) {
1611      len = (int)strlen((char *)rex.line);
1612      if (reg_tofree == NULL || len >= (int)reg_tofreelen) {
1613        len += 50;              // get some extra
1614        xfree(reg_tofree);
1615        reg_tofree = xmalloc((size_t)len);
1616        reg_tofreelen = (unsigned)len;
1617      }
1618      STRCPY(reg_tofree, rex.line);
1619      rex.input = reg_tofree + (rex.input - rex.line);
1620      rex.line = reg_tofree;
1621    }
1622
1623    // Get the line to compare with.
1624    p = reg_getline(clnum);
1625    assert(p);
1626
1627    if (clnum == end_lnum) {
1628      len = end_col - ccol;
1629    } else {
1630      len = reg_getline_len(clnum) - ccol;
1631    }
1632
1633    if ((!rex.reg_ic && cstrncmp(p + ccol, (char *)rex.input, &len) != 0)
1634        || (rex.reg_ic && mb_strnicmp(p + ccol, (char *)rex.input, (size_t)len) != 0)) {
1635      return RA_NOMATCH;  // doesn't match
1636    }
1637    if (bytelen != NULL) {
1638      *bytelen += len;
1639    }
1640    if (clnum == end_lnum) {
1641      break;  // match and at end!
1642    }
1643    if (rex.lnum >= rex.reg_maxline) {
1644      return RA_NOMATCH;  // text too short
1645    }
1646
1647    // Advance to next line.
1648    reg_nextline();
1649    if (bytelen != NULL) {
1650      *bytelen = 0;
1651    }
1652    clnum++;
1653    ccol = 0;
1654    if (got_int) {
1655      return RA_FAIL;
1656    }
1657  }
1658
1659  // found a match!  Note that rex.line may now point to a copy of the line,
1660  // that should not matter.
1661  return RA_MATCH;
1662}
1663
1664/// Used in a place where no * or \+ can follow.
1665static bool re_mult_next(char *what)
1666{
1667  if (re_multi_type(peekchr()) == MULTI_MULT) {
1668    semsg(_("E888: (NFA regexp) cannot repeat %s"), what);
1669    rc_did_emsg = true;
1670    return false;
1671  }
1672  return true;
1673}
1674
1675typedef struct {
1676  int a, b, c;
1677} decomp_T;
1678
1679// 0xfb20 - 0xfb4f
1680static decomp_T decomp_table[0xfb4f - 0xfb20 + 1] = {
1681  { 0x5e2, 0, 0 },          // 0xfb20       alt ayin
1682  { 0x5d0, 0, 0 },          // 0xfb21       alt alef
1683  { 0x5d3, 0, 0 },          // 0xfb22       alt dalet
1684  { 0x5d4, 0, 0 },          // 0xfb23       alt he
1685  { 0x5db, 0, 0 },          // 0xfb24       alt kaf
1686  { 0x5dc, 0, 0 },          // 0xfb25       alt lamed
1687  { 0x5dd, 0, 0 },          // 0xfb26       alt mem-sofit
1688  { 0x5e8, 0, 0 },          // 0xfb27       alt resh
1689  { 0x5ea, 0, 0 },          // 0xfb28       alt tav
1690  { '+', 0, 0 },            // 0xfb29       alt plus
1691  { 0x5e9, 0x5c1, 0 },      // 0xfb2a       shin+shin-dot
1692  { 0x5e9, 0x5c2, 0 },      // 0xfb2b       shin+sin-dot
1693  { 0x5e9, 0x5c1, 0x5bc },  // 0xfb2c       shin+shin-dot+dagesh
1694  { 0x5e9, 0x5c2, 0x5bc },  // 0xfb2d       shin+sin-dot+dagesh
1695  { 0x5d0, 0x5b7, 0 },      // 0xfb2e       alef+patah
1696  { 0x5d0, 0x5b8, 0 },      // 0xfb2f       alef+qamats
1697  { 0x5d0, 0x5b4, 0 },      // 0xfb30       alef+hiriq
1698  { 0x5d1, 0x5bc, 0 },      // 0xfb31       bet+dagesh
1699  { 0x5d2, 0x5bc, 0 },      // 0xfb32       gimel+dagesh
1700  { 0x5d3, 0x5bc, 0 },      // 0xfb33       dalet+dagesh
1701  { 0x5d4, 0x5bc, 0 },      // 0xfb34       he+dagesh
1702  { 0x5d5, 0x5bc, 0 },      // 0xfb35       vav+dagesh
1703  { 0x5d6, 0x5bc, 0 },      // 0xfb36       zayin+dagesh
1704  { 0xfb37, 0, 0 },         // 0xfb37 -- UNUSED
1705  { 0x5d8, 0x5bc, 0 },      // 0xfb38       tet+dagesh
1706  { 0x5d9, 0x5bc, 0 },      // 0xfb39       yud+dagesh
1707  { 0x5da, 0x5bc, 0 },      // 0xfb3a       kaf sofit+dagesh
1708  { 0x5db, 0x5bc, 0 },      // 0xfb3b       kaf+dagesh
1709  { 0x5dc, 0x5bc, 0 },      // 0xfb3c       lamed+dagesh
1710  { 0xfb3d, 0, 0 },         // 0xfb3d -- UNUSED
1711  { 0x5de, 0x5bc, 0 },      // 0xfb3e       mem+dagesh
1712  { 0xfb3f, 0, 0 },         // 0xfb3f -- UNUSED
1713  { 0x5e0, 0x5bc, 0 },      // 0xfb40       nun+dagesh
1714  { 0x5e1, 0x5bc, 0 },      // 0xfb41       samech+dagesh
1715  { 0xfb42, 0, 0 },         // 0xfb42 -- UNUSED
1716  { 0x5e3, 0x5bc, 0 },      // 0xfb43       pe sofit+dagesh
1717  { 0x5e4, 0x5bc, 0 },      // 0xfb44       pe+dagesh
1718  { 0xfb45, 0, 0 },         // 0xfb45 -- UNUSED
1719  { 0x5e6, 0x5bc, 0 },      // 0xfb46       tsadi+dagesh
1720  { 0x5e7, 0x5bc, 0 },      // 0xfb47       qof+dagesh
1721  { 0x5e8, 0x5bc, 0 },      // 0xfb48       resh+dagesh
1722  { 0x5e9, 0x5bc, 0 },      // 0xfb49       shin+dagesh
1723  { 0x5ea, 0x5bc, 0 },      // 0xfb4a       tav+dagesh
1724  { 0x5d5, 0x5b9, 0 },      // 0xfb4b       vav+holam
1725  { 0x5d1, 0x5bf, 0 },      // 0xfb4c       bet+rafe
1726  { 0x5db, 0x5bf, 0 },      // 0xfb4d       kaf+rafe
1727  { 0x5e4, 0x5bf, 0 },      // 0xfb4e       pe+rafe
1728  { 0x5d0, 0x5dc, 0 }       // 0xfb4f       alef-lamed
1729};
1730
1731static void mb_decompose(int c, int *c1, int *c2, int *c3)
1732{
1733  decomp_T d;
1734
1735  if (c >= 0xfb20 && c <= 0xfb4f) {
1736    d = decomp_table[c - 0xfb20];
1737    *c1 = d.a;
1738    *c2 = d.b;
1739    *c3 = d.c;
1740  } else {
1741    *c1 = c;
1742    *c2 = 0;
1743    *c3 = 0;
1744  }
1745}
1746
1747/// Compare two strings, ignore case if rex.reg_ic set.
1748/// Return 0 if strings match, non-zero otherwise.
1749/// Correct the length "*n" when composing characters are ignored
1750/// or when both utf codepoints are considered equal because of
1751/// case-folding but have different length (e.g. 's' and 'ſ')
1752static int cstrncmp(char *s1, char *s2, int *n)
1753{
1754  int result;
1755
1756  if (!rex.reg_ic) {
1757    result = strncmp(s1, s2, (size_t)(*n));
1758  } else {
1759    char *p = s1;
1760    int n2 = 0;
1761    int n1 = *n;
1762    // count the number of characters for byte-length of s1
1763    while (n1 > 0 && *p != NUL) {
1764      n1 -= utfc_ptr2len(p);
1765      MB_PTR_ADV(p);
1766      n2++;
1767    }
1768    // count the number of bytes to advance the same number of chars for s2
1769    p = s2;
1770    while (n2-- > 0 && *p != NUL) {
1771      MB_PTR_ADV(p);
1772    }
1773
1774    n2 = (int)(p - s2);
1775
1776    result = utf_strnicmp(s1, s2, (size_t)(*n), (size_t)n2);
1777    if (result == 0 && n2 < *n) {
1778      *n = n2;
1779    }
1780  }
1781
1782  // if it failed and it's utf8 and we want to combineignore:
1783  if (result != 0 && rex.reg_icombine) {
1784    const char *str1, *str2;
1785    int c1, c2, c11, c12;
1786    int junk;
1787
1788    // we have to handle the strcmp ourselves, since it is necessary to
1789    // deal with the composing characters by ignoring them:
1790    str1 = s1;
1791    str2 = s2;
1792    c1 = c2 = 0;
1793    while ((int)(str1 - s1) < *n) {
1794      c1 = mb_ptr2char_adv(&str1);
1795      c2 = mb_ptr2char_adv(&str2);
1796
1797      // decompose the character if necessary, into 'base' characters
1798      // because I don't care about Arabic, I will hard-code the Hebrew
1799      // which I *do* care about!  So sue me...
1800      if (c1 != c2 && (!rex.reg_ic || utf_fold(c1) != utf_fold(c2))) {
1801        // decomposition necessary?
1802        mb_decompose(c1, &c11, &junk, &junk);
1803        mb_decompose(c2, &c12, &junk, &junk);
1804        c1 = c11;
1805        c2 = c12;
1806        if (c11 != c12 && (!rex.reg_ic || utf_fold(c11) != utf_fold(c12))) {
1807          break;
1808        }
1809      }
1810    }
1811    result = c2 - c1;
1812    if (result == 0) {
1813      *n = (int)(str2 - s2);
1814    }
1815  }
1816
1817  return result;
1818}
1819
1820/// Wrapper around strchr which accounts for case-insensitive searches and
1821/// non-ASCII characters.
1822///
1823/// This function is used a lot for simple searches, keep it fast!
1824///
1825/// @param  s  string to search
1826/// @param  c  character to find in @a s
1827///
1828/// @return  NULL if no match, otherwise pointer to the position in @a s
1829static inline char *cstrchr(const char *const s, const int c)
1830  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
1831  FUNC_ATTR_ALWAYS_INLINE
1832{
1833  if (!rex.reg_ic) {
1834    return vim_strchr(s, c);
1835  }
1836
1837  int cc, lc;
1838  if (c > 0x80) {
1839    cc = utf_fold(c);
1840    lc = cc;
1841  } else if (ASCII_ISUPPER(c)) {
1842    cc = TOLOWER_ASC(c);
1843    lc = cc;
1844  } else if (ASCII_ISLOWER(c)) {
1845    cc = TOUPPER_ASC(c);
1846    lc = c;
1847  } else {
1848    return vim_strchr(s, c);
1849  }
1850
1851  for (const char *p = s; *p != NUL; p += utfc_ptr2len(p)) {
1852    const int uc = utf_ptr2char(p);
1853    if (c > 0x80 || uc > 0x80) {
1854      // Do not match an illegal byte.  E.g. 0xff matches 0xc3 0xbf, not 0xff.
1855      // Compare with lower case of the character.
1856      if ((uc < 0x80 || uc != (uint8_t)(*p)) && utf_fold(uc) == lc) {
1857        return (char *)p;
1858      }
1859    } else if ((uint8_t)(*p) == c || (uint8_t)(*p) == cc) {
1860      return (char *)p;
1861    }
1862  }
1863
1864  return NULL;
1865}
1866
1867////////////////////////////////////////////////////////////////
1868//                    regsub stuff                            //
1869////////////////////////////////////////////////////////////////
1870
1871static void do_upper(int *d, int c)
1872{
1873  *d = mb_toupper(c);
1874}
1875
1876static void do_lower(int *d, int c)
1877{
1878  *d = mb_tolower(c);
1879}
1880
1881/// regtilde(): Replace tildes in the pattern by the old pattern.
1882///
1883/// Short explanation of the tilde: It stands for the previous replacement
1884/// pattern.  If that previous pattern also contains a ~ we should go back a
1885/// step further...  But we insert the previous pattern into the current one
1886/// and remember that.
1887/// This still does not handle the case where "magic" changes.  So require the
1888/// user to keep his hands off of "magic".
1889///
1890/// The tildes are parsed once before the first call to vim_regsub().
1891char *regtilde(char *source, int magic, bool preview)
1892{
1893  char *newsub = source;
1894  size_t newsublen = 0;
1895  char tilde[3] = { '~', NUL, NUL };
1896  size_t tildelen = 1;
1897  bool error = false;
1898
1899  if (!magic) {
1900    tilde[0] = '\\';
1901    tilde[1] = '~';
1902    tilde[2] = NUL;
1903    tildelen = 2;
1904  }
1905
1906  char *p;
1907  for (p = newsub; *p; p++) {
1908    if (strncmp(p, tilde, tildelen) == 0) {
1909      size_t prefixlen = (size_t)(p - newsub);  // not including the tilde
1910      char *postfix = p + tildelen;
1911      size_t postfixlen;
1912      size_t tmpsublen;
1913
1914      if (newsublen == 0) {
1915        newsublen = strlen(newsub);
1916      }
1917      newsublen -= tildelen;
1918      postfixlen = newsublen - prefixlen;
1919      tmpsublen = prefixlen + reg_prev_sublen + postfixlen;
1920
1921      if (tmpsublen > 0 && reg_prev_sub != NULL) {
1922        // Avoid making the text longer than MAXCOL, it will cause
1923        // trouble at some point.
1924        if (tmpsublen > MAXCOL) {
1925          emsg(_(e_resulting_text_too_long));
1926          error = true;
1927          break;
1928        }
1929
1930        char *tmpsub = xmalloc(tmpsublen + 1);
1931        // copy prefix
1932        memmove(tmpsub, newsub, prefixlen);
1933        // interpret tilde
1934        memmove(tmpsub + prefixlen, reg_prev_sub, reg_prev_sublen);
1935        // copy postfix
1936        STRCPY(tmpsub + prefixlen + reg_prev_sublen, postfix);
1937
1938        if (newsub != source) {  // allocated newsub before
1939          xfree(newsub);
1940        }
1941        newsub = tmpsub;
1942        newsublen = tmpsublen;
1943        p = newsub + prefixlen + reg_prev_sublen;
1944      } else {
1945        memmove(p, postfix, postfixlen + 1);  // remove the tilde (+1 for the NUL)
1946      }
1947      p--;
1948    } else {
1949      if (*p == '\\' && p[1]) {  // skip escaped characters
1950        p++;
1951      }
1952      p += utfc_ptr2len(p) - 1;
1953    }
1954  }
1955
1956  if (error) {
1957    if (newsub != source) {
1958      xfree(newsub);
1959    }
1960    return source;
1961  }
1962
1963  // Only change reg_prev_sub when not previewing.
1964  if (!preview) {
1965    // Store a copy of newsub  in reg_prev_sub.  It is always allocated,
1966    // because recursive calls may make the returned string invalid.
1967    // Only store it if there something to store.
1968    newsublen = (size_t)(p - newsub);
1969    if (newsublen == 0) {
1970      XFREE_CLEAR(reg_prev_sub);
1971    } else {
1972      xfree(reg_prev_sub);
1973      reg_prev_sub = xstrnsave(newsub, newsublen);
1974    }
1975    reg_prev_sublen = newsublen;
1976  }
1977
1978  return newsub;
1979}
1980
1981/// Put the submatches in "argv[argskip]" which is a list passed into
1982/// call_func() by vim_regsub_both().
1983static int fill_submatch_list(int argc FUNC_ATTR_UNUSED, typval_T *argv, int argskip, ufunc_T *fp)
1984  FUNC_ATTR_NONNULL_ALL
1985{
1986  typval_T *listarg = argv + argskip;
1987
1988  if (!fp->uf_varargs && fp->uf_args.ga_len <= argskip) {
1989    // called function doesn't take a submatches argument
1990    return argskip;
1991  }
1992
1993  // Relies on sl_list to be the first item in staticList10_T.
1994  tv_list_init_static10((staticList10_T *)listarg->vval.v_list);
1995
1996  // There are always 10 list items in staticList10_T.
1997  listitem_T *li = tv_list_first(listarg->vval.v_list);
1998  for (int i = 0; i < 10; i++) {
1999    char *s = rsm.sm_match->startp[i];
2000    if (s == NULL || rsm.sm_match->endp[i] == NULL) {
2001      s = NULL;
2002    } else {
2003      s = xstrnsave(s, (size_t)(rsm.sm_match->endp[i] - s));
2004    }
2005    TV_LIST_ITEM_TV(li)->v_type = VAR_STRING;
2006    TV_LIST_ITEM_TV(li)->vval.v_string = s;
2007    li = TV_LIST_ITEM_NEXT(argv->vval.v_list, li);
2008  }
2009  return argskip + 1;
2010}
2011
2012static void clear_submatch_list(staticList10_T *sl)
2013{
2014  TV_LIST_ITER(&sl->sl_list, li, {
2015    xfree(TV_LIST_ITEM_TV(li)->vval.v_string);
2016  });
2017}
2018
2019/// vim_regsub() - perform substitutions after a vim_regexec() or
2020/// vim_regexec_multi() match.
2021///
2022/// If "flags" has REGSUB_COPY really copy into "dest[destlen]".
2023/// Otherwise nothing is copied, only compute the length of the result.
2024///
2025/// If "flags" has REGSUB_MAGIC then behave like 'magic' is set.
2026///
2027/// If "flags" has REGSUB_BACKSLASH a backslash will be removed later, need to
2028/// double them to keep them, and insert a backslash before a CR to avoid it
2029/// being replaced with a line break later.
2030///
2031/// Note: The matched text must not change between the call of
2032/// vim_regexec()/vim_regexec_multi() and vim_regsub()!  It would make the back
2033/// references invalid!
2034///
2035/// Returns the size of the replacement, including terminating NUL.
2036int vim_regsub(regmatch_T *rmp, char *source, typval_T *expr, char *dest, int destlen, int flags)
2037{
2038  regexec_T rex_save;
2039  bool rex_in_use_save = rex_in_use;
2040
2041  if (rex_in_use) {
2042    // Being called recursively, save the state.
2043    rex_save = rex;
2044  }
2045  rex_in_use = true;
2046
2047  rex.reg_match = rmp;
2048  rex.reg_mmatch = NULL;
2049  rex.reg_maxline = 0;
2050  rex.reg_buf = curbuf;
2051  rex.reg_line_lbr = true;
2052  int result = vim_regsub_both(source, expr, dest, destlen, flags);
2053
2054  rex_in_use = rex_in_use_save;
2055  if (rex_in_use) {
2056    rex = rex_save;
2057  }
2058
2059  return result;
2060}
2061
2062int vim_regsub_multi(regmmatch_T *rmp, linenr_T lnum, char *source, char *dest, int destlen,
2063                     int flags)
2064{
2065  regexec_T rex_save;
2066  bool rex_in_use_save = rex_in_use;
2067
2068  if (rex_in_use) {
2069    // Being called recursively, save the state.
2070    rex_save = rex;
2071  }
2072  rex_in_use = true;
2073
2074  rex.reg_match = NULL;
2075  rex.reg_mmatch = rmp;
2076  rex.reg_buf = curbuf;  // always works on the current buffer!
2077  rex.reg_firstlnum = lnum;
2078  rex.reg_maxline = curbuf->b_ml.ml_line_count - lnum;
2079  rex.reg_line_lbr = false;
2080  int result = vim_regsub_both(source, NULL, dest, destlen, flags);
2081
2082  rex_in_use = rex_in_use_save;
2083  if (rex_in_use) {
2084    rex = rex_save;
2085  }
2086
2087  return result;
2088}
2089
2090// When nesting more than a couple levels it's probably a mistake.
2091#define MAX_REGSUB_NESTING 4
2092static char *eval_result[MAX_REGSUB_NESTING] = { NULL, NULL, NULL, NULL };
2093
2094#ifdef EXITFREE
2095void free_resub_eval_result(void)
2096{
2097  for (int i = 0; i < MAX_REGSUB_NESTING; i++) {
2098    XFREE_CLEAR(eval_result[i]);
2099  }
2100}
2101#endif
2102
2103static int vim_regsub_both(char *source, typval_T *expr, char *dest, int destlen, int flags)
2104{
2105  char *src;
2106  char *dst;
2107  char *s;
2108  int c;
2109  int cc;
2110  int no = -1;
2111  fptr_T func_all = (fptr_T)NULL;
2112  fptr_T func_one = (fptr_T)NULL;
2113  linenr_T clnum = 0;           // init for GCC
2114  int len = 0;                  // init for GCC
2115  static int nesting = 0;
2116  bool copy = flags & REGSUB_COPY;
2117
2118  // Be paranoid...
2119  if ((source == NULL && expr == NULL) || dest == NULL) {
2120    emsg(_(e_null));
2121    return 0;
2122  }
2123  if (prog_magic_wrong()) {
2124    return 0;
2125  }
2126  if (nesting == MAX_REGSUB_NESTING) {
2127    emsg(_(e_substitute_nesting_too_deep));
2128    return 0;
2129  }
2130  int nested = nesting;
2131  src = source;
2132  dst = dest;
2133
2134  // When the substitute part starts with "\=" evaluate it as an expression.
2135  if (expr != NULL || (source[0] == '\\' && source[1] == '=')) {
2136    // To make sure that the length doesn't change between checking the
2137    // length and copying the string, and to speed up things, the
2138    // resulting string is saved from the call with
2139    // "flags & REGSUB_COPY" == 0 to the call with
2140    // "flags & REGSUB_COPY" != 0.
2141    if (copy) {
2142      if (eval_result[nested] != NULL) {
2143        size_t eval_len = strlen(eval_result[nested]);
2144        if (eval_len < (size_t)destlen) {
2145          STRCPY(dest, eval_result[nested]);
2146          dst += eval_len;
2147          XFREE_CLEAR(eval_result[nested]);
2148        }
2149      }
2150    } else {
2151      const bool prev_can_f_submatch = can_f_submatch;
2152      regsubmatch_T rsm_save;
2153
2154      XFREE_CLEAR(eval_result[nested]);
2155
2156      // The expression may contain substitute(), which calls us
2157      // recursively.  Make sure submatch() gets the text from the first
2158      // level.
2159      if (can_f_submatch) {
2160        rsm_save = rsm;
2161      }
2162      can_f_submatch = true;
2163      rsm.sm_match = rex.reg_match;
2164      rsm.sm_mmatch = rex.reg_mmatch;
2165      rsm.sm_firstlnum = rex.reg_firstlnum;
2166      rsm.sm_maxline = rex.reg_maxline;
2167      rsm.sm_line_lbr = rex.reg_line_lbr;
2168
2169      // Although unlikely, it is possible that the expression invokes a
2170      // substitute command (it might fail, but still).  Therefore keep
2171      // an array of eval results.
2172      nesting++;
2173
2174      if (expr != NULL) {
2175        typval_T argv[2];
2176        typval_T rettv;
2177        staticList10_T matchList = TV_LIST_STATIC10_INIT;
2178        rettv.v_type = VAR_STRING;
2179        rettv.vval.v_string = NULL;
2180        argv[0].v_type = VAR_LIST;
2181        argv[0].vval.v_list = &matchList.sl_list;
2182        funcexe_T funcexe = FUNCEXE_INIT;
2183        funcexe.fe_argv_func = fill_submatch_list;
2184        funcexe.fe_evaluate = true;
2185        if (expr->v_type == VAR_FUNC) {
2186          s = expr->vval.v_string;
2187          call_func(s, -1, &rettv, 1, argv, &funcexe);
2188        } else if (expr->v_type == VAR_PARTIAL) {
2189          partial_T *partial = expr->vval.v_partial;
2190
2191          s = partial_name(partial);
2192          funcexe.fe_partial = partial;
2193          call_func(s, -1, &rettv, 1, argv, &funcexe);
2194        }
2195        if (tv_list_len(&matchList.sl_list) > 0) {
2196          // fill_submatch_list() was called.
2197          clear_submatch_list(&matchList);
2198        }
2199        if (rettv.v_type == VAR_UNKNOWN) {
2200          // something failed, no need to report another error
2201          eval_result[nested] = NULL;
2202        } else {
2203          char buf[NUMBUFLEN];
2204          eval_result[nested] = (char *)tv_get_string_buf_chk(&rettv, buf);
2205          if (eval_result[nested] != NULL) {
2206            eval_result[nested] = xstrdup(eval_result[nested]);
2207          }
2208        }
2209        tv_clear(&rettv);
2210      } else {
2211        eval_result[nested] = eval_to_string(source + 2, true, false);
2212      }
2213      nesting--;
2214
2215      if (eval_result[nested] != NULL) {
2216        int had_backslash = false;
2217
2218        for (s = eval_result[nested]; *s != NUL; MB_PTR_ADV(s)) {
2219          // Change NL to CR, so that it becomes a line break,
2220          // unless called from vim_regexec_nl().
2221          // Skip over a backslashed character.
2222          if (*s == NL && !rsm.sm_line_lbr) {
2223            *s = CAR;
2224          } else if (*s == '\\' && s[1] != NUL) {
2225            s++;
2226            // Change NL to CR here too, so that this works:
2227            // :s/abc\\\ndef/\="aaa\\\nbbb"/  on text:
2228            //   abc{backslash}
2229            //   def
2230            // Not when called from vim_regexec_nl().
2231            if (*s == NL && !rsm.sm_line_lbr) {
2232              *s = CAR;
2233            }
2234            had_backslash = true;
2235          }
2236        }
2237        if (had_backslash && (flags & REGSUB_BACKSLASH)) {
2238          // Backslashes will be consumed, need to double them.
2239          s = vim_strsave_escaped(eval_result[nested], "\\");
2240          xfree(eval_result[nested]);
2241          eval_result[nested] = s;
2242        }
2243
2244        dst += strlen(eval_result[nested]);
2245      }
2246
2247      can_f_submatch = prev_can_f_submatch;
2248      if (can_f_submatch) {
2249        rsm = rsm_save;
2250      }
2251    }
2252  } else {
2253    while ((c = (uint8_t)(*src++)) != NUL) {
2254      if (c == '&' && (flags & REGSUB_MAGIC)) {
2255        no = 0;
2256      } else if (c == '\\' && *src != NUL) {
2257        if (*src == '&' && !(flags & REGSUB_MAGIC)) {
2258          src++;
2259          no = 0;
2260        } else if ('0' <= *src && *src <= '9') {
2261          no = *src++ - '0';
2262        } else if (vim_strchr("uUlLeE", (uint8_t)(*src))) {
2263          switch (*src++) {
2264          case 'u':
2265            func_one = do_upper;
2266            continue;
2267          case 'U':
2268            func_all = do_upper;
2269            continue;
2270          case 'l':
2271            func_one = do_lower;
2272            continue;
2273          case 'L':
2274            func_all = do_lower;
2275            continue;
2276          case 'e':
2277          case 'E':
2278            func_one = func_all = (fptr_T)NULL;
2279            continue;
2280          }
2281        }
2282      }
2283      if (no < 0) {           // Ordinary character.
2284        if (c == K_SPECIAL && src[0] != NUL && src[1] != NUL) {
2285          // Copy a special key as-is.
2286          if (copy) {
2287            if (dst + 3 > dest + destlen) {
2288              iemsg("vim_regsub_both(): not enough space");
2289              return 0;
2290            }
2291            *dst++ = (char)c;
2292            *dst++ = *src++;
2293            *dst++ = *src++;
2294          } else {
2295            dst += 3;
2296            src += 2;
2297          }
2298          continue;
2299        }
2300
2301        if (c == '\\' && *src != NUL) {
2302          // Check for abbreviations -- webb
2303          switch (*src) {
2304          case 'r':
2305            c = CAR;        ++src;  break;
2306          case 'n':
2307            c = NL;         ++src;  break;
2308          case 't':
2309            c = TAB;        ++src;  break;
2310          // Oh no!  \e already has meaning in subst pat :-(
2311          // case 'e':   c = ESC;        ++src;  break;
2312          case 'b':
2313            c = Ctrl_H;     ++src;  break;
2314
2315          // If "backslash" is true the backslash will be removed
2316          // later.  Used to insert a literal CR.
2317          default:
2318            if (flags & REGSUB_BACKSLASH) {
2319              if (copy) {
2320                if (dst + 1 > dest + destlen) {
2321                  iemsg("vim_regsub_both(): not enough space");
2322                  return 0;
2323                }
2324                *dst = '\\';
2325              }
2326              dst++;
2327            }
2328            c = (uint8_t)(*src++);
2329          }
2330        } else {
2331          c = utf_ptr2char(src - 1);
2332        }
2333
2334        // Write to buffer, if copy is set.
2335        if (func_one != NULL) {
2336          func_one(&cc, c);
2337          func_one = NULL;
2338        } else if (func_all != NULL) {
2339          func_all(&cc, c);
2340        } else {
2341          // just copy
2342          cc = c;
2343        }
2344
2345        int totlen = utfc_ptr2len(src - 1);
2346        int charlen = utf_char2len(cc);
2347
2348        if (copy) {
2349          if (dst + charlen > dest + destlen) {
2350            iemsg("vim_regsub_both(): not enough space");
2351            return 0;
2352          }
2353          utf_char2bytes(cc, dst);
2354        }
2355        dst += charlen - 1;
2356        int clen = utf_ptr2len(src - 1);
2357
2358        // If the character length is shorter than "totlen", there
2359        // are composing characters; copy them as-is.
2360        if (clen < totlen) {
2361          if (copy) {
2362            if (dst + totlen - clen > dest + destlen) {
2363              iemsg("vim_regsub_both(): not enough space");
2364              return 0;
2365            }
2366            memmove(dst + 1, src - 1 + clen, (size_t)(totlen - clen));
2367          }
2368          dst += totlen - clen;
2369        }
2370        src += totlen - 1;
2371        dst++;
2372      } else {
2373        if (REG_MULTI) {
2374          clnum = rex.reg_mmatch->startpos[no].lnum;
2375          if (clnum < 0 || rex.reg_mmatch->endpos[no].lnum < 0) {
2376            s = NULL;
2377          } else {
2378            s = reg_getline(clnum) + rex.reg_mmatch->startpos[no].col;
2379            if (rex.reg_mmatch->endpos[no].lnum == clnum) {
2380              len = rex.reg_mmatch->endpos[no].col
2381                    - rex.reg_mmatch->startpos[no].col;
2382            } else {
2383              len = reg_getline_len(clnum) - rex.reg_mmatch->startpos[no].col;
2384            }
2385          }
2386        } else {
2387          s = rex.reg_match->startp[no];
2388          if (rex.reg_match->endp[no] == NULL) {
2389            s = NULL;
2390          } else {
2391            len = (int)(rex.reg_match->endp[no] - s);
2392          }
2393        }
2394        if (s != NULL) {
2395          while (true) {
2396            if (len == 0) {
2397              if (REG_MULTI) {
2398                if (rex.reg_mmatch->endpos[no].lnum == clnum) {
2399                  break;
2400                }
2401                if (copy) {
2402                  if (dst + 1 > dest + destlen) {
2403                    iemsg("vim_regsub_both(): not enough space");
2404                    return 0;
2405                  }
2406                  *dst = CAR;
2407                }
2408                dst++;
2409                s = reg_getline(++clnum);
2410                if (rex.reg_mmatch->endpos[no].lnum == clnum) {
2411                  len = rex.reg_mmatch->endpos[no].col;
2412                } else {
2413                  len = reg_getline_len(clnum);
2414                }
2415              } else {
2416                break;
2417              }
2418            } else if (*s == NUL) {  // we hit NUL.
2419              if (copy) {
2420                iemsg(_(e_re_damg));
2421              }
2422              goto exit;
2423            } else {
2424              if ((flags & REGSUB_BACKSLASH) && (*s == CAR || *s == '\\')) {
2425                // Insert a backslash in front of a CR, otherwise
2426                // it will be replaced by a line break.
2427                // Number of backslashes will be halved later,
2428                // double them here.
2429                if (copy) {
2430                  if (dst + 2 > dest + destlen) {
2431                    iemsg("vim_regsub_both(): not enough space");
2432                    return 0;
2433                  }
2434                  dst[0] = '\\';
2435                  dst[1] = *s;
2436                }
2437                dst += 2;
2438              } else {
2439                c = utf_ptr2char(s);
2440
2441                if (func_one != (fptr_T)NULL) {
2442                  func_one(&cc, c);
2443                  func_one = NULL;
2444                } else if (func_all != (fptr_T)NULL) {
2445                  func_all(&cc, c);
2446                } else {  // just copy
2447                  cc = c;
2448                }
2449
2450                {
2451                  int l;
2452                  int charlen;
2453
2454                  // Copy composing characters separately, one
2455                  // at a time.
2456                  l = utf_ptr2len(s) - 1;
2457
2458                  s += l;
2459                  len -= l;
2460                  charlen = utf_char2len(cc);
2461                  if (copy) {
2462                    if (dst + charlen > dest + destlen) {
2463                      iemsg("vim_regsub_both(): not enough space");
2464                      return 0;
2465                    }
2466                    utf_char2bytes(cc, dst);
2467                  }
2468                  dst += charlen - 1;
2469                }
2470                dst++;
2471              }
2472
2473              s++;
2474              len--;
2475            }
2476          }
2477        }
2478        no = -1;
2479      }
2480    }
2481  }
2482  if (copy) {
2483    *dst = NUL;
2484  }
2485
2486exit:
2487  return (int)((dst - dest) + 1);
2488}
2489
2490static char *reg_getline_submatch(linenr_T lnum)
2491{
2492  char *line;
2493  reg_getline_common(lnum, RGLF_LINE | RGLF_SUBMATCH, &line, NULL);
2494  return line;
2495}
2496
2497static colnr_T reg_getline_submatch_len(linenr_T lnum)
2498{
2499  colnr_T length;
2500  reg_getline_common(lnum, RGLF_LENGTH | RGLF_SUBMATCH, NULL, &length);
2501  return length;
2502}
2503
2504/// Used for the submatch() function: get the string from the n'th submatch in
2505/// allocated memory.
2506///
2507/// @return  NULL when not in a ":s" command and for a non-existing submatch.
2508char *reg_submatch(int no)
2509{
2510  char *retval = NULL;
2511  char *s;
2512  int round;
2513  linenr_T lnum;
2514
2515  if (!can_f_submatch || no < 0) {
2516    return NULL;
2517  }
2518
2519  if (rsm.sm_match == NULL) {
2520    ssize_t len;
2521
2522    // First round: compute the length and allocate memory.
2523    // Second round: copy the text.
2524    for (round = 1; round <= 2; round++) {
2525      lnum = rsm.sm_mmatch->startpos[no].lnum;
2526      if (lnum < 0 || rsm.sm_mmatch->endpos[no].lnum < 0) {
2527        return NULL;
2528      }
2529
2530      s = reg_getline_submatch(lnum);
2531      if (s == NULL) {  // anti-crash check, cannot happen?
2532        break;
2533      }
2534      s += rsm.sm_mmatch->startpos[no].col;
2535      if (rsm.sm_mmatch->endpos[no].lnum == lnum) {
2536        // Within one line: take form start to end col.
2537        len = rsm.sm_mmatch->endpos[no].col - rsm.sm_mmatch->startpos[no].col;
2538        if (round == 2) {
2539          xmemcpyz(retval, s, (size_t)len);
2540        }
2541        len++;
2542      } else {
2543        // Multiple lines: take start line from start col, middle
2544        // lines completely and end line up to end col.
2545        len = reg_getline_submatch_len(lnum) - rsm.sm_mmatch->startpos[no].col;
2546        if (round == 2) {
2547          STRCPY(retval, s);
2548          retval[len] = '\n';
2549        }
2550        len++;
2551        lnum++;
2552        while (lnum < rsm.sm_mmatch->endpos[no].lnum) {
2553          s = reg_getline_submatch(lnum);
2554          if (round == 2) {
2555            STRCPY(retval + len, s);
2556          }
2557          len += reg_getline_submatch_len(lnum);
2558          if (round == 2) {
2559            retval[len] = '\n';
2560          }
2561          len++;
2562          lnum++;
2563        }
2564        if (round == 2) {
2565          strncpy(retval + len,  // NOLINT(runtime/printf)
2566                  reg_getline_submatch(lnum),
2567                  (size_t)rsm.sm_mmatch->endpos[no].col);
2568        }
2569        len += rsm.sm_mmatch->endpos[no].col;
2570        if (round == 2) {
2571          retval[len] = NUL;
2572        }
2573        len++;
2574      }
2575
2576      if (retval == NULL) {
2577        retval = xmalloc((size_t)len);
2578      }
2579    }
2580  } else {
2581    s = rsm.sm_match->startp[no];
2582    if (s == NULL || rsm.sm_match->endp[no] == NULL) {
2583      retval = NULL;
2584    } else {
2585      retval = xstrnsave(s, (size_t)(rsm.sm_match->endp[no] - s));
2586    }
2587  }
2588
2589  return retval;
2590}
2591
2592// Used for the submatch() function with the optional non-zero argument: get
2593// the list of strings from the n'th submatch in allocated memory with NULs
2594// represented in NLs.
2595// Returns a list of allocated strings.  Returns NULL when not in a ":s"
2596// command, for a non-existing submatch and for any error.
2597list_T *reg_submatch_list(int no)
2598{
2599  if (!can_f_submatch || no < 0) {
2600    return NULL;
2601  }
2602
2603  linenr_T slnum;
2604  linenr_T elnum;
2605  list_T *list;
2606  const char *s;
2607
2608  if (rsm.sm_match == NULL) {
2609    slnum = rsm.sm_mmatch->startpos[no].lnum;
2610    elnum = rsm.sm_mmatch->endpos[no].lnum;
2611    if (slnum < 0 || elnum < 0) {
2612      return NULL;
2613    }
2614
2615    colnr_T scol = rsm.sm_mmatch->startpos[no].col;
2616    colnr_T ecol = rsm.sm_mmatch->endpos[no].col;
2617
2618    list = tv_list_alloc(elnum - slnum + 1);
2619
2620    s = reg_getline_submatch(slnum) + scol;
2621    if (slnum == elnum) {
2622      tv_list_append_string(list, s, ecol - scol);
2623    } else {
2624      int max_lnum = elnum - slnum;
2625      tv_list_append_string(list, s, -1);
2626      for (int i = 1; i < max_lnum; i++) {
2627        s = reg_getline_submatch(slnum + i);
2628        tv_list_append_string(list, s, -1);
2629      }
2630      s = reg_getline_submatch(elnum);
2631      tv_list_append_string(list, s, ecol);
2632    }
2633  } else {
2634    s = rsm.sm_match->startp[no];
2635    if (s == NULL || rsm.sm_match->endp[no] == NULL) {
2636      return NULL;
2637    }
2638    list = tv_list_alloc(1);
2639    tv_list_append_string(list, s, rsm.sm_match->endp[no] - s);
2640  }
2641
2642  tv_list_ref(list);
2643  return list;
2644}
2645
2646/// Initialize the values used for matching against multiple lines
2647///
2648/// @param win   window in which to search or NULL
2649/// @param buf   buffer in which to search
2650/// @param lnum  nr of line to start looking for match
2651static void init_regexec_multi(regmmatch_T *rmp, win_T *win, buf_T *buf, linenr_T lnum)
2652{
2653  rex.reg_match = NULL;
2654  rex.reg_mmatch = rmp;
2655  rex.reg_buf = buf;
2656  rex.reg_win = win;
2657  rex.reg_firstlnum = lnum;
2658  rex.reg_maxline = rex.reg_buf->b_ml.ml_line_count - lnum;
2659  rex.reg_line_lbr = false;
2660  rex.reg_ic = rmp->rmm_ic;
2661  rex.reg_icombine = false;
2662  rex.reg_nobreak = rmp->regprog->re_flags & RE_NOBREAK;
2663  rex.reg_maxcol = rmp->rmm_maxcol;
2664}
2665
2666#define CLASS_not            0x80
2667#define CLASS_af             0x40
2668#define CLASS_AF             0x20
2669#define CLASS_az             0x10
2670#define CLASS_AZ             0x08
2671#define CLASS_o7             0x04
2672#define CLASS_o9             0x02
2673#define CLASS_underscore     0x01
2674
2675/// Parse the "[...]" collection between "start" (the first character after the
2676/// "[") and "end" (the "]") into a combination of CLASS_ bits, so that it can
2677/// be turned into a faster character class like \d or \x.  Sets "*newl" to TRUE
2678/// when the collection also matches a newline.  Returns -1 when the collection
2679/// is not a plain combination of the recognized ranges.
2680static int get_char_class_bits(const uint8_t *start, const uint8_t *end, bool *newl)
2681{
2682  int config = 0;
2683
2684  *newl = false;
2685  if (*end != ']') {
2686    return -1;
2687  }
2688  const uint8_t *p = start;
2689  if (*p == '^') {
2690    config |= CLASS_not;
2691    p++;
2692  }
2693
2694  while (p < end) {
2695    if (p + 2 < end && *(p + 1) == '-') {
2696      switch (*p) {
2697      case '0':
2698        if (*(p + 2) == '9') {
2699          config |= CLASS_o9;
2700          break;
2701        } else if (*(p + 2) == '7') {
2702          config |= CLASS_o7;
2703          break;
2704        }
2705        return -1;
2706      case 'a':
2707        if (*(p + 2) == 'z') {
2708          config |= CLASS_az;
2709          break;
2710        } else if (*(p + 2) == 'f') {
2711          config |= CLASS_af;
2712          break;
2713        }
2714        return -1;
2715      case 'A':
2716        if (*(p + 2) == 'Z') {
2717          config |= CLASS_AZ;
2718          break;
2719        } else if (*(p + 2) == 'F') {
2720          config |= CLASS_AF;
2721          break;
2722        }
2723        return -1;
2724      default:
2725        return -1;
2726      }
2727      p += 3;
2728    } else if (p + 1 < end && *p == '\\' && *(p + 1) == 'n') {
2729      *newl = true;
2730      p += 2;
2731    } else if (*p == '_') {
2732      config |= CLASS_underscore;
2733      p++;
2734    } else if (*p == '\n') {
2735      *newl = true;
2736      p++;
2737    } else {
2738      return -1;
2739    }
2740  }   // while (p < end)
2741
2742  if (p != end) {
2743    return -1;
2744  }
2745
2746  // U+017F and U+212A fold to ASCII 's' and 'k', missed by the class opcodes
2747  if (config & (CLASS_az | CLASS_AZ)) {
2748    return -1;
2749  }
2750
2751  return config;
2752}
2753
2754// regexp_bt.c {{{1
2755
2756// Backtracking regular expression implementation.
2757//
2758// NOTICE:
2759//
2760// This is NOT the original regular expression code as written by Henry
2761// Spencer.  This code has been modified specifically for use with the VIM
2762// editor, and should not be used separately from Vim.  If you want a good
2763// regular expression library, get the original code.  The copyright notice
2764// that follows is from the original.
2765//
2766// END NOTICE
2767//
2768//      Copyright (c) 1986 by University of Toronto.
2769//      Written by Henry Spencer.  Not derived from licensed software.
2770//
2771//      Permission is granted to anyone to use this software for any
2772//      purpose on any computer system, and to redistribute it freely,
2773//      subject to the following restrictions:
2774//
2775//      1. The author is not responsible for the consequences of use of
2776//              this software, no matter how awful, even if they arise
2777//              from defects in it.
2778//
2779//      2. The origin of this software must not be misrepresented, either
2780//              by explicit claim or by omission.
2781//
2782//      3. Altered versions must be plainly marked as such, and must not
2783//              be misrepresented as being the original software.
2784//
2785// Beware that some of this code is subtly aware of the way operator
2786// precedence is structured in regular expressions.  Serious changes in
2787// regular-expression syntax might require a total rethink.
2788//
2789// Changes have been made by Tony Andrews, Olaf 'Rhialto' Seibert, Robert
2790// Webb, Ciaran McCreesh and Bram Moolenaar.
2791// Named character class support added by Walter Briscoe (1998 Jul 01)
2792
2793// The "internal use only" fields in regexp_defs.h are present to pass info from
2794// compile to execute that permits the execute phase to run lots faster on
2795// simple cases.  They are:
2796//
2797// regstart     char that must begin a match; NUL if none obvious; Can be a
2798//              multi-byte character.
2799// reganch      is the match anchored (at beginning-of-line only)?
2800// regmust      string (pointer into program) that match must include, or NULL
2801// regmlen      length of regmust string
2802// regflags     RF_ values or'ed together
2803//
2804// Regstart and reganch permit very fast decisions on suitable starting points
2805// for a match, cutting down the work a lot.  Regmust permits fast rejection
2806// of lines that cannot possibly match.  The regmust tests are costly enough
2807// that vim_regcomp() supplies a regmust only if the r.e. contains something
2808// potentially expensive (at present, the only such thing detected is * or +
2809// at the start of the r.e., which can involve a lot of backup).  Regmlen is
2810// supplied because the test in vim_regexec() needs it and vim_regcomp() is
2811// computing it anyway.
2812
2813// Structure for regexp "program".  This is essentially a linear encoding
2814// of a nondeterministic finite-state machine (aka syntax charts or
2815// "railroad normal form" in parsing technology).  Each node is an opcode
2816// plus a "next" pointer, possibly plus an operand.  "Next" pointers of
2817// all nodes except BRANCH and BRACES_COMPLEX implement concatenation; a "next"
2818// pointer with a BRANCH on both ends of it is connecting two alternatives.
2819// (Here we have one of the subtle syntax dependencies: an individual BRANCH
2820// (as opposed to a collection of them) is never concatenated with anything
2821// because of operator precedence).  The "next" pointer of a BRACES_COMPLEX
2822// node points to the node after the stuff to be repeated.
2823// The operand of some types of node is a literal string; for others, it is a
2824// node leading into a sub-FSM.  In particular, the operand of a BRANCH node
2825// is the first node of the branch.
2826// (NB this is *not* a tree structure: the tail of the branch connects to the
2827// thing following the set of BRANCHes.)
2828//
2829// pattern      is coded like:
2830//
2831//                        +-----------------+
2832//                        |                 V
2833// <aa>\|<bb>   BRANCH <aa> BRANCH <bb> --> END
2834//                   |      ^    |          ^
2835//                   +------+    +----------+
2836//
2837//
2838//                     +------------------+
2839//                     V                  |
2840// <aa>*        BRANCH BRANCH <aa> --> BACK BRANCH --> NOTHING --> END
2841//                   |      |               ^                      ^
2842//                   |      +---------------+                      |
2843//                   +---------------------------------------------+
2844//
2845//
2846//                     +----------------------+
2847//                     V                      |
2848// <aa>\+       BRANCH <aa> --> BRANCH --> BACK  BRANCH --> NOTHING --> END
2849//                   |               |           ^                      ^
2850//                   |               +-----------+                      |
2851//                   +--------------------------------------------------+
2852//
2853//
2854//                                      +-------------------------+
2855//                                      V                         |
2856// <aa>\{}      BRANCH BRACE_LIMITS --> BRACE_COMPLEX <aa> --> BACK  END
2857//                   |                              |                ^
2858//                   |                              +----------------+
2859//                   +-----------------------------------------------+
2860//
2861//
2862// <aa>\@!<bb>  BRANCH NOMATCH <aa> --> END  <bb> --> END
2863//                   |       |                ^       ^
2864//                   |       +----------------+       |
2865//                   +--------------------------------+
2866//
2867//                                                    +---------+
2868//                                                    |         V
2869// \z[abc]      BRANCH BRANCH  a  BRANCH  b  BRANCH  c  BRANCH  NOTHING --> END
2870//                   |      |          |          |     ^                   ^
2871//                   |      |          |          +-----+                   |
2872//                   |      |          +----------------+                   |
2873//                   |      +---------------------------+                   |
2874//                   +------------------------------------------------------+
2875//
2876// They all start with a BRANCH for "\|" alternatives, even when there is only
2877// one alternative.
2878
2879// The opcodes are:
2880
2881// definition   number             opnd?    meaning
2882#define END             0       //      End of program or NOMATCH operand.
2883#define BOL             1       //      Match "" at beginning of line.
2884#define EOL             2       //      Match "" at end of line.
2885#define BRANCH          3       // node Match this alternative, or the
2886                                //      next...
2887#define BACK            4       //      Match "", "next" ptr points backward.
2888#define EXACTLY         5       // str  Match this string.
2889#define NOTHING         6       //      Match empty string.
2890#define STAR            7       // node Match this (simple) thing 0 or more
2891                                //      times.
2892#define PLUS            8       // node Match this (simple) thing 1 or more
2893                                //      times.
2894#define MATCH           9       // node match the operand zero-width
2895#define NOMATCH         10      // node check for no match with operand
2896#define BEHIND          11      // node look behind for a match with operand
2897#define NOBEHIND        12      // node look behind for no match with operand
2898#define SUBPAT          13      // node match the operand here
2899#define BRACE_SIMPLE    14      // node Match this (simple) thing between m and
2900                                //      n times (\{m,n\}).
2901#define BOW             15      //      Match "" after [^a-zA-Z0-9_]
2902#define EOW             16      //      Match "" at    [^a-zA-Z0-9_]
2903#define BRACE_LIMITS    17      // nr nr  define the min & max for BRACE_SIMPLE
2904                                //      and BRACE_COMPLEX.
2905#define NEWL            18      //      Match line-break
2906#define BHPOS           19      //      End position for BEHIND or NOBEHIND
2907
2908// character classes: 20-48 normal, 50-78 include a line-break
2909#define ADD_NL          30
2910#define FIRST_NL        ANY + ADD_NL
2911#define ANY             20      //      Match any one character.
2912#define ANYOF           21      // str  Match any character in this string.
2913#define ANYBUT          22      // str  Match any character not in this
2914                                //      string.
2915#define IDENT           23      //      Match identifier char
2916#define SIDENT          24      //      Match identifier char but no digit
2917#define KWORD           25      //      Match keyword char
2918#define SKWORD          26      //      Match word char but no digit
2919#define FNAME           27      //      Match file name char
2920#define SFNAME          28      //      Match file name char but no digit
2921#define PRINT           29      //      Match printable char
2922#define SPRINT          30      //      Match printable char but no digit
2923#define WHITE           31      //      Match whitespace char
2924#define NWHITE          32      //      Match non-whitespace char
2925#define DIGIT           33      //      Match digit char
2926#define NDIGIT          34      //      Match non-digit char
2927#define HEX             35      //      Match hex char
2928#define NHEX            36      //      Match non-hex char
2929#define OCTAL           37      //      Match octal char
2930#define NOCTAL          38      //      Match non-octal char
2931#define WORD            39      //      Match word char
2932#define NWORD           40      //      Match non-word char
2933#define HEAD            41      //      Match head char
2934#define NHEAD           42      //      Match non-head char
2935#define ALPHA           43      //      Match alpha char
2936#define NALPHA          44      //      Match non-alpha char
2937#define LOWER           45      //      Match lowercase char
2938#define NLOWER          46      //      Match non-lowercase char
2939#define UPPER           47      //      Match uppercase char
2940#define NUPPER          48      //      Match non-uppercase char
2941#define LAST_NL         NUPPER + ADD_NL
2942#define WITH_NL(op)     ((op) >= FIRST_NL && (op) <= LAST_NL)
2943
2944#define MOPEN           80   // -89 Mark this point in input as start of
2945                             //     \( … \) subexpr.  MOPEN + 0 marks start of
2946                             //     match.
2947#define MCLOSE          90   // -99 Analogous to MOPEN.  MCLOSE + 0 marks
2948                             //     end of match.
2949#define BACKREF         100  // -109 node Match same string again \1-\9.
2950
2951#define ZOPEN          110  // -119 Mark this point in input as start of
2952                            //  \z( … \) subexpr.
2953#define ZCLOSE         120  // -129 Analogous to ZOPEN.
2954#define ZREF           130  // -139 node Match external submatch \z1-\z9
2955
2956#define BRACE_COMPLEX   140  // -149 node Match nodes between m & n times
2957
2958#define NOPEN           150     // Mark this point in input as start of
2959                                // \%( subexpr.
2960#define NCLOSE          151     // Analogous to NOPEN.
2961
2962#define MULTIBYTECODE   200     // mbc  Match one multi-byte character
2963#define RE_BOF          201     //      Match "" at beginning of file.
2964#define RE_EOF          202     //      Match "" at end of file.
2965#define CURSOR          203     //      Match location of cursor.
2966
2967#define RE_LNUM         204     // nr cmp  Match line number
2968#define RE_COL          205     // nr cmp  Match column number
2969#define RE_VCOL         206     // nr cmp  Match virtual column number
2970
2971#define RE_MARK         207     // mark cmp  Match mark position
2972#define RE_VISUAL       208     //      Match Visual area
2973#define RE_COMPOSING    209     // any composing characters
2974
2975// Flags to be passed up and down.
2976#define HASWIDTH        0x1     // Known never to match null string.
2977#define SIMPLE          0x2     // Simple enough to be STAR/PLUS operand.
2978#define SPSTART         0x4     // Starts with * or +.
2979#define HASNL           0x8     // Contains some \n.
2980#define HASLOOKBH       0x10    // Contains "\@<=" or "\@<!".
2981#define WORST           0       // Worst case.
2982
2983static int prevchr_len;         ///< byte length of previous char
2984static int num_complex_braces;  ///< Complex \{...} count
2985static uint8_t *regcode;         ///< Code-emit pointer, or JUST_CALC_SIZE
2986static int64_t regsize;            ///< Code size.
2987static int reg_toolong;         ///< true when offset out of range
2988static int bt_reg_parse_depth;     ///< nesting depth in reg()
2989static uint8_t had_endbrace[NSUBEXP];  ///< flags, true if end of () found
2990static int64_t brace_min[10];        ///< Minimums for complex brace repeats
2991static int64_t brace_max[10];        ///< Maximums for complex brace repeats
2992static int brace_count[10];       ///< Current counts for complex brace repeats
2993static int one_exactly = false;   ///< only do one char for EXACTLY
2994
2995// When making changes to classchars also change nfa_classcodes.
2996static uint8_t *classchars = (uint8_t *)".iIkKfFpPsSdDxXoOwWhHaAlLuU";
2997static const int classcodes[] = {
2998  ANY, IDENT, SIDENT, KWORD, SKWORD,
2999  FNAME, SFNAME, PRINT, SPRINT,
3000  WHITE, NWHITE, DIGIT, NDIGIT,
3001  HEX, NHEX, OCTAL, NOCTAL,
3002  WORD, NWORD, HEAD, NHEAD,
3003  ALPHA, NALPHA, LOWER, NLOWER,
3004  UPPER, NUPPER
3005};
3006
3007/// Search between "start" (the first char of the range) and "end" (the closing
3008/// "]") and try to recognize a character class in expanded form, for example
3009/// [0-9].  On success, return the atom to be emitted, on failure 0.
3010static int bt_recognize_char_class(const uint8_t *start, const uint8_t *end)
3011{
3012  bool newl;
3013  int config = get_char_class_bits(start, end, &newl);
3014
3015  // A newline would need the ADD_NL variant, don't bother with it here.
3016  if (config < 0 || newl) {
3017    return 0;
3018  }
3019
3020  // The old engine has no case-insensitive class opcode, so [a-z] and [A-Z]
3021  // are left as collections.  The classes below are case-independent.
3022  switch (config) {
3023  case CLASS_o9:
3024    return DIGIT;
3025  case CLASS_not | CLASS_o9:
3026    return NDIGIT;
3027  case CLASS_af | CLASS_AF | CLASS_o9:
3028    return HEX;
3029  case CLASS_not | CLASS_af | CLASS_AF | CLASS_o9:
3030    return NHEX;
3031  case CLASS_o7:
3032    return OCTAL;
3033  case CLASS_not | CLASS_o7:
3034    return NOCTAL;
3035  case CLASS_az | CLASS_AZ | CLASS_o9 | CLASS_underscore:
3036    return WORD;
3037  case CLASS_not | CLASS_az | CLASS_AZ | CLASS_o9 | CLASS_underscore:
3038    return NWORD;
3039  case CLASS_az | CLASS_AZ | CLASS_underscore:
3040    return HEAD;
3041  case CLASS_not | CLASS_az | CLASS_AZ | CLASS_underscore:
3042    return NHEAD;
3043  case CLASS_az | CLASS_AZ:
3044    return ALPHA;
3045  case CLASS_not | CLASS_az | CLASS_AZ:
3046    return NALPHA;
3047  }
3048  return 0;
3049}
3050
3051// When regcode is set to this value, code is not emitted and size is computed
3052// instead.
3053#define JUST_CALC_SIZE  ((uint8_t *)-1)
3054
3055// used for STAR, PLUS and BRACE_SIMPLE matching
3056typedef struct regstar_S {
3057  int nextb;            // next byte
3058  int nextb_ic;         // next byte reverse case
3059  int64_t count;
3060  int64_t minval;
3061  int64_t maxval;
3062} regstar_T;
3063
3064// used to store input position when a BACK was encountered, so that we now if
3065// we made any progress since the last time.
3066typedef struct backpos_S {
3067  uint8_t *bp_scan;         // "scan" where BACK was encountered
3068  regsave_T bp_pos;           // last input position
3069} backpos_T;
3070
3071// "regstack" and "backpos" are used by regmatch().  They are kept over calls
3072// to avoid invoking malloc() and free() often.
3073// "regstack" is a stack with regitem_T items, sometimes preceded by regstar_T
3074// or regbehind_T.
3075// "backpos_T" is a table with backpos_T for BACK
3076static garray_T regstack = GA_EMPTY_INIT_VALUE;
3077static garray_T backpos = GA_EMPTY_INIT_VALUE;
3078
3079static regsave_T behind_pos;
3080
3081// Both for regstack and backpos tables we use the following strategy of
3082// allocation (to reduce malloc/free calls):
3083// - Initial size is fairly small.
3084// - When needed, the tables are grown bigger (8 times at first, double after
3085//   that).
3086// - After executing the match we free the memory only if the array has grown.
3087//   Thus the memory is kept allocated when it's at the initial size.
3088// This makes it fast while not keeping a lot of memory allocated.
3089// A three times speed increase was observed when using many simple patterns.
3090#define REGSTACK_INITIAL        2048
3091#define BACKPOS_INITIAL         64
3092
3093// Opcode notes:
3094//
3095// BRANCH       The set of branches constituting a single choice are hooked
3096//              together with their "next" pointers, since precedence prevents
3097//              anything being concatenated to any individual branch.  The
3098//              "next" pointer of the last BRANCH in a choice points to the
3099//              thing following the whole choice.  This is also where the
3100//              final "next" pointer of each individual branch points; each
3101//              branch starts with the operand node of a BRANCH node.
3102//
3103// BACK         Normal "next" pointers all implicitly point forward; BACK
3104//              exists to make loop structures possible.
3105//
3106// STAR,PLUS    '=', and complex '*' and '+', are implemented as circular
3107//              BRANCH structures using BACK.  Simple cases (one character
3108//              per match) are implemented with STAR and PLUS for speed
3109//              and to minimize recursive plunges.
3110//
3111// BRACE_LIMITS This is always followed by a BRACE_SIMPLE or BRACE_COMPLEX
3112//              node, and defines the min and max limits to be used for that
3113//              node.
3114//
3115// MOPEN,MCLOSE ...are numbered at compile time.
3116// ZOPEN,ZCLOSE ...ditto
3117///
3118//
3119//
3120// A node is one char of opcode followed by two chars of "next" pointer.
3121// "Next" pointers are stored as two 8-bit bytes, high order first.  The
3122// value is a positive offset from the opcode of the node containing it.
3123// An operand, if any, simply follows the node.  (Note that much of the
3124// code generation knows about this implicit relationship.)
3125//
3126// Using two bytes for the "next" pointer is vast overkill for most things,
3127// but allows patterns to get big without disasters.
3128#define OP(p)           ((int)(*(p)))
3129#define NEXT(p)         (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
3130#define OPERAND(p)      ((p) + 3)
3131// Obtain an operand that was stored as four bytes, MSB first.
3132#define OPERAND_MIN(p)  (((int64_t)(p)[3] << 24) + ((int64_t)(p)[4] << 16) \
3133                         + ((int64_t)(p)[5] << 8) + (int64_t)(p)[6])
3134// Obtain a second operand stored as four bytes.
3135#define OPERAND_MAX(p)  OPERAND_MIN((p) + 4)
3136// Obtain a second single-byte operand stored after a four bytes operand.
3137#define OPERAND_CMP(p)  (p)[7]
3138
3139static uint8_t *reg(int paren, int *flagp);
3140
3141#ifdef BT_REGEXP_DUMP
3142static void     regdump(uint8_t *, bt_regprog_T *);
3143#endif
3144
3145#ifdef REGEXP_DEBUG
3146static uint8_t *regprop(uint8_t *);
3147
3148static int regnarrate = 0;
3149#endif
3150
3151// Setup to parse the regexp.  Used once to get the length and once to do it.
3152static void regcomp_start(uint8_t *expr, int re_flags)                        // see vim_regcomp()
3153{
3154  initchr((char *)expr);
3155  if (re_flags & RE_MAGIC) {
3156    reg_magic = MAGIC_ON;
3157  } else {
3158    reg_magic = MAGIC_OFF;
3159  }
3160  reg_string = (re_flags & RE_STRING);
3161  reg_strict = (re_flags & RE_STRICT);
3162  get_cpo_flags();
3163
3164  num_complex_braces = 0;
3165  regnpar = 1;
3166  CLEAR_FIELD(had_endbrace);
3167  regnzpar = 1;
3168  re_has_z = 0;
3169  regsize = 0L;
3170  reg_toolong = false;
3171  bt_reg_parse_depth = 0;
3172  regflags = 0;
3173  had_eol = false;
3174}
3175
3176// Return true if MULTIBYTECODE should be used instead of EXACTLY for
3177// character "c".
3178static bool use_multibytecode(int c)
3179{
3180  return utf_char2len(c) > 1
3181         && (re_multi_type(peekchr()) != NOT_MULTI
3182             || utf_iscomposing_legacy(c));
3183}
3184
3185// Emit (if appropriate) a byte of code
3186static void regc(int b)
3187{
3188  if (regcode == JUST_CALC_SIZE) {
3189    regsize++;
3190  } else {
3191    *regcode++ = (uint8_t)b;
3192  }
3193}
3194
3195// Emit (if appropriate) a multi-byte character of code
3196static void regmbc(int c)
3197{
3198  if (regcode == JUST_CALC_SIZE) {
3199    regsize += utf_char2len(c);
3200  } else {
3201    regcode += utf_char2bytes(c, (char *)regcode);
3202  }
3203}
3204
3205// Produce the bytes for equivalence class "c".
3206// Currently only handles latin1, latin9 and utf-8.
3207// NOTE: When changing this function, also change nfa_emit_equi_class()
3208static void reg_equi_class(int c)
3209{
3210  {
3211    switch (c) {
3212    // Do not use '\300' style, it results in a negative number.
3213    case 'A':
3214    case 0xc0:
3215    case 0xc1:
3216    case 0xc2:
3217    case 0xc3:
3218    case 0xc4:
3219    case 0xc5:
3220    case 0x100:
3221    case 0x102:
3222    case 0x104:
3223    case 0x1cd:
3224    case 0x1de:
3225    case 0x1e0:
3226    case 0x1fa:
3227    case 0x202:
3228    case 0x226:
3229    case 0x23a:
3230    case 0x1e00:
3231    case 0x1ea0:
3232    case 0x1ea2:
3233    case 0x1ea4:
3234    case 0x1ea6:
3235    case 0x1ea8:
3236    case 0x1eaa:
3237    case 0x1eac:
3238    case 0x1eae:
3239    case 0x1eb0:
3240    case 0x1eb2:
3241    case 0x1eb4:
3242    case 0x1eb6:
3243      regmbc('A'); regmbc(0xc0); regmbc(0xc1); regmbc(0xc2);
3244      regmbc(0xc3); regmbc(0xc4); regmbc(0xc5);
3245      regmbc(0x100); regmbc(0x102); regmbc(0x104);
3246      regmbc(0x1cd); regmbc(0x1de); regmbc(0x1e0);
3247      regmbc(0x1fa); regmbc(0x202); regmbc(0x226);
3248      regmbc(0x23a); regmbc(0x1e00); regmbc(0x1ea0);
3249      regmbc(0x1ea2); regmbc(0x1ea4); regmbc(0x1ea6);
3250      regmbc(0x1ea8); regmbc(0x1eaa); regmbc(0x1eac);
3251      regmbc(0x1eae); regmbc(0x1eb0); regmbc(0x1eb2);
3252      regmbc(0x1eb4); regmbc(0x1eb6);
3253      return;
3254    case 'B':
3255    case 0x181:
3256    case 0x243:
3257    case 0x1e02:
3258    case 0x1e04:
3259    case 0x1e06:
3260      regmbc('B');
3261      regmbc(0x181); regmbc(0x243); regmbc(0x1e02);
3262      regmbc(0x1e04); regmbc(0x1e06);
3263      return;
3264    case 'C':
3265    case 0xc7:
3266    case 0x106:
3267    case 0x108:
3268    case 0x10a:
3269    case 0x10c:
3270    case 0x187:
3271    case 0x23b:
3272    case 0x1e08:
3273    case 0xa792:
3274      regmbc('C'); regmbc(0xc7);
3275      regmbc(0x106); regmbc(0x108); regmbc(0x10a);
3276      regmbc(0x10c); regmbc(0x187); regmbc(0x23b);
3277      regmbc(0x1e08); regmbc(0xa792);
3278      return;
3279    case 'D':
3280    case 0x10e:
3281    case 0x110:
3282    case 0x18a:
3283    case 0x1e0a:
3284    case 0x1e0c:
3285    case 0x1e0e:
3286    case 0x1e10:
3287    case 0x1e12:
3288      regmbc('D'); regmbc(0x10e); regmbc(0x110);
3289      regmbc(0x18a); regmbc(0x1e0a); regmbc(0x1e0c);
3290      regmbc(0x1e0e); regmbc(0x1e10); regmbc(0x1e12);
3291      return;
3292    case 'E':
3293    case 0xc8:
3294    case 0xc9:
3295    case 0xca:
3296    case 0xcb:
3297    case 0x112:
3298    case 0x114:
3299    case 0x116:
3300    case 0x118:
3301    case 0x11a:
3302    case 0x204:
3303    case 0x206:
3304    case 0x228:
3305    case 0x246:
3306    case 0x1e14:
3307    case 0x1e16:
3308    case 0x1e18:
3309    case 0x1e1a:
3310    case 0x1e1c:
3311    case 0x1eb8:
3312    case 0x1eba:
3313    case 0x1ebc:
3314    case 0x1ebe:
3315    case 0x1ec0:
3316    case 0x1ec2:
3317    case 0x1ec4:
3318    case 0x1ec6:
3319      regmbc('E'); regmbc(0xc8); regmbc(0xc9);
3320      regmbc(0xca); regmbc(0xcb); regmbc(0x112);
3321      regmbc(0x114); regmbc(0x116); regmbc(0x118);
3322      regmbc(0x11a); regmbc(0x204); regmbc(0x206);
3323      regmbc(0x228); regmbc(0x246); regmbc(0x1e14);
3324      regmbc(0x1e16); regmbc(0x1e18); regmbc(0x1e1a);
3325      regmbc(0x1e1c); regmbc(0x1eb8); regmbc(0x1eba);
3326      regmbc(0x1ebc); regmbc(0x1ebe); regmbc(0x1ec0);
3327      regmbc(0x1ec2); regmbc(0x1ec4); regmbc(0x1ec6);
3328      return;
3329    case 'F':
3330    case 0x191:
3331    case 0x1e1e:
3332    case 0xa798:
3333      regmbc('F'); regmbc(0x191); regmbc(0x1e1e);
3334      regmbc(0xa798);
3335      return;
3336    case 'G':
3337    case 0x11c:
3338    case 0x11e:
3339    case 0x120:
3340    case 0x122:
3341    case 0x193:
3342    case 0x1e4:
3343    case 0x1e6:
3344    case 0x1f4:
3345    case 0x1e20:
3346    case 0xa7a0:
3347      regmbc('G'); regmbc(0x11c); regmbc(0x11e);
3348      regmbc(0x120); regmbc(0x122); regmbc(0x193);
3349      regmbc(0x1e4); regmbc(0x1e6); regmbc(0x1f4);
3350      regmbc(0x1e20); regmbc(0xa7a0);
3351      return;
3352    case 'H':
3353    case 0x124:
3354    case 0x126:
3355    case 0x21e:
3356    case 0x1e22:
3357    case 0x1e24:
3358    case 0x1e26:
3359    case 0x1e28:
3360    case 0x1e2a:
3361    case 0x2c67:
3362      regmbc('H'); regmbc(0x124); regmbc(0x126);
3363      regmbc(0x21e); regmbc(0x1e22); regmbc(0x1e24);
3364      regmbc(0x1e26); regmbc(0x1e28); regmbc(0x1e2a);
3365      regmbc(0x2c67);
3366      return;
3367    case 'I':
3368    case 0xcc:
3369    case 0xcd:
3370    case 0xce:
3371    case 0xcf:
3372    case 0x128:
3373    case 0x12a:
3374    case 0x12c:
3375    case 0x12e:
3376    case 0x130:
3377    case 0x197:
3378    case 0x1cf:
3379    case 0x208:
3380    case 0x20a:
3381    case 0x1e2c:
3382    case 0x1e2e:
3383    case 0x1ec8:
3384    case 0x1eca:
3385      regmbc('I'); regmbc(0xcc); regmbc(0xcd);
3386      regmbc(0xce); regmbc(0xcf); regmbc(0x128);
3387      regmbc(0x12a); regmbc(0x12c); regmbc(0x12e);
3388      regmbc(0x130); regmbc(0x197); regmbc(0x1cf);
3389      regmbc(0x208); regmbc(0x20a); regmbc(0x1e2c);
3390      regmbc(0x1e2e); regmbc(0x1ec8); regmbc(0x1eca);
3391      return;
3392    case 'J':
3393    case 0x134:
3394    case 0x248:
3395      regmbc('J'); regmbc(0x134); regmbc(0x248);
3396      return;
3397    case 'K':
3398    case 0x136:
3399    case 0x198:
3400    case 0x1e8:
3401    case 0x1e30:
3402    case 0x1e32:
3403    case 0x1e34:
3404    case 0x2c69:
3405    case 0xa740:
3406      regmbc('K'); regmbc(0x136); regmbc(0x198);
3407      regmbc(0x1e8); regmbc(0x1e30); regmbc(0x1e32);
3408      regmbc(0x1e34); regmbc(0x2c69); regmbc(0xa740);
3409      return;
3410    case 'L':
3411    case 0x139:
3412    case 0x13b:
3413    case 0x13d:
3414    case 0x13f:
3415    case 0x141:
3416    case 0x23d:
3417    case 0x1e36:
3418    case 0x1e38:
3419    case 0x1e3a:
3420    case 0x1e3c:
3421    case 0x2c60:
3422      regmbc('L'); regmbc(0x139); regmbc(0x13b);
3423      regmbc(0x13d); regmbc(0x13f); regmbc(0x141);
3424      regmbc(0x23d); regmbc(0x1e36); regmbc(0x1e38);
3425      regmbc(0x1e3a); regmbc(0x1e3c); regmbc(0x2c60);
3426      return;
3427    case 'M':
3428    case 0x1e3e:
3429    case 0x1e40:
3430    case 0x1e42:
3431      regmbc('M'); regmbc(0x1e3e); regmbc(0x1e40);
3432      regmbc(0x1e42);
3433      return;
3434    case 'N':
3435    case 0xd1:
3436    case 0x143:
3437    case 0x145:
3438    case 0x147:
3439    case 0x1f8:
3440    case 0x1e44:
3441    case 0x1e46:
3442    case 0x1e48:
3443    case 0x1e4a:
3444    case 0xa7a4:
3445      regmbc('N'); regmbc(0xd1);
3446      regmbc(0x143); regmbc(0x145); regmbc(0x147);
3447      regmbc(0x1f8); regmbc(0x1e44); regmbc(0x1e46);
3448      regmbc(0x1e48); regmbc(0x1e4a); regmbc(0xa7a4);
3449      return;
3450    case 'O':
3451    case 0xd2:
3452    case 0xd3:
3453    case 0xd4:
3454    case 0xd5:
3455    case 0xd6:
3456    case 0xd8:
3457    case 0x14c:
3458    case 0x14e:
3459    case 0x150:
3460    case 0x19f:
3461    case 0x1a0:
3462    case 0x1d1:
3463    case 0x1ea:
3464    case 0x1ec:
3465    case 0x1fe:
3466    case 0x20c:
3467    case 0x20e:
3468    case 0x22a:
3469    case 0x22c:
3470    case 0x22e:
3471    case 0x230:
3472    case 0x1e4c:
3473    case 0x1e4e:
3474    case 0x1e50:
3475    case 0x1e52:
3476    case 0x1ecc:
3477    case 0x1ece:
3478    case 0x1ed0:
3479    case 0x1ed2:
3480    case 0x1ed4:
3481    case 0x1ed6:
3482    case 0x1ed8:
3483    case 0x1eda:
3484    case 0x1edc:
3485    case 0x1ede:
3486    case 0x1ee0:
3487    case 0x1ee2:
3488      regmbc('O'); regmbc(0xd2); regmbc(0xd3); regmbc(0xd4);
3489      regmbc(0xd5); regmbc(0xd6); regmbc(0xd8);
3490      regmbc(0x14c); regmbc(0x14e); regmbc(0x150);
3491      regmbc(0x19f); regmbc(0x1a0); regmbc(0x1d1);
3492      regmbc(0x1ea); regmbc(0x1ec); regmbc(0x1fe);
3493      regmbc(0x20c); regmbc(0x20e); regmbc(0x22a);
3494      regmbc(0x22c); regmbc(0x22e); regmbc(0x230);
3495      regmbc(0x1e4c); regmbc(0x1e4e); regmbc(0x1e50);
3496      regmbc(0x1e52); regmbc(0x1ecc); regmbc(0x1ece);
3497      regmbc(0x1ed0); regmbc(0x1ed2); regmbc(0x1ed4);
3498      regmbc(0x1ed6); regmbc(0x1ed8); regmbc(0x1eda);
3499      regmbc(0x1edc); regmbc(0x1ede); regmbc(0x1ee0);
3500      regmbc(0x1ee2);
3501      return;
3502    case 'P':
3503    case 0x1a4:
3504    case 0x1e54:
3505    case 0x1e56:
3506    case 0x2c63:
3507      regmbc('P'); regmbc(0x1a4); regmbc(0x1e54);
3508      regmbc(0x1e56); regmbc(0x2c63);
3509      return;
3510    case 'Q':
3511    case 0x24a:
3512      regmbc('Q'); regmbc(0x24a);
3513      return;
3514    case 'R':
3515    case 0x154:
3516    case 0x156:
3517    case 0x158:
3518    case 0x210:
3519    case 0x212:
3520    case 0x24c:
3521    case 0x1e58:
3522    case 0x1e5a:
3523    case 0x1e5c:
3524    case 0x1e5e:
3525    case 0x2c64:
3526    case 0xa7a6:
3527      regmbc('R'); regmbc(0x154); regmbc(0x156);
3528      regmbc(0x210); regmbc(0x212); regmbc(0x158);
3529      regmbc(0x24c); regmbc(0x1e58); regmbc(0x1e5a);
3530      regmbc(0x1e5c); regmbc(0x1e5e); regmbc(0x2c64);
3531      regmbc(0xa7a6);
3532      return;
3533    case 'S':
3534    case 0x15a:
3535    case 0x15c:
3536    case 0x15e:
3537    case 0x160:
3538    case 0x218:
3539    case 0x1e60:
3540    case 0x1e62:
3541    case 0x1e64:
3542    case 0x1e66:
3543    case 0x1e68:
3544    case 0x2c7e:
3545    case 0xa7a8:
3546      regmbc('S'); regmbc(0x15a); regmbc(0x15c);
3547      regmbc(0x15e); regmbc(0x160); regmbc(0x218);
3548      regmbc(0x1e60); regmbc(0x1e62); regmbc(0x1e64);
3549      regmbc(0x1e66); regmbc(0x1e68); regmbc(0x2c7e);
3550      regmbc(0xa7a8);
3551      return;
3552    case 'T':
3553    case 0x162:
3554    case 0x164:
3555    case 0x166:
3556    case 0x1ac:
3557    case 0x1ae:
3558    case 0x21a:
3559    case 0x23e:
3560    case 0x1e6a:
3561    case 0x1e6c:
3562    case 0x1e6e:
3563    case 0x1e70:
3564      regmbc('T'); regmbc(0x162); regmbc(0x164);
3565      regmbc(0x166); regmbc(0x1ac); regmbc(0x23e);
3566      regmbc(0x1ae); regmbc(0x21a); regmbc(0x1e6a);
3567      regmbc(0x1e6c); regmbc(0x1e6e); regmbc(0x1e70);
3568      return;
3569    case 'U':
3570    case 0xd9:
3571    case 0xda:
3572    case 0xdb:
3573    case 0xdc:
3574    case 0x168:
3575    case 0x16a:
3576    case 0x16c:
3577    case 0x16e:
3578    case 0x170:
3579    case 0x172:
3580    case 0x1af:
3581    case 0x1d3:
3582    case 0x1d5:
3583    case 0x1d7:
3584    case 0x1d9:
3585    case 0x1db:
3586    case 0x214:
3587    case 0x216:
3588    case 0x244:
3589    case 0x1e72:
3590    case 0x1e74:
3591    case 0x1e76:
3592    case 0x1e78:
3593    case 0x1e7a:
3594    case 0x1ee4:
3595    case 0x1ee6:
3596    case 0x1ee8:
3597    case 0x1eea:
3598    case 0x1eec:
3599    case 0x1eee:
3600    case 0x1ef0:
3601      regmbc('U'); regmbc(0xd9); regmbc(0xda);
3602      regmbc(0xdb); regmbc(0xdc); regmbc(0x168);
3603      regmbc(0x16a); regmbc(0x16c); regmbc(0x16e);
3604      regmbc(0x170); regmbc(0x172); regmbc(0x1af);
3605      regmbc(0x1d3); regmbc(0x1d5); regmbc(0x1d7);
3606      regmbc(0x1d9); regmbc(0x1db); regmbc(0x214);
3607      regmbc(0x216); regmbc(0x244); regmbc(0x1e72);
3608      regmbc(0x1e74); regmbc(0x1e76); regmbc(0x1e78);
3609      regmbc(0x1e7a); regmbc(0x1ee4); regmbc(0x1ee6);
3610      regmbc(0x1ee8); regmbc(0x1eea); regmbc(0x1eec);
3611      regmbc(0x1eee); regmbc(0x1ef0);
3612      return;
3613    case 'V':
3614    case 0x1b2:
3615    case 0x1e7c:
3616    case 0x1e7e:
3617      regmbc('V'); regmbc(0x1b2); regmbc(0x1e7c);
3618      regmbc(0x1e7e);
3619      return;
3620    case 'W':
3621    case 0x174:
3622    case 0x1e80:
3623    case 0x1e82:
3624    case 0x1e84:
3625    case 0x1e86:
3626    case 0x1e88:
3627      regmbc('W'); regmbc(0x174); regmbc(0x1e80);
3628      regmbc(0x1e82); regmbc(0x1e84); regmbc(0x1e86);
3629      regmbc(0x1e88);
3630      return;
3631    case 'X':
3632    case 0x1e8a:
3633    case 0x1e8c:
3634      regmbc('X'); regmbc(0x1e8a); regmbc(0x1e8c);
3635      return;
3636    case 'Y':
3637    case 0xdd:
3638    case 0x176:
3639    case 0x178:
3640    case 0x1b3:
3641    case 0x232:
3642    case 0x24e:
3643    case 0x1e8e:
3644    case 0x1ef2:
3645    case 0x1ef6:
3646    case 0x1ef4:
3647    case 0x1ef8:
3648      regmbc('Y'); regmbc(0xdd); regmbc(0x176);
3649      regmbc(0x178); regmbc(0x1b3); regmbc(0x232);
3650      regmbc(0x24e); regmbc(0x1e8e); regmbc(0x1ef2);
3651      regmbc(0x1ef4); regmbc(0x1ef6); regmbc(0x1ef8);
3652      return;
3653    case 'Z':
3654    case 0x179:
3655    case 0x17b:
3656    case 0x17d:
3657    case 0x1b5:
3658    case 0x1e90:
3659    case 0x1e92:
3660    case 0x1e94:
3661    case 0x2c6b:
3662      regmbc('Z'); regmbc(0x179); regmbc(0x17b);
3663      regmbc(0x17d); regmbc(0x1b5); regmbc(0x1e90);
3664      regmbc(0x1e92); regmbc(0x1e94); regmbc(0x2c6b);
3665      return;
3666    case 'a':
3667    case 0xe0:
3668    case 0xe1:
3669    case 0xe2:
3670    case 0xe3:
3671    case 0xe4:
3672    case 0xe5:
3673    case 0x101:
3674    case 0x103:
3675    case 0x105:
3676    case 0x1ce:
3677    case 0x1df:
3678    case 0x1e1:
3679    case 0x1fb:
3680    case 0x201:
3681    case 0x203:
3682    case 0x227:
3683    case 0x1d8f:
3684    case 0x1e01:
3685    case 0x1e9a:
3686    case 0x1ea1:
3687    case 0x1ea3:
3688    case 0x1ea5:
3689    case 0x1ea7:
3690    case 0x1ea9:
3691    case 0x1eab:
3692    case 0x1ead:
3693    case 0x1eaf:
3694    case 0x1eb1:
3695    case 0x1eb3:
3696    case 0x1eb5:
3697    case 0x1eb7:
3698    case 0x2c65:
3699      regmbc('a'); regmbc(0xe0); regmbc(0xe1);
3700      regmbc(0xe2); regmbc(0xe3); regmbc(0xe4);
3701      regmbc(0xe5); regmbc(0x101); regmbc(0x103);
3702      regmbc(0x105); regmbc(0x1ce); regmbc(0x1df);
3703      regmbc(0x1e1); regmbc(0x1fb); regmbc(0x201);
3704      regmbc(0x203); regmbc(0x227); regmbc(0x1d8f);
3705      regmbc(0x1e01); regmbc(0x1e9a); regmbc(0x1ea1);
3706      regmbc(0x1ea3); regmbc(0x1ea5); regmbc(0x1ea7);
3707      regmbc(0x1ea9); regmbc(0x1eab); regmbc(0x1ead);
3708      regmbc(0x1eaf); regmbc(0x1eb1); regmbc(0x1eb3);
3709      regmbc(0x1eb5); regmbc(0x1eb7); regmbc(0x2c65);
3710      return;
3711    case 'b':
3712    case 0x180:
3713    case 0x253:
3714    case 0x1d6c:
3715    case 0x1d80:
3716    case 0x1e03:
3717    case 0x1e05:
3718    case 0x1e07:
3719      regmbc('b');
3720      regmbc(0x180); regmbc(0x253); regmbc(0x1d6c);
3721      regmbc(0x1d80); regmbc(0x1e03); regmbc(0x1e05);
3722      regmbc(0x1e07);
3723      return;
3724    case 'c':
3725    case 0xe7:
3726    case 0x107:
3727    case 0x109:
3728    case 0x10b:
3729    case 0x10d:
3730    case 0x188:
3731    case 0x23c:
3732    case 0x1e09:
3733    case 0xa793:
3734    case 0xa794:
3735      regmbc('c'); regmbc(0xe7); regmbc(0x107);
3736      regmbc(0x109); regmbc(0x10b); regmbc(0x10d);
3737      regmbc(0x188); regmbc(0x23c); regmbc(0x1e09);
3738      regmbc(0xa793); regmbc(0xa794);
3739      return;
3740    case 'd':
3741    case 0x10f:
3742    case 0x111:
3743    case 0x257:
3744    case 0x1d6d:
3745    case 0x1d81:
3746    case 0x1d91:
3747    case 0x1e0b:
3748    case 0x1e0d:
3749    case 0x1e0f:
3750    case 0x1e11:
3751    case 0x1e13:
3752      regmbc('d'); regmbc(0x10f); regmbc(0x111);
3753      regmbc(0x257); regmbc(0x1d6d); regmbc(0x1d81);
3754      regmbc(0x1d91); regmbc(0x1e0b); regmbc(0x1e0d);
3755      regmbc(0x1e0f); regmbc(0x1e11); regmbc(0x1e13);
3756      return;
3757    case 'e':
3758    case 0xe8:
3759    case 0xe9:
3760    case 0xea:
3761    case 0xeb:
3762    case 0x113:
3763    case 0x115:
3764    case 0x117:
3765    case 0x119:
3766    case 0x11b:
3767    case 0x205:
3768    case 0x207:
3769    case 0x229:
3770    case 0x247:
3771    case 0x1d92:
3772    case 0x1e15:
3773    case 0x1e17:
3774    case 0x1e19:
3775    case 0x1e1b:
3776    case 0x1eb9:
3777    case 0x1ebb:
3778    case 0x1e1d:
3779    case 0x1ebd:
3780    case 0x1ebf:
3781    case 0x1ec1:
3782    case 0x1ec3:
3783    case 0x1ec5:
3784    case 0x1ec7:
3785      regmbc('e'); regmbc(0xe8); regmbc(0xe9);
3786      regmbc(0xea); regmbc(0xeb); regmbc(0x113);
3787      regmbc(0x115); regmbc(0x117); regmbc(0x119);
3788      regmbc(0x11b); regmbc(0x205); regmbc(0x207);
3789      regmbc(0x229); regmbc(0x247); regmbc(0x1d92);
3790      regmbc(0x1e15); regmbc(0x1e17); regmbc(0x1e19);
3791      regmbc(0x1e1b); regmbc(0x1e1d); regmbc(0x1eb9);
3792      regmbc(0x1ebb); regmbc(0x1ebd); regmbc(0x1ebf);
3793      regmbc(0x1ec1); regmbc(0x1ec3); regmbc(0x1ec5);
3794      regmbc(0x1ec7);
3795      return;
3796    case 'f':
3797    case 0x192:
3798    case 0x1d6e:
3799    case 0x1d82:
3800    case 0x1e1f:
3801    case 0xa799:
3802      regmbc('f'); regmbc(0x192); regmbc(0x1d6e);
3803      regmbc(0x1d82); regmbc(0x1e1f); regmbc(0xa799);
3804      return;
3805    case 'g':
3806    case 0x11d:
3807    case 0x11f:
3808    case 0x121:
3809    case 0x123:
3810    case 0x1e5:
3811    case 0x1e7:
3812    case 0x260:
3813    case 0x1f5:
3814    case 0x1d83:
3815    case 0x1e21:
3816    case 0xa7a1:
3817      regmbc('g'); regmbc(0x11d); regmbc(0x11f);
3818      regmbc(0x121); regmbc(0x123); regmbc(0x1e5);
3819      regmbc(0x1e7); regmbc(0x1f5); regmbc(0x260);
3820      regmbc(0x1d83); regmbc(0x1e21); regmbc(0xa7a1);
3821      return;
3822    case 'h':
3823    case 0x125:
3824    case 0x127:
3825    case 0x21f:
3826    case 0x1e23:
3827    case 0x1e25:
3828    case 0x1e27:
3829    case 0x1e29:
3830    case 0x1e2b:
3831    case 0x1e96:
3832    case 0x2c68:
3833    case 0xa795:
3834      regmbc('h'); regmbc(0x125); regmbc(0x127);
3835      regmbc(0x21f); regmbc(0x1e23); regmbc(0x1e25);
3836      regmbc(0x1e27); regmbc(0x1e29); regmbc(0x1e2b);
3837      regmbc(0x1e96); regmbc(0x2c68); regmbc(0xa795);
3838      return;
3839    case 'i':
3840    case 0xec:
3841    case 0xed:
3842    case 0xee:
3843    case 0xef:
3844    case 0x129:
3845    case 0x12b:
3846    case 0x12d:
3847    case 0x12f:
3848    case 0x1d0:
3849    case 0x209:
3850    case 0x20b:
3851    case 0x268:
3852    case 0x1d96:
3853    case 0x1e2d:
3854    case 0x1e2f:
3855    case 0x1ec9:
3856    case 0x1ecb:
3857      regmbc('i'); regmbc(0xec); regmbc(0xed);
3858      regmbc(0xee); regmbc(0xef); regmbc(0x129);
3859      regmbc(0x12b); regmbc(0x12d); regmbc(0x12f);
3860      regmbc(0x1d0); regmbc(0x209); regmbc(0x20b);
3861      regmbc(0x268); regmbc(0x1d96); regmbc(0x1e2d);
3862      regmbc(0x1e2f); regmbc(0x1ec9); regmbc(0x1ecb);
3863      return;
3864    case 'j':
3865    case 0x135:
3866    case 0x1f0:
3867    case 0x249:
3868      regmbc('j'); regmbc(0x135); regmbc(0x1f0);
3869      regmbc(0x249);
3870      return;
3871    case 'k':
3872    case 0x137:
3873    case 0x199:
3874    case 0x1e9:
3875    case 0x1d84:
3876    case 0x1e31:
3877    case 0x1e33:
3878    case 0x1e35:
3879    case 0x2c6a:
3880    case 0xa741:
3881      regmbc('k'); regmbc(0x137); regmbc(0x199);
3882      regmbc(0x1e9); regmbc(0x1d84); regmbc(0x1e31);
3883      regmbc(0x1e33); regmbc(0x1e35); regmbc(0x2c6a);
3884      regmbc(0xa741);
3885      return;
3886    case 'l':
3887    case 0x13a:
3888    case 0x13c:
3889    case 0x13e:
3890    case 0x140:
3891    case 0x142:
3892    case 0x19a:
3893    case 0x1e37:
3894    case 0x1e39:
3895    case 0x1e3b:
3896    case 0x1e3d:
3897    case 0x2c61:
3898      regmbc('l'); regmbc(0x13a); regmbc(0x13c);
3899      regmbc(0x13e); regmbc(0x140); regmbc(0x142);
3900      regmbc(0x19a); regmbc(0x1e37); regmbc(0x1e39);
3901      regmbc(0x1e3b); regmbc(0x1e3d); regmbc(0x2c61);
3902      return;
3903    case 'm':
3904    case 0x1d6f:
3905    case 0x1e3f:
3906    case 0x1e41:
3907    case 0x1e43:
3908      regmbc('m'); regmbc(0x1d6f); regmbc(0x1e3f);
3909      regmbc(0x1e41); regmbc(0x1e43);
3910      return;
3911    case 'n':
3912    case 0xf1:
3913    case 0x144:
3914    case 0x146:
3915    case 0x148:
3916    case 0x149:
3917    case 0x1f9:
3918    case 0x1d70:
3919    case 0x1d87:
3920    case 0x1e45:
3921    case 0x1e47:
3922    case 0x1e49:
3923    case 0x1e4b:
3924    case 0xa7a5:
3925      regmbc('n'); regmbc(0xf1); regmbc(0x144);
3926      regmbc(0x146); regmbc(0x148); regmbc(0x149);
3927      regmbc(0x1f9); regmbc(0x1d70); regmbc(0x1d87);
3928      regmbc(0x1e45); regmbc(0x1e47); regmbc(0x1e49);
3929      regmbc(0x1e4b); regmbc(0xa7a5);
3930      return;
3931    case 'o':
3932    case 0xf2:
3933    case 0xf3:
3934    case 0xf4:
3935    case 0xf5:
3936    case 0xf6:
3937    case 0xf8:
3938    case 0x14d:
3939    case 0x14f:
3940    case 0x151:
3941    case 0x1a1:
3942    case 0x1d2:
3943    case 0x1eb:
3944    case 0x1ed:
3945    case 0x1ff:
3946    case 0x20d:
3947    case 0x20f:
3948    case 0x22b:
3949    case 0x22d:
3950    case 0x22f:
3951    case 0x231:
3952    case 0x275:
3953    case 0x1e4d:
3954    case 0x1e4f:
3955    case 0x1e51:
3956    case 0x1e53:
3957    case 0x1ecd:
3958    case 0x1ecf:
3959    case 0x1ed1:
3960    case 0x1ed3:
3961    case 0x1ed5:
3962    case 0x1ed7:
3963    case 0x1ed9:
3964    case 0x1edb:
3965    case 0x1edd:
3966    case 0x1edf:
3967    case 0x1ee1:
3968    case 0x1ee3:
3969      regmbc('o'); regmbc(0xf2); regmbc(0xf3);
3970      regmbc(0xf4); regmbc(0xf5); regmbc(0xf6);
3971      regmbc(0xf8); regmbc(0x14d); regmbc(0x14f);
3972      regmbc(0x151); regmbc(0x1a1); regmbc(0x1d2);
3973      regmbc(0x1eb); regmbc(0x1ed); regmbc(0x1ff);
3974      regmbc(0x20d); regmbc(0x20f); regmbc(0x22b);
3975      regmbc(0x22d); regmbc(0x22f); regmbc(0x231);
3976      regmbc(0x275); regmbc(0x1e4d); regmbc(0x1e4f);
3977      regmbc(0x1e51); regmbc(0x1e53); regmbc(0x1ecd);
3978      regmbc(0x1ecf); regmbc(0x1ed1); regmbc(0x1ed3);
3979      regmbc(0x1ed5); regmbc(0x1ed7); regmbc(0x1ed9);
3980      regmbc(0x1edb); regmbc(0x1edd); regmbc(0x1edf);
3981      regmbc(0x1ee1); regmbc(0x1ee3);
3982      return;
3983    case 'p':
3984    case 0x1a5:
3985    case 0x1d71:
3986    case 0x1d88:
3987    case 0x1d7d:
3988    case 0x1e55:
3989    case 0x1e57:
3990      regmbc('p'); regmbc(0x1a5); regmbc(0x1d71);
3991      regmbc(0x1d7d); regmbc(0x1d88); regmbc(0x1e55);
3992      regmbc(0x1e57);
3993      return;
3994    case 'q':
3995    case 0x24b:
3996    case 0x2a0:
3997      regmbc('q'); regmbc(0x24b); regmbc(0x2a0);
3998      return;
3999    case 'r':
4000    case 0x155:
4001    case 0x157:
4002    case 0x159:
4003    case 0x211:
4004    case 0x213:
4005    case 0x24d:
4006    case 0x27d:
4007    case 0x1d72:
4008    case 0x1d73:
4009    case 0x1d89:
4010    case 0x1e59:
4011    case 0x1e5b:
4012    case 0x1e5d:
4013    case 0x1e5f:
4014    case 0xa7a7:
4015      regmbc('r'); regmbc(0x155); regmbc(0x157);
4016      regmbc(0x159); regmbc(0x211); regmbc(0x213);
4017      regmbc(0x24d); regmbc(0x1d72); regmbc(0x1d73);
4018      regmbc(0x1d89); regmbc(0x1e59); regmbc(0x27d);
4019      regmbc(0x1e5b); regmbc(0x1e5d); regmbc(0x1e5f);
4020      regmbc(0xa7a7);
4021      return;
4022    case 's':
4023    case 0x15b:
4024    case 0x15d:
4025    case 0x15f:
4026    case 0x161:
4027    case 0x1e61:
4028    case 0x219:
4029    case 0x23f:
4030    case 0x1d74:
4031    case 0x1d8a:
4032    case 0x1e63:
4033    case 0x1e65:
4034    case 0x1e67:
4035    case 0x1e69:
4036    case 0xa7a9:
4037      regmbc('s'); regmbc(0x15b); regmbc(0x15d);
4038      regmbc(0x15f); regmbc(0x161); regmbc(0x23f);
4039      regmbc(0x219); regmbc(0x1d74); regmbc(0x1d8a);
4040      regmbc(0x1e61); regmbc(0x1e63); regmbc(0x1e65);
4041      regmbc(0x1e67); regmbc(0x1e69); regmbc(0xa7a9);
4042      return;
4043    case 't':
4044    case 0x163:
4045    case 0x165:
4046    case 0x167:
4047    case 0x1ab:
4048    case 0x1ad:
4049    case 0x21b:
4050    case 0x288:
4051    case 0x1d75:
4052    case 0x1e6b:
4053    case 0x1e6d:
4054    case 0x1e6f:
4055    case 0x1e71:
4056    case 0x1e97:
4057    case 0x2c66:
4058      regmbc('t'); regmbc(0x163); regmbc(0x165);
4059      regmbc(0x167); regmbc(0x1ab); regmbc(0x21b);
4060      regmbc(0x1ad); regmbc(0x288); regmbc(0x1d75);
4061      regmbc(0x1e6b); regmbc(0x1e6d); regmbc(0x1e6f);
4062      regmbc(0x1e71); regmbc(0x1e97); regmbc(0x2c66);
4063      return;
4064    case 'u':
4065    case 0xf9:
4066    case 0xfa:
4067    case 0xfb:
4068    case 0xfc:
4069    case 0x169:
4070    case 0x16b:
4071    case 0x16d:
4072    case 0x16f:
4073    case 0x171:
4074    case 0x173:
4075    case 0x1b0:
4076    case 0x1d4:
4077    case 0x1d6:
4078    case 0x1d8:
4079    case 0x1da:
4080    case 0x1dc:
4081    case 0x215:
4082    case 0x217:
4083    case 0x289:
4084    case 0x1e73:
4085    case 0x1d7e:
4086    case 0x1d99:
4087    case 0x1e75:
4088    case 0x1e77:
4089    case 0x1e79:
4090    case 0x1e7b:
4091    case 0x1ee5:
4092    case 0x1ee7:
4093    case 0x1ee9:
4094    case 0x1eeb:
4095    case 0x1eed:
4096    case 0x1eef:
4097    case 0x1ef1:
4098      regmbc('u'); regmbc(0xf9); regmbc(0xfa);
4099      regmbc(0xfb); regmbc(0xfc); regmbc(0x169);
4100      regmbc(0x16b); regmbc(0x16d); regmbc(0x16f);
4101      regmbc(0x171); regmbc(0x173); regmbc(0x1d6);
4102      regmbc(0x1d8); regmbc(0x1da); regmbc(0x1dc);
4103      regmbc(0x215); regmbc(0x217); regmbc(0x1b0);
4104      regmbc(0x1d4); regmbc(0x289); regmbc(0x1d7e);
4105      regmbc(0x1d99); regmbc(0x1e73); regmbc(0x1e75);
4106      regmbc(0x1e77); regmbc(0x1e79); regmbc(0x1e7b);
4107      regmbc(0x1ee5); regmbc(0x1ee7); regmbc(0x1ee9);
4108      regmbc(0x1eeb); regmbc(0x1eed); regmbc(0x1eef);
4109      regmbc(0x1ef1);
4110      return;
4111    case 'v':
4112    case 0x28b:
4113    case 0x1d8c:
4114    case 0x1e7d:
4115    case 0x1e7f:
4116      regmbc('v'); regmbc(0x28b); regmbc(0x1d8c);
4117      regmbc(0x1e7d); regmbc(0x1e7f);
4118      return;
4119    case 'w':
4120    case 0x175:
4121    case 0x1e81:
4122    case 0x1e83:
4123    case 0x1e85:
4124    case 0x1e87:
4125    case 0x1e89:
4126    case 0x1e98:
4127      regmbc('w'); regmbc(0x175); regmbc(0x1e81);
4128      regmbc(0x1e83); regmbc(0x1e85); regmbc(0x1e87);
4129      regmbc(0x1e89); regmbc(0x1e98);
4130      return;
4131    case 'x':
4132    case 0x1e8b:
4133    case 0x1e8d:
4134      regmbc('x'); regmbc(0x1e8b); regmbc(0x1e8d);
4135      return;
4136    case 'y':
4137    case 0xfd:
4138    case 0xff:
4139    case 0x177:
4140    case 0x1b4:
4141    case 0x233:
4142    case 0x24f:
4143    case 0x1e8f:
4144    case 0x1e99:
4145    case 0x1ef3:
4146    case 0x1ef5:
4147    case 0x1ef7:
4148    case 0x1ef9:
4149      regmbc('y'); regmbc(0xfd); regmbc(0xff);
4150      regmbc(0x177); regmbc(0x1b4); regmbc(0x233);
4151      regmbc(0x24f); regmbc(0x1e8f); regmbc(0x1e99);
4152      regmbc(0x1ef3); regmbc(0x1ef5); regmbc(0x1ef7);
4153      regmbc(0x1ef9);
4154      return;
4155    case 'z':
4156    case 0x17a:
4157    case 0x17c:
4158    case 0x17e:
4159    case 0x1b6:
4160    case 0x1d76:
4161    case 0x1d8e:
4162    case 0x1e91:
4163    case 0x1e93:
4164    case 0x1e95:
4165    case 0x2c6c:
4166      regmbc('z'); regmbc(0x17a); regmbc(0x17c);
4167      regmbc(0x17e); regmbc(0x1b6); regmbc(0x1d76);
4168      regmbc(0x1d8e); regmbc(0x1e91); regmbc(0x1e93);
4169      regmbc(0x1e95); regmbc(0x2c6c);
4170      return;
4171    }
4172  }
4173  regmbc(c);
4174}
4175
4176// Emit a node.
4177// Return pointer to generated code.
4178static uint8_t *regnode(int op)
4179{
4180  uint8_t *ret;
4181
4182  ret = regcode;
4183  if (ret == JUST_CALC_SIZE) {
4184    regsize += 3;
4185  } else {
4186    *regcode++ = (uint8_t)op;
4187    *regcode++ = NUL;                   // Null "next" pointer.
4188    *regcode++ = NUL;
4189  }
4190  return ret;
4191}
4192
4193// Write a four bytes number at "p" and return pointer to the next char.
4194static uint8_t *re_put_uint32(uint8_t *p, uint32_t val)
4195{
4196  *p++ = (uint8_t)((val >> 24) & 0377);
4197  *p++ = (uint8_t)((val >> 16) & 0377);
4198  *p++ = (uint8_t)((val >> 8) & 0377);
4199  *p++ = (uint8_t)(val & 0377);
4200  return p;
4201}
4202
4203// regnext - dig the "next" pointer out of a node
4204// Returns NULL when calculating size, when there is no next item and when
4205// there is an error.
4206static uint8_t *regnext(uint8_t *p)
4207  FUNC_ATTR_NONNULL_ALL
4208{
4209  int offset;
4210
4211  if (p == JUST_CALC_SIZE || reg_toolong) {
4212    return NULL;
4213  }
4214
4215  offset = NEXT(p);
4216  if (offset == 0) {
4217    return NULL;
4218  }
4219
4220  if (OP(p) == BACK) {
4221    return p - offset;
4222  } else {
4223    return p + offset;
4224  }
4225}
4226
4227// Set the next-pointer at the end of a node chain.
4228static void regtail(uint8_t *p, const uint8_t *val)
4229{
4230  int offset;
4231
4232  if (p == JUST_CALC_SIZE) {
4233    return;
4234  }
4235
4236  // Find last node.
4237  uint8_t *scan = p;
4238  while (true) {
4239    uint8_t *temp = regnext(scan);
4240    if (temp == NULL) {
4241      break;
4242    }
4243    scan = temp;
4244  }
4245
4246  if (OP(scan) == BACK) {
4247    offset = (int)(scan - val);
4248  } else {
4249    offset = (int)(val - scan);
4250  }
4251  // When the offset uses more than 16 bits it can no longer fit in the two
4252  // bytes available.  Use a global flag to avoid having to check return
4253  // values in too many places.
4254  if (offset > 0xffff) {
4255    reg_toolong = true;
4256  } else {
4257    *(scan + 1) = (uint8_t)(((unsigned)offset >> 8) & 0377);
4258    *(scan + 2) = (uint8_t)(offset & 0377);
4259  }
4260}
4261
4262// Like regtail, on item after a BRANCH; nop if none.
4263static void regoptail(uint8_t *p, uint8_t *val)
4264{
4265  // When op is neither BRANCH nor BRACE_COMPLEX0-9, it is "operandless"
4266  if (p == NULL || p == JUST_CALC_SIZE
4267      || (OP(p) != BRANCH
4268          && (OP(p) < BRACE_COMPLEX || OP(p) > BRACE_COMPLEX + 9))) {
4269    return;
4270  }
4271  regtail(OPERAND(p), val);
4272}
4273
4274// Insert an operator in front of already-emitted operand
4275//
4276// Means relocating the operand.
4277static void reginsert(int op, uint8_t *opnd)
4278{
4279  uint8_t *src;
4280  uint8_t *dst;
4281  uint8_t *place;
4282
4283  if (regcode == JUST_CALC_SIZE) {
4284    regsize += 3;
4285    return;
4286  }
4287  src = regcode;
4288  regcode += 3;
4289  dst = regcode;
4290  while (src > opnd) {
4291    *--dst = *--src;
4292  }
4293
4294  place = opnd;                 // Op node, where operand used to be.
4295  *place++ = (uint8_t)op;
4296  *place++ = NUL;
4297  *place = NUL;
4298}
4299
4300// Insert an operator in front of already-emitted operand.
4301// Add a number to the operator.
4302static void reginsert_nr(int op, int64_t val, uint8_t *opnd)
4303{
4304  uint8_t *src;
4305  uint8_t *dst;
4306  uint8_t *place;
4307
4308  if (regcode == JUST_CALC_SIZE) {
4309    regsize += 7;
4310    return;
4311  }
4312  src = regcode;
4313  regcode += 7;
4314  dst = regcode;
4315  while (src > opnd) {
4316    *--dst = *--src;
4317  }
4318
4319  place = opnd;                 // Op node, where operand used to be.
4320  *place++ = (uint8_t)op;
4321  *place++ = NUL;
4322  *place++ = NUL;
4323  assert(val >= 0 && (uintmax_t)val <= UINT32_MAX);
4324  re_put_uint32(place, (uint32_t)val);
4325}
4326
4327// Insert an operator in front of already-emitted operand.
4328// The operator has the given limit values as operands.  Also set next pointer.
4329//
4330// Means relocating the operand.
4331static void reginsert_limits(int op, int64_t minval, int64_t maxval, uint8_t *opnd)
4332{
4333  uint8_t *src;
4334  uint8_t *dst;
4335  uint8_t *place;
4336
4337  if (regcode == JUST_CALC_SIZE) {
4338    regsize += 11;
4339    return;
4340  }
4341  src = regcode;
4342  regcode += 11;
4343  dst = regcode;
4344  while (src > opnd) {
4345    *--dst = *--src;
4346  }
4347
4348  place = opnd;                 // Op node, where operand used to be.
4349  *place++ = (uint8_t)op;
4350  *place++ = NUL;
4351  *place++ = NUL;
4352  assert(minval >= 0 && (uintmax_t)minval <= UINT32_MAX);
4353  place = re_put_uint32(place, (uint32_t)minval);
4354  assert(maxval >= 0 && (uintmax_t)maxval <= UINT32_MAX);
4355  place = re_put_uint32(place, (uint32_t)maxval);
4356  regtail(opnd, place);
4357}
4358
4359/// Return true if the back reference is legal. We must have seen the close
4360/// brace.
4361/// TODO(vim): Should also check that we don't refer to something repeated
4362/// (+*=): what instance of the repetition should we match?
4363static int seen_endbrace(int refnum)
4364{
4365  if (!had_endbrace[refnum]) {
4366    uint8_t *p;
4367
4368    // Trick: check if "@<=" or "@<!" follows, in which case
4369    // the \1 can appear before the referenced match.
4370    for (p = (uint8_t *)regparse; *p != NUL; p++) {
4371      if (p[0] == '@' && p[1] == '<' && (p[2] == '!' || p[2] == '=')) {
4372        break;
4373      }
4374    }
4375
4376    if (*p == NUL) {
4377      emsg(_("E65: Illegal back reference"));
4378      rc_did_emsg = true;
4379      return false;
4380    }
4381  }
4382  return true;
4383}
4384
4385// Parse the lowest level.
4386//
4387// Optimization:  gobbles an entire sequence of ordinary characters so that
4388// it can turn them into a single node, which is smaller to store and
4389// faster to run.  Don't do this when one_exactly is set.
4390static uint8_t *regatom(int *flagp)
4391{
4392  uint8_t *ret;
4393  int flags;
4394  int c;
4395  uint8_t *p;
4396  int extra = 0;
4397  int save_prev_at_start = prev_at_start;
4398
4399  *flagp = WORST;               // Tentatively.
4400
4401  c = getchr();
4402  switch (c) {
4403  case Magic('^'):
4404    ret = regnode(BOL);
4405    break;
4406
4407  case Magic('$'):
4408    ret = regnode(EOL);
4409    had_eol = true;
4410    break;
4411
4412  case Magic('<'):
4413    ret = regnode(BOW);
4414    break;
4415
4416  case Magic('>'):
4417    ret = regnode(EOW);
4418    break;
4419
4420  case Magic('_'):
4421    c = no_Magic(getchr());
4422    if (c == '^') {             // "\_^" is start-of-line
4423      ret = regnode(BOL);
4424      break;
4425    }
4426    if (c == '$') {             // "\_$" is end-of-line
4427      ret = regnode(EOL);
4428      had_eol = true;
4429      break;
4430    }
4431
4432    extra = ADD_NL;
4433    *flagp |= HASNL;
4434
4435    // "\_[" is character range plus newline
4436    if (c == '[') {
4437      goto collection;
4438    }
4439
4440    // "\_x" is character class plus newline
4441    FALLTHROUGH;
4442
4443  // Character classes.
4444  case Magic('.'):
4445  case Magic('i'):
4446  case Magic('I'):
4447  case Magic('k'):
4448  case Magic('K'):
4449  case Magic('f'):
4450  case Magic('F'):
4451  case Magic('p'):
4452  case Magic('P'):
4453  case Magic('s'):
4454  case Magic('S'):
4455  case Magic('d'):
4456  case Magic('D'):
4457  case Magic('x'):
4458  case Magic('X'):
4459  case Magic('o'):
4460  case Magic('O'):
4461  case Magic('w'):
4462  case Magic('W'):
4463  case Magic('h'):
4464  case Magic('H'):
4465  case Magic('a'):
4466  case Magic('A'):
4467  case Magic('l'):
4468  case Magic('L'):
4469  case Magic('u'):
4470  case Magic('U'):
4471    p = (uint8_t *)vim_strchr((char *)classchars, no_Magic(c));
4472    if (p == NULL) {
4473      EMSG_RET_NULL(_(e_invalid_use_of_underscore));
4474    }
4475    // When '.' is followed by a composing char ignore the dot, so that
4476    // the composing char is matched here.
4477    if (c == Magic('.') && utf_iscomposing_legacy(peekchr())) {
4478      c = getchr();
4479      goto do_multibyte;
4480    }
4481    ret = regnode(classcodes[p - classchars] + extra);
4482    *flagp |= HASWIDTH | SIMPLE;
4483    break;
4484
4485  case Magic('n'):
4486    if (reg_string) {
4487      // In a string "\n" matches a newline character.
4488      ret = regnode(EXACTLY);
4489      regc(NL);
4490      regc(NUL);
4491      *flagp |= HASWIDTH | SIMPLE;
4492    } else {
4493      // In buffer text "\n" matches the end of a line.
4494      ret = regnode(NEWL);
4495      *flagp |= HASWIDTH | HASNL;
4496    }
4497    break;
4498
4499  case Magic('('):
4500    if (one_exactly) {
4501      EMSG_ONE_RET_NULL;
4502    }
4503    ret = reg(REG_PAREN, &flags);
4504    if (ret == NULL) {
4505      return NULL;
4506    }
4507    *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
4508    break;
4509
4510  case NUL:
4511  case Magic('|'):
4512  case Magic('&'):
4513  case Magic(')'):
4514    if (one_exactly) {
4515      EMSG_ONE_RET_NULL;
4516    }
4517    // Supposed to be caught earlier.
4518    IEMSG_RET_NULL(_(e_internal_error_in_regexp));
4519  // NOTREACHED
4520
4521  case Magic('='):
4522  case Magic('?'):
4523  case Magic('+'):
4524  case Magic('@'):
4525  case Magic('{'):
4526  case Magic('*'):
4527    c = no_Magic(c);
4528    EMSG3_RET_NULL(_("E64: %s%c follows nothing"),
4529                   (c == '*' ? reg_magic >= MAGIC_ON : reg_magic == MAGIC_ALL), c);
4530  // NOTREACHED
4531
4532  case Magic('~'):              // previous substitute pattern
4533    if (reg_prev_sub != NULL) {
4534      uint8_t *lp;
4535
4536      ret = regnode(EXACTLY);
4537      lp = (uint8_t *)reg_prev_sub;
4538      while (*lp != NUL) {
4539        regc(*lp++);
4540      }
4541      regc(NUL);
4542      if (*reg_prev_sub != NUL) {
4543        *flagp |= HASWIDTH;
4544        if ((lp - (uint8_t *)reg_prev_sub) == 1) {
4545          *flagp |= SIMPLE;
4546        }
4547      }
4548    } else {
4549      EMSG_RET_NULL(_(e_nopresub));
4550    }
4551    break;
4552
4553  case Magic('1'):
4554  case Magic('2'):
4555  case Magic('3'):
4556  case Magic('4'):
4557  case Magic('5'):
4558  case Magic('6'):
4559  case Magic('7'):
4560  case Magic('8'):
4561  case Magic('9'): {
4562    int refnum;
4563
4564    refnum = c - Magic('0');
4565    if (!seen_endbrace(refnum)) {
4566      return NULL;
4567    }
4568    ret = regnode(BACKREF + refnum);
4569  }
4570  break;
4571
4572  case Magic('z'):
4573    c = no_Magic(getchr());
4574    switch (c) {
4575    case '(':
4576      if ((reg_do_extmatch & REX_SET) == 0) {
4577        EMSG_RET_NULL(_(e_z_not_allowed));
4578      }
4579      if (one_exactly) {
4580        EMSG_ONE_RET_NULL;
4581      }
4582      ret = reg(REG_ZPAREN, &flags);
4583      if (ret == NULL) {
4584        return NULL;
4585      }
4586      *flagp |= flags & (HASWIDTH|SPSTART|HASNL|HASLOOKBH);
4587      re_has_z = REX_SET;
4588      break;
4589
4590    case '1':
4591    case '2':
4592    case '3':
4593    case '4':
4594    case '5':
4595    case '6':
4596    case '7':
4597    case '8':
4598    case '9':
4599      if ((reg_do_extmatch & REX_USE) == 0) {
4600        EMSG_RET_NULL(_(e_z1_not_allowed));
4601      }
4602      ret = regnode(ZREF + c - '0');
4603      re_has_z = REX_USE;
4604      break;
4605
4606    case 's':
4607      ret = regnode(MOPEN + 0);
4608      if (!re_mult_next("\\zs")) {
4609        return NULL;
4610      }
4611      break;
4612
4613    case 'e':
4614      ret = regnode(MCLOSE + 0);
4615      if (!re_mult_next("\\ze")) {
4616        return NULL;
4617      }
4618      break;
4619
4620    default:
4621      EMSG_RET_NULL(_("E68: Invalid character after \\z"));
4622    }
4623    break;
4624
4625  case Magic('%'):
4626    c = no_Magic(getchr());
4627    switch (c) {
4628    // () without a back reference
4629    case '(':
4630      if (one_exactly) {
4631        EMSG_ONE_RET_NULL;
4632      }
4633      ret = reg(REG_NPAREN, &flags);
4634      if (ret == NULL) {
4635        return NULL;
4636      }
4637      *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
4638      break;
4639
4640    // Catch \%^ and \%$ regardless of where they appear in the
4641    // pattern -- regardless of whether or not it makes sense.
4642    case '^':
4643      ret = regnode(RE_BOF);
4644      break;
4645
4646    case '$':
4647      ret = regnode(RE_EOF);
4648      break;
4649
4650    case '#':
4651      if (regparse[0] == '=' && regparse[1] >= 48 && regparse[1] <= 50) {
4652        // misplaced \%#=1
4653        semsg(_(e_atom_engine_must_be_at_start_of_pattern), regparse[1]);
4654        return FAIL;
4655      }
4656      ret = regnode(CURSOR);
4657      break;
4658
4659    case 'V':
4660      ret = regnode(RE_VISUAL);
4661      break;
4662
4663    case 'C':
4664      ret = regnode(RE_COMPOSING);
4665      break;
4666
4667    // \%[abc]: Emit as a list of branches, all ending at the last
4668    // branch which matches nothing.
4669    case '[':
4670      if (one_exactly) {                        // doesn't nest
4671        EMSG_ONE_RET_NULL;
4672      }
4673      {
4674        uint8_t *lastbranch;
4675        uint8_t *lastnode = NULL;
4676        uint8_t *br;
4677
4678        ret = NULL;
4679        while ((c = getchr()) != ']') {
4680          if (c == NUL) {
4681            EMSG2_RET_NULL(_(e_missing_sb),
4682                           reg_magic == MAGIC_ALL);
4683          }
4684          br = regnode(BRANCH);
4685          if (ret == NULL) {
4686            ret = br;
4687          } else {
4688            regtail(lastnode, br);
4689            if (reg_toolong) {
4690              return NULL;
4691            }
4692          }
4693
4694          ungetchr();
4695          one_exactly = true;
4696          lastnode = regatom(flagp);
4697          one_exactly = false;
4698          if (lastnode == NULL) {
4699            return NULL;
4700          }
4701        }
4702        if (ret == NULL) {
4703          EMSG2_RET_NULL(_(e_empty_sb),
4704                         reg_magic == MAGIC_ALL);
4705        }
4706        lastbranch = regnode(BRANCH);
4707        br = regnode(NOTHING);
4708        if (ret != JUST_CALC_SIZE) {
4709          regtail(lastnode, br);
4710          regtail(lastbranch, br);
4711          // connect all branches to the NOTHING
4712          // branch at the end
4713          for (br = ret; br != lastnode;) {
4714            if (OP(br) == BRANCH) {
4715              regtail(br, lastbranch);
4716              if (reg_toolong) {
4717                return NULL;
4718              }
4719              br = OPERAND(br);
4720            } else {
4721              br = regnext(br);
4722            }
4723          }
4724        }
4725        *flagp &= ~(HASWIDTH | SIMPLE);
4726        break;
4727      }
4728
4729    case 'd':               // %d123 decimal
4730    case 'o':               // %o123 octal
4731    case 'x':               // %xab hex 2
4732    case 'u':               // %uabcd hex 4
4733    case 'U':               // %U1234abcd hex 8
4734    {
4735      int64_t i;
4736
4737      switch (c) {
4738      case 'd':
4739        i = getdecchrs(); break;
4740      case 'o':
4741        i = getoctchrs(); break;
4742      case 'x':
4743        i = gethexchrs(2); break;
4744      case 'u':
4745        i = gethexchrs(4); break;
4746      case 'U':
4747        i = gethexchrs(8); break;
4748      default:
4749        i = -1; break;
4750      }
4751
4752      if (i < 0 || i > INT_MAX) {
4753        EMSG2_RET_NULL(_("E678: Invalid character after %s%%[dxouU]"),
4754                       reg_magic == MAGIC_ALL);
4755      }
4756      if (use_multibytecode((int)i)) {
4757        ret = regnode(MULTIBYTECODE);
4758      } else {
4759        ret = regnode(EXACTLY);
4760      }
4761      if (i == 0) {
4762        regc(0x0a);
4763      } else {
4764        regmbc((int)i);
4765      }
4766      regc(NUL);
4767      *flagp |= HASWIDTH;
4768      break;
4769    }
4770
4771    default:
4772      if (ascii_isdigit(c) || c == '<' || c == '>' || c == '\'' || c == '.') {
4773        uint32_t n = 0;
4774        int cmp;
4775        bool cur = false;
4776        bool got_digit = false;
4777
4778        cmp = c;
4779        if (cmp == '<' || cmp == '>') {
4780          c = getchr();
4781        }
4782        if (no_Magic(c) == '.') {
4783          cur = true;
4784          c = getchr();
4785        }
4786        while (ascii_isdigit(c)) {
4787          got_digit = true;
4788          n = n * 10 + (uint32_t)(c - '0');
4789          c = getchr();
4790        }
4791        if (no_Magic(c) == '\'' && n == 0) {
4792          // "\%'m", "\%<'m" and "\%>'m": Mark
4793          c = getchr();
4794          ret = regnode(RE_MARK);
4795          if (ret == JUST_CALC_SIZE) {
4796            regsize += 2;
4797          } else {
4798            *regcode++ = (uint8_t)c;
4799            *regcode++ = (uint8_t)cmp;
4800          }
4801          break;
4802        } else if ((c == 'l' || c == 'c' || c == 'v') && (cur || got_digit)) {
4803          if (cur && n) {
4804            semsg(_(e_regexp_number_after_dot_pos_search_chr), no_Magic(c));
4805            rc_did_emsg = true;
4806            return NULL;
4807          }
4808          if (c == 'l') {
4809            if (cur) {
4810              n = (uint32_t)curwin->w_cursor.lnum;
4811            }
4812            ret = regnode(RE_LNUM);
4813            if (save_prev_at_start) {
4814              at_start = true;
4815            }
4816          } else if (c == 'c') {
4817            if (cur) {
4818              n = (uint32_t)curwin->w_cursor.col;
4819              n++;
4820            }
4821            ret = regnode(RE_COL);
4822          } else {
4823            if (cur) {
4824              colnr_T vcol = 0;
4825              getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &vcol, 0);
4826              n = (uint32_t)(++vcol);
4827            }
4828            ret = regnode(RE_VCOL);
4829          }
4830          if (ret == JUST_CALC_SIZE) {
4831            regsize += 5;
4832          } else {
4833            // put the number and the optional
4834            // comparator after the opcode
4835            regcode = re_put_uint32(regcode, n);
4836            *regcode++ = (uint8_t)cmp;
4837          }
4838          break;
4839        }
4840      }
4841
4842      EMSG2_RET_NULL(_("E71: Invalid character after %s%%"),
4843                     reg_magic == MAGIC_ALL);
4844    }
4845    break;
4846
4847  case Magic('['):
4848collection:
4849    {
4850      uint8_t *lp;
4851
4852      // If there is no matching ']', we assume the '[' is a normal
4853      // character.  This makes 'incsearch' and ":help [" work.
4854      lp = (uint8_t *)skip_anyof(regparse);
4855      if (*lp == ']') {         // there is a matching ']'
4856        int startc = -1;                // > 0 when next '-' is a range
4857        int endc;
4858
4859        if (extra == 0) {
4860          int cl = bt_recognize_char_class((uint8_t *)regparse, lp);
4861
4862          if (cl != 0) {
4863            ret = regnode(cl);
4864            regparse = (char *)lp;
4865            skipchr();
4866            *flagp |= HASWIDTH | SIMPLE;
4867            break;
4868          }
4869        }
4870
4871        // In a character class, different parsing rules apply.
4872        // Not even \ is special anymore, nothing is.
4873        if (*regparse == '^') {             // Complement of range.
4874          ret = regnode(ANYBUT + extra);
4875          regparse++;
4876        } else {
4877          ret = regnode(ANYOF + extra);
4878        }
4879
4880        // At the start ']' and '-' mean the literal character.
4881        if (*regparse == ']' || *regparse == '-') {
4882          startc = (uint8_t)(*regparse);
4883          regc(*regparse++);
4884        }
4885
4886        while (*regparse != NUL && *regparse != ']') {
4887          if (*regparse == '-') {
4888            regparse++;
4889            // The '-' is not used for a range at the end and
4890            // after or before a '\n'.
4891            if (*regparse == ']' || *regparse == NUL
4892                || startc == -1
4893                || (regparse[0] == '\\' && regparse[1] == 'n')) {
4894              regc('-');
4895              startc = '-';                     // [--x] is a range
4896            } else {
4897              // Also accept "a-[.z.]"
4898              endc = 0;
4899              if (*regparse == '[') {
4900                endc = get_coll_element(&regparse);
4901              }
4902              if (endc == 0) {
4903                endc = mb_ptr2char_adv((const char **)&regparse);
4904              }
4905
4906              // Handle \o40, \x20 and \u20AC style sequences
4907              if (endc == '\\' && !reg_cpo_lit) {
4908                endc = coll_get_char();
4909              }
4910
4911              if (startc > endc) {
4912                EMSG_RET_NULL(_(e_reverse_range));
4913              }
4914              if (utf_char2len(startc) > 1
4915                  || utf_char2len(endc) > 1) {
4916                // Limit to a range of 256 chars
4917                if (endc > startc + 256) {
4918                  EMSG_RET_NULL(_(e_large_class));
4919                }
4920                while (++startc <= endc) {
4921                  regmbc(startc);
4922                }
4923              } else {
4924                while (++startc <= endc) {
4925                  regc(startc);
4926                }
4927              }
4928              startc = -1;
4929            }
4930          }
4931          // Only "\]", "\^", "\]" and "\\" are special in Vi.  Vim
4932          // accepts "\t", "\e", etc., but only when the 'l' flag in
4933          // 'cpoptions' is not included.
4934          else if (*regparse == '\\'
4935                   && (vim_strchr(REGEXP_INRANGE, (uint8_t)regparse[1]) != NULL
4936                       || (!reg_cpo_lit
4937                           && vim_strchr(REGEXP_ABBR,
4938                                         (uint8_t)regparse[1]) != NULL))) {
4939            regparse++;
4940            if (*regparse == 'n') {
4941              // '\n' in range: also match NL
4942              if (ret != JUST_CALC_SIZE) {
4943                // Using \n inside [^] does not change what
4944                // matches. "[^\n]" is the same as ".".
4945                if (*ret == ANYOF) {
4946                  *ret = ANYOF + ADD_NL;
4947                  *flagp |= HASNL;
4948                }
4949                // else: must have had a \n already
4950              }
4951              regparse++;
4952              startc = -1;
4953            } else if (*regparse == 'd'
4954                       || *regparse == 'o'
4955                       || *regparse == 'x'
4956                       || *regparse == 'u'
4957                       || *regparse == 'U') {
4958              startc = coll_get_char();
4959              // max UTF-8 Codepoint is U+10FFFF,
4960              // but allow values until INT_MAX
4961              if (startc == INT_MAX) {
4962                EMSG_RET_NULL(_(e_unicode_val_too_large));
4963              }
4964              if (startc == 0) {
4965                regc(0x0a);
4966              } else {
4967                regmbc(startc);
4968              }
4969            } else {
4970              startc = backslash_trans(*regparse++);
4971              regc(startc);
4972            }
4973          } else if (*regparse == '[') {
4974            int c_class;
4975            int cu;
4976
4977            c_class = get_char_class(&regparse);
4978            startc = -1;
4979            // Characters assumed to be 8 bits!
4980            switch (c_class) {
4981            case CLASS_NONE:
4982              c_class = get_equi_class(&regparse);
4983              if (c_class != 0) {
4984                // produce equivalence class
4985                reg_equi_class(c_class);
4986              } else if ((c_class = get_coll_element(&regparse)) != 0) {
4987                // produce a collating element
4988                regmbc(c_class);
4989              } else {
4990                // literal '[', allow [[-x] as a range
4991                startc = (uint8_t)(*regparse++);
4992                regc(startc);
4993              }
4994              break;
4995            case CLASS_ALNUM:
4996              for (cu = 1; cu < 128; cu++) {
4997                if (isalnum(cu)) {
4998                  regmbc(cu);
4999                }
5000              }
5001              break;
5002            case CLASS_ALPHA:
5003              for (cu = 1; cu < 128; cu++) {
5004                if (isalpha(cu)) {
5005                  regmbc(cu);
5006                }
5007              }
5008              break;
5009            case CLASS_BLANK:
5010              regc(' ');
5011              regc('\t');
5012              break;
5013            case CLASS_CNTRL:
5014              for (cu = 1; cu <= 127; cu++) {
5015                if (iscntrl(cu)) {
5016                  regmbc(cu);
5017                }
5018              }
5019              break;
5020            case CLASS_DIGIT:
5021              for (cu = 1; cu <= 127; cu++) {
5022                if (ascii_isdigit(cu)) {
5023                  regmbc(cu);
5024                }
5025              }
5026              break;
5027            case CLASS_GRAPH:
5028              for (cu = 1; cu <= 127; cu++) {
5029                if (isgraph(cu)) {
5030                  regmbc(cu);
5031                }
5032              }
5033              break;
5034            case CLASS_LOWER:
5035              for (cu = 1; cu <= 255; cu++) {
5036                if (mb_islower(cu) && cu != 170 && cu != 186) {
5037                  regmbc(cu);
5038                }
5039              }
5040              break;
5041            case CLASS_PRINT:
5042              for (cu = 1; cu <= 255; cu++) {
5043                if (vim_isprintc(cu)) {
5044                  regmbc(cu);
5045                }
5046              }
5047              break;
5048            case CLASS_PUNCT:
5049              for (cu = 1; cu < 128; cu++) {
5050                if (ispunct(cu)) {
5051                  regmbc(cu);
5052                }
5053              }
5054              break;
5055            case CLASS_SPACE:
5056              for (cu = 9; cu <= 13; cu++) {
5057                regc(cu);
5058              }
5059              regc(' ');
5060              break;
5061            case CLASS_UPPER:
5062              for (cu = 1; cu <= 255; cu++) {
5063                if (mb_isupper(cu)) {
5064                  regmbc(cu);
5065                }
5066              }
5067              break;
5068            case CLASS_XDIGIT:
5069              for (cu = 1; cu <= 255; cu++) {
5070                if (ascii_isxdigit(cu)) {
5071                  regmbc(cu);
5072                }
5073              }
5074              break;
5075            case CLASS_TAB:
5076              regc('\t');
5077              break;
5078            case CLASS_RETURN:
5079              regc('\r');
5080              break;
5081            case CLASS_BACKSPACE:
5082              regc('\b');
5083              break;
5084            case CLASS_ESCAPE:
5085              regc(ESC);
5086              break;
5087            case CLASS_IDENT:
5088              for (cu = 1; cu <= 255; cu++) {
5089                if (vim_isIDc(cu)) {
5090                  regmbc(cu);
5091                }
5092              }
5093              break;
5094            case CLASS_KEYWORD:
5095              for (cu = 1; cu <= 255; cu++) {
5096                if (reg_iswordc(cu)) {
5097                  regmbc(cu);
5098                }
5099              }
5100              break;
5101            case CLASS_FNAME:
5102              for (cu = 1; cu <= 255; cu++) {
5103                if (vim_isfilec(cu)) {
5104                  regmbc(cu);
5105                }
5106              }
5107              break;
5108            }
5109          } else {
5110            // produce a multibyte character, including any
5111            // following composing characters.
5112            startc = utf_ptr2char(regparse);
5113            int len = utfc_ptr2len(regparse);
5114            if (utf_char2len(startc) != len) {
5115              // composing chars
5116              startc = -1;
5117            }
5118            while (--len >= 0) {
5119              regc(*regparse++);
5120            }
5121          }
5122        }
5123        regc(NUL);
5124        prevchr_len = 1;                // last char was the ']'
5125        if (*regparse != ']') {
5126          EMSG_RET_NULL(_(e_toomsbra));                 // Cannot happen?
5127        }
5128        skipchr();                  // let's be friends with the lexer again
5129        *flagp |= HASWIDTH | SIMPLE;
5130        break;
5131      } else if (reg_strict) {
5132        EMSG2_RET_NULL(_(e_missingbracket), reg_magic > MAGIC_OFF);
5133      }
5134    }
5135    FALLTHROUGH;
5136
5137  default: {
5138    int len;
5139
5140    // A multi-byte character is handled as a separate atom if it's
5141    // before a multi and when it's a composing char.
5142    if (use_multibytecode(c)) {
5143do_multibyte:
5144      ret = regnode(MULTIBYTECODE);
5145      regmbc(c);
5146      *flagp |= HASWIDTH | SIMPLE;
5147      break;
5148    }
5149
5150    ret = regnode(EXACTLY);
5151
5152    // Append characters as long as:
5153    // - there is no following multi, we then need the character in
5154    //   front of it as a single character operand
5155    // - not running into a Magic character
5156    // - "one_exactly" is not set
5157    // But always emit at least one character.  Might be a Multi,
5158    // e.g., a "[" without matching "]".
5159    for (len = 0; c != NUL && (len == 0
5160                               || (re_multi_type(peekchr()) == NOT_MULTI
5161                                   && !one_exactly
5162                                   && !is_Magic(c))); len++) {
5163      c = no_Magic(c);
5164      {
5165        regmbc(c);
5166        {
5167          int l;
5168
5169          // Need to get composing character too.
5170          GraphemeState state = GRAPHEME_STATE_INIT;
5171          while (true) {
5172            l = utf_ptr2len(regparse);
5173            if (!utf_composinglike(regparse, regparse + l, &state)) {
5174              break;
5175            }
5176            regmbc(utf_ptr2char(regparse));
5177            skipchr();
5178          }
5179        }
5180      }
5181      c = getchr();
5182    }
5183    ungetchr();
5184
5185    regc(NUL);
5186    *flagp |= HASWIDTH;
5187    if (len == 1) {
5188      *flagp |= SIMPLE;
5189    }
5190  }
5191  break;
5192  }
5193
5194  return ret;
5195}
5196
5197// Parse something followed by possible [*+=].
5198//
5199// Note that the branching code sequences used for = and the general cases
5200// of * and + are somewhat optimized:  they use the same NOTHING node as
5201// both the endmarker for their branch list and the body of the last branch.
5202// It might seem that this node could be dispensed with entirely, but the
5203// endmarker role is not redundant.
5204static uint8_t *regpiece(int *flagp)
5205{
5206  uint8_t *ret;
5207  int op;
5208  uint8_t *next;
5209  int flags;
5210  int minval;
5211  int maxval;
5212
5213  ret = regatom(&flags);
5214  if (ret == NULL) {
5215    return NULL;
5216  }
5217
5218  op = peekchr();
5219  if (re_multi_type(op) == NOT_MULTI) {
5220    *flagp = flags;
5221    return ret;
5222  }
5223  // default flags
5224  *flagp = (WORST | SPSTART | (flags & (HASNL | HASLOOKBH)));
5225
5226  skipchr();
5227  switch (op) {
5228  case Magic('*'):
5229    if (flags & SIMPLE) {
5230      reginsert(STAR, ret);
5231    } else {
5232      // Emit x* as (x&|), where & means "self".
5233      reginsert(BRANCH, ret);           // Either x
5234      regoptail(ret, regnode(BACK));            // and loop
5235      regoptail(ret, ret);              // back
5236      regtail(ret, regnode(BRANCH));            // or
5237      regtail(ret, regnode(NOTHING));           // null.
5238    }
5239    break;
5240
5241  case Magic('+'):
5242    if (flags & SIMPLE) {
5243      reginsert(PLUS, ret);
5244    } else {
5245      // Emit x+ as x(&|), where & means "self".
5246      next = regnode(BRANCH);           // Either
5247      regtail(ret, next);
5248      regtail(regnode(BACK), ret);              // loop back
5249      regtail(next, regnode(BRANCH));           // or
5250      regtail(ret, regnode(NOTHING));           // null.
5251    }
5252    *flagp = (WORST | HASWIDTH | (flags & (HASNL | HASLOOKBH)));
5253    break;
5254
5255  case Magic('@'): {
5256    int lop = END;
5257    int64_t nr = getdecchrs();
5258
5259    switch (no_Magic(getchr())) {
5260    case '=':
5261      lop = MATCH; break;                                 // \@=
5262    case '!':
5263      lop = NOMATCH; break;                               // \@!
5264    case '>':
5265      lop = SUBPAT; break;                                // \@>
5266    case '<':
5267      switch (no_Magic(getchr())) {
5268      case '=':
5269        lop = BEHIND; break;                               // \@<=
5270      case '!':
5271        lop = NOBEHIND; break;                             // \@<!
5272      }
5273    }
5274    if (lop == END) {
5275      EMSG2_RET_NULL(_(e_invalid_character_after_str_at),
5276                     reg_magic == MAGIC_ALL);
5277    }
5278    // Look behind must match with behind_pos.
5279    if (lop == BEHIND || lop == NOBEHIND) {
5280      regtail(ret, regnode(BHPOS));
5281      *flagp |= HASLOOKBH;
5282    }
5283    regtail(ret, regnode(END));             // operand ends
5284    if (lop == BEHIND || lop == NOBEHIND) {
5285      if (nr < 0) {
5286        nr = 0;                 // no limit is same as zero limit
5287      }
5288      reginsert_nr(lop, (uint32_t)nr, ret);
5289    } else {
5290      reginsert(lop, ret);
5291    }
5292    break;
5293  }
5294
5295  case Magic('?'):
5296  case Magic('='):
5297    // Emit x= as (x|)
5298    reginsert(BRANCH, ret);                     // Either x
5299    regtail(ret, regnode(BRANCH));              // or
5300    next = regnode(NOTHING);                    // null.
5301    regtail(ret, next);
5302    regoptail(ret, next);
5303    break;
5304
5305  case Magic('{'):
5306    if (!read_limits(&minval, &maxval)) {
5307      return NULL;
5308    }
5309    if (flags & SIMPLE) {
5310      reginsert(BRACE_SIMPLE, ret);
5311      reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
5312    } else {
5313      if (num_complex_braces >= 10) {
5314        EMSG2_RET_NULL(_("E60: Too many complex %s{...}s"),
5315                       reg_magic == MAGIC_ALL);
5316      }
5317      reginsert(BRACE_COMPLEX + num_complex_braces, ret);
5318      regoptail(ret, regnode(BACK));
5319      regoptail(ret, ret);
5320      reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
5321      num_complex_braces++;
5322    }
5323    if (minval > 0 && maxval > 0) {
5324      *flagp = (HASWIDTH | (flags & (HASNL | HASLOOKBH)));
5325    }
5326    break;
5327  }
5328  if (re_multi_type(peekchr()) != NOT_MULTI) {
5329    // Can't have a multi follow a multi.
5330    if (peekchr() == Magic('*')) {
5331      EMSG2_RET_NULL(_("E61: Nested %s*"), reg_magic >= MAGIC_ON);
5332    }
5333    EMSG3_RET_NULL(_("E62: Nested %s%c"), reg_magic == MAGIC_ALL, no_Magic(peekchr()));
5334  }
5335
5336  return ret;
5337}
5338
5339// Parse one alternative of an | or & operator.
5340// Implements the concatenation operator.
5341static uint8_t *regconcat(int *flagp)
5342{
5343  uint8_t *first = NULL;
5344  uint8_t *chain = NULL;
5345  uint8_t *latest;
5346  int flags;
5347  int cont = true;
5348
5349  *flagp = WORST;               // Tentatively.
5350
5351  while (cont) {
5352    switch (peekchr()) {
5353    case NUL:
5354    case Magic('|'):
5355    case Magic('&'):
5356    case Magic(')'):
5357      cont = false;
5358      break;
5359    case Magic('Z'):
5360      regflags |= RF_ICOMBINE;
5361      skipchr_keepstart();
5362      break;
5363    case Magic('c'):
5364      regflags |= RF_ICASE;
5365      skipchr_keepstart();
5366      break;
5367    case Magic('C'):
5368      regflags |= RF_NOICASE;
5369      skipchr_keepstart();
5370      break;
5371    case Magic('v'):
5372      reg_magic = MAGIC_ALL;
5373      skipchr_keepstart();
5374      curchr = -1;
5375      break;
5376    case Magic('m'):
5377      reg_magic = MAGIC_ON;
5378      skipchr_keepstart();
5379      curchr = -1;
5380      break;
5381    case Magic('M'):
5382      reg_magic = MAGIC_OFF;
5383      skipchr_keepstart();
5384      curchr = -1;
5385      break;
5386    case Magic('V'):
5387      reg_magic = MAGIC_NONE;
5388      skipchr_keepstart();
5389      curchr = -1;
5390      break;
5391    default:
5392      latest = regpiece(&flags);
5393      if (latest == NULL || reg_toolong) {
5394        return NULL;
5395      }
5396      *flagp |= flags & (HASWIDTH | HASNL | HASLOOKBH);
5397      if (chain == NULL) {                      // First piece.
5398        *flagp |= flags & SPSTART;
5399      } else {
5400        regtail(chain, latest);
5401      }
5402      chain = latest;
5403      if (first == NULL) {
5404        first = latest;
5405      }
5406      break;
5407    }
5408  }
5409  if (first == NULL) {          // Loop ran zero times.
5410    first = regnode(NOTHING);
5411  }
5412  return first;
5413}
5414
5415// Parse one alternative of an | operator.
5416// Implements the & operator.
5417static uint8_t *regbranch(int *flagp)
5418{
5419  uint8_t *ret;
5420  uint8_t *chain = NULL;
5421  uint8_t *latest;
5422  int flags;
5423
5424  *flagp = WORST | HASNL;               // Tentatively.
5425
5426  ret = regnode(BRANCH);
5427  while (true) {
5428    latest = regconcat(&flags);
5429    if (latest == NULL) {
5430      return NULL;
5431    }
5432    // If one of the branches has width, the whole thing has.  If one of
5433    // the branches anchors at start-of-line, the whole thing does.
5434    // If one of the branches uses look-behind, the whole thing does.
5435    *flagp |= flags & (HASWIDTH | SPSTART | HASLOOKBH);
5436    // If one of the branches doesn't match a line-break, the whole thing
5437    // doesn't.
5438    *flagp &= ~HASNL | (flags & HASNL);
5439    if (chain != NULL) {
5440      regtail(chain, latest);
5441    }
5442    if (peekchr() != Magic('&')) {
5443      break;
5444    }
5445    skipchr();
5446    regtail(latest, regnode(END));     // operand ends
5447    if (reg_toolong) {
5448      break;
5449    }
5450    reginsert(MATCH, latest);
5451    chain = latest;
5452  }
5453
5454  return ret;
5455}
5456
5457/// Parse regular expression, i.e. main body or parenthesized thing.
5458///
5459/// Caller must absorb opening parenthesis.
5460///
5461/// Combining parenthesis handling with the base level of regular expression
5462/// is a trifle forced, but the need to tie the tails of the branches to what
5463/// follows makes it hard to avoid.
5464///
5465/// @param paren  REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN
5466static uint8_t *reg(int paren, int *flagp)
5467{
5468  uint8_t *ret;
5469  uint8_t *br;
5470  uint8_t *ender;
5471  int parno = 0;
5472  int flags;
5473
5474  *flagp = HASWIDTH;            // Tentatively.
5475
5476  if (paren == REG_ZPAREN) {
5477    // Make a ZOPEN node.
5478    if (regnzpar >= NSUBEXP) {
5479      EMSG_RET_NULL(_("E50: Too many \\z("));
5480    }
5481    parno = regnzpar;
5482    regnzpar++;
5483    ret = regnode(ZOPEN + parno);
5484  } else if (paren == REG_PAREN) {
5485    // Make a MOPEN node.
5486    if (regnpar >= NSUBEXP) {
5487      EMSG2_RET_NULL(_("E51: Too many %s("), reg_magic == MAGIC_ALL);
5488    }
5489    parno = regnpar;
5490    regnpar++;
5491    ret = regnode(MOPEN + parno);
5492  } else if (paren == REG_NPAREN) {
5493    // Make a NOPEN node.
5494    ret = regnode(NOPEN);
5495  } else {
5496    ret = NULL;
5497  }
5498
5499  if (bt_reg_parse_depth >= REG_MAX_PAREN_DEPTH) {
5500    EMSG_RET_NULL(_(e_command_too_complex));
5501  }
5502  bt_reg_parse_depth++;
5503
5504  // Pick up the branches, linking them together.
5505  br = regbranch(&flags);
5506  if (br == NULL) {
5507    ret = NULL;
5508    goto theend;
5509  }
5510  if (ret != NULL) {
5511    regtail(ret, br);           // [MZ]OPEN -> first.
5512  } else {
5513    ret = br;
5514  }
5515  // If one of the branches can be zero-width, the whole thing can.
5516  // If one of the branches has * at start or matches a line-break, the
5517  // whole thing can.
5518  if (!(flags & HASWIDTH)) {
5519    *flagp &= ~HASWIDTH;
5520  }
5521  *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
5522  while (peekchr() == Magic('|')) {
5523    skipchr();
5524    br = regbranch(&flags);
5525    if (br == NULL || reg_toolong) {
5526      ret = NULL;
5527      goto theend;
5528    }
5529    regtail(ret, br);           // BRANCH -> BRANCH.
5530    if (!(flags & HASWIDTH)) {
5531      *flagp &= ~HASWIDTH;
5532    }
5533    *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
5534  }
5535
5536  // Make a closing node, and hook it on the end.
5537  ender = regnode(paren == REG_ZPAREN ? ZCLOSE + parno
5538                                      : paren == REG_PAREN ? MCLOSE + parno
5539                                                           : paren == REG_NPAREN ? NCLOSE : END);
5540  regtail(ret, ender);
5541
5542  // Hook the tails of the branches to the closing node.
5543  for (br = ret; br != NULL; br = regnext(br)) {
5544    regoptail(br, ender);
5545  }
5546
5547  // Check for proper termination.
5548  if (paren != REG_NOPAREN && getchr() != Magic(')')) {
5549    if (paren == REG_ZPAREN) {
5550      emsg(_(e_unmatched_z));
5551      rc_did_emsg = true;
5552      ret = NULL;
5553      goto theend;
5554    } else if (paren == REG_NPAREN) {
5555      semsg(_(e_unmatched_str_percent_open), reg_magic == MAGIC_ALL ? "" : "\\");
5556      rc_did_emsg = true;
5557      ret = NULL;
5558      goto theend;
5559    } else {
5560      semsg(_(e_unmatched_str_open), reg_magic == MAGIC_ALL ? "" : "\\");
5561      rc_did_emsg = true;
5562      ret = NULL;
5563      goto theend;
5564    }
5565  } else if (paren == REG_NOPAREN && peekchr() != NUL) {
5566    if (curchr == Magic(')')) {
5567      semsg(_(e_unmatched_str_close), reg_magic == MAGIC_ALL ? "" : "\\");
5568      rc_did_emsg = true;
5569      ret = NULL;
5570      goto theend;
5571    } else {
5572      emsg(_(e_trailing));     // "Can't happen".
5573      rc_did_emsg = true;
5574      ret = NULL;
5575      goto theend;
5576    }
5577  }
5578  // Here we set the flag allowing back references to this set of
5579  // parentheses.
5580  if (paren == REG_PAREN) {
5581    had_endbrace[parno] = true;  // have seen the close paren
5582  }
5583
5584theend:
5585  bt_reg_parse_depth--;
5586  return ret;
5587}
5588
5589// bt_regcomp() - compile a regular expression into internal code for the
5590// traditional back track matcher.
5591// Returns the program in allocated space.  Returns NULL for an error.
5592//
5593// We can't allocate space until we know how big the compiled form will be,
5594// but we can't compile it (and thus know how big it is) until we've got a
5595// place to put the code.  So we cheat:  we compile it twice, once with code
5596// generation turned off and size counting turned on, and once "for real".
5597// This also means that we don't allocate space until we are sure that the
5598// thing really will compile successfully, and we never have to move the
5599// code and thus invalidate pointers into it.  (Note that it has to be in
5600// one piece because free() must be able to free it all.)
5601//
5602// Whether upper/lower case is to be ignored is decided when executing the
5603// program, it does not matter here.
5604//
5605// Beware that the optimization-preparation code in here knows about some
5606// of the structure of the compiled regexp.
5607// "re_flags": RE_MAGIC and/or RE_STRING.
5608static regprog_T *bt_regcomp(uint8_t *expr, int re_flags)
5609{
5610  uint8_t *scan;
5611  uint8_t *longest;
5612  int len;
5613  int flags;
5614
5615  if (expr == NULL) {
5616    IEMSG_RET_NULL(_(e_null));
5617  }
5618
5619  init_class_tab();
5620
5621  // First pass: determine size, legality.
5622  regcomp_start(expr, re_flags);
5623  regcode = JUST_CALC_SIZE;
5624  regc(REGMAGIC);
5625  if (reg(REG_NOPAREN, &flags) == NULL) {
5626    return NULL;
5627  }
5628
5629  // Allocate space.
5630  bt_regprog_T *r = xmalloc(offsetof(bt_regprog_T, program) + (size_t)regsize);
5631  r->re_in_use = false;
5632#ifdef REGEXP_DEBUG
5633  r->regsz = regsize;
5634#endif
5635
5636  // Second pass: emit code.
5637  regcomp_start(expr, re_flags);
5638  regcode = r->program;
5639  regc(REGMAGIC);
5640  if (reg(REG_NOPAREN, &flags) == NULL || reg_toolong) {
5641    xfree(r);
5642    if (reg_toolong) {
5643      EMSG_RET_NULL(_("E339: Pattern too long"));
5644    }
5645    return NULL;
5646  }
5647
5648  // Dig out information for optimizations.
5649  r->regstart = NUL;            // Worst-case defaults.
5650  r->reganch = 0;
5651  r->regmust = NULL;
5652  r->regmlen = 0;
5653  r->regflags = regflags;
5654  if (flags & HASNL) {
5655    r->regflags |= RF_HASNL;
5656  }
5657  if (flags & HASLOOKBH) {
5658    r->regflags |= RF_LOOKBH;
5659  }
5660  // Remember whether this pattern has any \z specials in it.
5661  r->reghasz = (uint8_t)re_has_z;
5662  scan = &r->program[1];  // First BRANCH.
5663  if (OP(regnext(scan)) == END) {   // Only one top-level choice.
5664    scan = OPERAND(scan);
5665
5666    // Starting-point info.
5667    if (OP(scan) == BOL || OP(scan) == RE_BOF) {
5668      r->reganch++;
5669      scan = regnext(scan);
5670    }
5671
5672    if (OP(scan) == EXACTLY) {
5673      r->regstart = utf_ptr2char((char *)OPERAND(scan));
5674    } else if (OP(scan) == BOW
5675               || OP(scan) == EOW
5676               || OP(scan) == NOTHING
5677               || OP(scan) == MOPEN + 0 || OP(scan) == NOPEN
5678               || OP(scan) == MCLOSE + 0 || OP(scan) == NCLOSE) {
5679      uint8_t *regnext_scan = regnext(scan);
5680      if (OP(regnext_scan) == EXACTLY) {
5681        r->regstart = utf_ptr2char((char *)OPERAND(regnext_scan));
5682      }
5683    }
5684
5685    // If there's something expensive in the r.e., find the longest
5686    // literal string that must appear and make it the regmust.  Resolve
5687    // ties in favor of later strings, since the regstart check works
5688    // with the beginning of the r.e. and avoiding duplication
5689    // strengthens checking.  Not a strong reason, but sufficient in the
5690    // absence of others.
5691
5692    // When the r.e. starts with BOW, it is faster to look for a regmust
5693    // first. Used a lot for "#" and "*" commands. (Added by mool).
5694    if ((flags & SPSTART || OP(scan) == BOW || OP(scan) == EOW)
5695        && !(flags & HASNL)) {
5696      longest = NULL;
5697      len = 0;
5698      for (; scan != NULL; scan = regnext(scan)) {
5699        if (OP(scan) == EXACTLY) {
5700          size_t scanlen = strlen((char *)OPERAND(scan));
5701          if (scanlen >= (size_t)len) {
5702            longest = OPERAND(scan);
5703            len = (int)scanlen;
5704          }
5705        }
5706      }
5707      r->regmust = longest;
5708      r->regmlen = len;
5709    }
5710  }
5711#ifdef BT_REGEXP_DUMP
5712  regdump(expr, r);
5713#endif
5714  r->engine = &bt_regengine;
5715  return (regprog_T *)r;
5716}
5717
5718// Check if during the previous call to vim_regcomp the EOL item "$" has been
5719// found.  This is messy, but it works fine.
5720int vim_regcomp_had_eol(void)
5721{
5722  return had_eol;
5723}
5724
5725// Get a number after a backslash that is inside [].
5726// When nothing is recognized return a backslash.
5727static int coll_get_char(void)
5728{
5729  int64_t nr = -1;
5730
5731  switch (*regparse++) {
5732  case 'd':
5733    nr = getdecchrs(); break;
5734  case 'o':
5735    nr = getoctchrs(); break;
5736  case 'x':
5737    nr = gethexchrs(2); break;
5738  case 'u':
5739    nr = gethexchrs(4); break;
5740  case 'U':
5741    nr = gethexchrs(8); break;
5742  }
5743  if (nr < 0) {
5744    // If getting the number fails be backwards compatible: the character
5745    // is a backslash.
5746    regparse--;
5747    nr = '\\';
5748  }
5749  if (nr > INT_MAX) {
5750    nr = INT_MAX;
5751  }
5752  return (int)nr;
5753}
5754
5755// Free a compiled regexp program, returned by bt_regcomp().
5756static void bt_regfree(regprog_T *prog)
5757{
5758  xfree(prog);
5759}
5760
5761#define ADVANCE_REGINPUT() MB_PTR_ADV(rex.input)
5762
5763// The arguments from BRACE_LIMITS are stored here.  They are actually local
5764// to regmatch(), but they are here to reduce the amount of stack space used
5765// (it can be called recursively many times).
5766static int64_t bl_minval;
5767static int64_t bl_maxval;
5768
5769// Save the input line and position in a regsave_T.
5770static void reg_save(regsave_T *save, garray_T *gap)
5771  FUNC_ATTR_NONNULL_ALL
5772{
5773  if (REG_MULTI) {
5774    save->rs_u.pos.col = (colnr_T)(rex.input - rex.line);
5775    save->rs_u.pos.lnum = rex.lnum;
5776  } else {
5777    save->rs_u.ptr = rex.input;
5778  }
5779  save->rs_len = gap->ga_len;
5780}
5781
5782// Restore the input line and position from a regsave_T.
5783static void reg_restore(regsave_T *save, garray_T *gap)
5784  FUNC_ATTR_NONNULL_ALL
5785{
5786  if (REG_MULTI) {
5787    if (rex.lnum != save->rs_u.pos.lnum) {
5788      // only call reg_getline() when the line number changed to save
5789      // a bit of time
5790      rex.lnum = save->rs_u.pos.lnum;
5791      rex.line = (uint8_t *)reg_getline(rex.lnum);
5792    }
5793    rex.input = rex.line + save->rs_u.pos.col;
5794  } else {
5795    rex.input = save->rs_u.ptr;
5796  }
5797  gap->ga_len = save->rs_len;
5798}
5799
5800// Return true if current position is equal to saved position.
5801static bool reg_save_equal(const regsave_T *save)
5802  FUNC_ATTR_NONNULL_ALL
5803{
5804  if (REG_MULTI) {
5805    return rex.lnum == save->rs_u.pos.lnum
5806           && rex.input == rex.line + save->rs_u.pos.col;
5807  }
5808  return rex.input == save->rs_u.ptr;
5809}
5810
5811// Save the sub-expressions before attempting a match.
5812#define save_se(savep, posp, pp) \
5813  REG_MULTI ? save_se_multi((savep), (posp)) : save_se_one((savep), (pp))
5814
5815// After a failed match restore the sub-expressions.
5816#define restore_se(savep, posp, pp) { \
5817  if (REG_MULTI) \
5818  *(posp) = (savep)->se_u.pos; \
5819  else \
5820  *(pp) = (savep)->se_u.ptr; }
5821
5822// Tentatively set the sub-expression start to the current position (after
5823// calling regmatch() they will have changed).  Need to save the existing
5824// values for when there is no match.
5825// Use se_save() to use pointer (save_se_multi()) or position (save_se_one()),
5826// depending on REG_MULTI.
5827static void save_se_multi(save_se_T *savep, lpos_T *posp)
5828{
5829  savep->se_u.pos = *posp;
5830  posp->lnum = rex.lnum;
5831  posp->col = (colnr_T)(rex.input - rex.line);
5832}
5833
5834static void save_se_one(save_se_T *savep, uint8_t **pp)
5835{
5836  savep->se_u.ptr = *pp;
5837  *pp = rex.input;
5838}
5839
5840/// regrepeat - repeatedly match something simple, return how many.
5841/// Advances rex.input (and rex.lnum) to just after the matched chars.
5842///
5843/// @param maxcount  maximum number of matches allowed
5844static int regrepeat(uint8_t *p, int64_t maxcount)
5845{
5846  int64_t count = 0;
5847  uint8_t *opnd;
5848  int mask;
5849  int testval = 0;
5850
5851  uint8_t *scan = rex.input;  // Make local copy of rex.input for speed.
5852  opnd = OPERAND(p);
5853  switch (OP(p)) {
5854  case ANY:
5855  case ANY + ADD_NL:
5856    while (count < maxcount) {
5857      // Matching anything means we continue until end-of-line (or
5858      // end-of-file for ANY + ADD_NL), only limited by maxcount.
5859      while (*scan != NUL && count < maxcount) {
5860        count++;
5861        MB_PTR_ADV(scan);
5862      }
5863      if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
5864          || rex.reg_line_lbr || count == maxcount) {
5865        break;
5866      }
5867      count++;  // count the line-break
5868      reg_nextline();
5869      scan = rex.input;
5870      if (got_int) {
5871        break;
5872      }
5873    }
5874    break;
5875
5876  case IDENT:
5877  case IDENT + ADD_NL:
5878    testval = 1;
5879    FALLTHROUGH;
5880  case SIDENT:
5881  case SIDENT + ADD_NL:
5882    while (count < maxcount) {
5883      if (vim_isIDc(utf_ptr2char((char *)scan)) && (testval || !ascii_isdigit(*scan))) {
5884        MB_PTR_ADV(scan);
5885      } else if (*scan == NUL) {
5886        if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
5887            || rex.reg_line_lbr) {
5888          break;
5889        }
5890        reg_nextline();
5891        scan = rex.input;
5892        if (got_int) {
5893          break;
5894        }
5895      } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
5896        scan++;
5897      } else {
5898        break;
5899      }
5900      count++;
5901    }
5902    break;
5903
5904  case KWORD:
5905  case KWORD + ADD_NL:
5906    testval = 1;
5907    FALLTHROUGH;
5908  case SKWORD:
5909  case SKWORD + ADD_NL:
5910    while (count < maxcount) {
5911      if (vim_iswordp_buf((char *)scan, rex.reg_buf)
5912          && (testval || !ascii_isdigit(*scan))) {
5913        MB_PTR_ADV(scan);
5914      } else if (*scan == NUL) {
5915        if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
5916            || rex.reg_line_lbr) {
5917          break;
5918        }
5919        reg_nextline();
5920        scan = rex.input;
5921        if (got_int) {
5922          break;
5923        }
5924      } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
5925        scan++;
5926      } else {
5927        break;
5928      }
5929      count++;
5930    }
5931    break;
5932
5933  case FNAME:
5934  case FNAME + ADD_NL:
5935    testval = 1;
5936    FALLTHROUGH;
5937  case SFNAME:
5938  case SFNAME + ADD_NL:
5939    while (count < maxcount) {
5940      if (vim_isfilec(utf_ptr2char((char *)scan)) && (testval || !ascii_isdigit(*scan))) {
5941        MB_PTR_ADV(scan);
5942      } else if (*scan == NUL) {
5943        if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
5944            || rex.reg_line_lbr) {
5945          break;
5946        }
5947        reg_nextline();
5948        scan = rex.input;
5949        if (got_int) {
5950          break;
5951        }
5952      } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
5953        scan++;
5954      } else {
5955        break;
5956      }
5957      count++;
5958    }
5959    break;
5960
5961  case PRINT:
5962  case PRINT + ADD_NL:
5963    testval = 1;
5964    FALLTHROUGH;
5965  case SPRINT:
5966  case SPRINT + ADD_NL:
5967    while (count < maxcount) {
5968      if (*scan == NUL) {
5969        if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
5970            || rex.reg_line_lbr) {
5971          break;
5972        }
5973        reg_nextline();
5974        scan = rex.input;
5975        if (got_int) {
5976          break;
5977        }
5978      } else if (vim_isprintc(utf_ptr2char((char *)scan)) == 1
5979                 && (testval || !ascii_isdigit(*scan))) {
5980        MB_PTR_ADV(scan);
5981      } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
5982        scan++;
5983      } else {
5984        break;
5985      }
5986      count++;
5987    }
5988    break;
5989
5990  case WHITE:
5991  case WHITE + ADD_NL:
5992    testval = mask = RI_WHITE;
5993do_class:
5994    while (count < maxcount) {
5995      int l;
5996      if (*scan == NUL) {
5997        if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
5998            || rex.reg_line_lbr) {
5999          break;
6000        }
6001        reg_nextline();
6002        scan = rex.input;
6003        if (got_int) {
6004          break;
6005        }
6006      } else if ((l = utfc_ptr2len((char *)scan)) > 1) {
6007        if (testval != 0) {
6008          break;
6009        }
6010        scan += l;
6011      } else if ((class_tab[*scan] & mask) == testval) {
6012        scan++;
6013      } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
6014        scan++;
6015      } else {
6016        break;
6017      }
6018      count++;
6019    }
6020    break;
6021
6022  case NWHITE:
6023  case NWHITE + ADD_NL:
6024    mask = RI_WHITE;
6025    goto do_class;
6026  case DIGIT:
6027  case DIGIT + ADD_NL:
6028    testval = mask = RI_DIGIT;
6029    goto do_class;
6030  case NDIGIT:
6031  case NDIGIT + ADD_NL:
6032    mask = RI_DIGIT;
6033    goto do_class;
6034  case HEX:
6035  case HEX + ADD_NL:
6036    testval = mask = RI_HEX;
6037    goto do_class;
6038  case NHEX:
6039  case NHEX + ADD_NL:
6040    mask = RI_HEX;
6041    goto do_class;
6042  case OCTAL:
6043  case OCTAL + ADD_NL:
6044    testval = mask = RI_OCTAL;
6045    goto do_class;
6046  case NOCTAL:
6047  case NOCTAL + ADD_NL:
6048    mask = RI_OCTAL;
6049    goto do_class;
6050  case WORD:
6051  case WORD + ADD_NL:
6052    testval = mask = RI_WORD;
6053    goto do_class;
6054  case NWORD:
6055  case NWORD + ADD_NL:
6056    mask = RI_WORD;
6057    goto do_class;
6058  case HEAD:
6059  case HEAD + ADD_NL:
6060    testval = mask = RI_HEAD;
6061    goto do_class;
6062  case NHEAD:
6063  case NHEAD + ADD_NL:
6064    mask = RI_HEAD;
6065    goto do_class;
6066  case ALPHA:
6067  case ALPHA + ADD_NL:
6068    testval = mask = RI_ALPHA;
6069    goto do_class;
6070  case NALPHA:
6071  case NALPHA + ADD_NL:
6072    mask = RI_ALPHA;
6073    goto do_class;
6074  case LOWER:
6075  case LOWER + ADD_NL:
6076    testval = mask = RI_LOWER;
6077    goto do_class;
6078  case NLOWER:
6079  case NLOWER + ADD_NL:
6080    mask = RI_LOWER;
6081    goto do_class;
6082  case UPPER:
6083  case UPPER + ADD_NL:
6084    testval = mask = RI_UPPER;
6085    goto do_class;
6086  case NUPPER:
6087  case NUPPER + ADD_NL:
6088    mask = RI_UPPER;
6089    goto do_class;
6090
6091  case EXACTLY: {
6092    int cu, cl;
6093
6094    // This doesn't do a multi-byte character, because a MULTIBYTECODE
6095    // would have been used for it.  It does handle single-byte
6096    // characters, such as latin1.
6097    if (rex.reg_ic) {
6098      cu = mb_toupper(*opnd);
6099      cl = mb_tolower(*opnd);
6100      while (count < maxcount && (*scan == cu || *scan == cl)) {
6101        count++;
6102        scan++;
6103      }
6104    } else {
6105      cu = *opnd;
6106      while (count < maxcount && *scan == cu) {
6107        count++;
6108        scan++;
6109      }
6110    }
6111    break;
6112  }
6113
6114  case MULTIBYTECODE: {
6115    int i, len, cf = 0;
6116
6117    // Safety check (just in case 'encoding' was changed since
6118    // compiling the program).
6119    if ((len = utfc_ptr2len((char *)opnd)) > 1) {
6120      if (rex.reg_ic) {
6121        cf = utf_fold(utf_ptr2char((char *)opnd));
6122      }
6123      while (count < maxcount && utfc_ptr2len((char *)scan) >= len) {
6124        for (i = 0; i < len; i++) {
6125          if (opnd[i] != scan[i]) {
6126            break;
6127          }
6128        }
6129        if (i < len && (!rex.reg_ic
6130                        || utf_fold(utf_ptr2char((char *)scan)) != cf)) {
6131          break;
6132        }
6133        scan += len;
6134        count++;
6135      }
6136    }
6137  }
6138  break;
6139
6140  case ANYOF:
6141  case ANYOF + ADD_NL:
6142    testval = 1;
6143    FALLTHROUGH;
6144
6145  case ANYBUT:
6146  case ANYBUT + ADD_NL:
6147    while (count < maxcount) {
6148      int len;
6149      if (*scan == NUL) {
6150        if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
6151            || rex.reg_line_lbr) {
6152          break;
6153        }
6154        reg_nextline();
6155        scan = rex.input;
6156        if (got_int) {
6157          break;
6158        }
6159      } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
6160        scan++;
6161      } else if ((len = utfc_ptr2len((char *)scan)) > 1) {
6162        if ((cstrchr((char *)opnd, utf_ptr2char((char *)scan)) == NULL) == testval) {
6163          break;
6164        }
6165        scan += len;
6166      } else {
6167        if ((cstrchr((char *)opnd, *scan) == NULL) == testval) {
6168          break;
6169        }
6170        scan++;
6171      }
6172      count++;
6173    }
6174    break;
6175
6176  case NEWL:
6177    while (count < maxcount
6178           && ((*scan == NUL && rex.lnum <= rex.reg_maxline && !rex.reg_line_lbr
6179                && REG_MULTI) || (*scan == '\n' && rex.reg_line_lbr))) {
6180      count++;
6181      if (rex.reg_line_lbr) {
6182        ADVANCE_REGINPUT();
6183      } else {
6184        reg_nextline();
6185      }
6186      scan = rex.input;
6187      if (got_int) {
6188        break;
6189      }
6190    }
6191    break;
6192
6193  default:  // Oh dear.  Called inappropriately.
6194    iemsg(_(e_re_corr));
6195#ifdef REGEXP_DEBUG
6196    printf("Called regrepeat with op code %d\n", OP(p));
6197#endif
6198    break;
6199  }
6200
6201  rex.input = scan;
6202
6203  return (int)count;
6204}
6205
6206// Push an item onto the regstack.
6207// Returns pointer to new item.  Returns NULL when out of memory.
6208static regitem_T *regstack_push(regstate_T state, uint8_t *scan)
6209{
6210  regitem_T *rp;
6211
6212  if ((int64_t)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
6213    emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
6214    return NULL;
6215  }
6216  ga_grow(&regstack, sizeof(regitem_T));
6217
6218  rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len);
6219  rp->rs_state = state;
6220  rp->rs_scan = scan;
6221
6222  regstack.ga_len += (int)sizeof(regitem_T);
6223  return rp;
6224}
6225
6226// Pop an item from the regstack.
6227static void regstack_pop(uint8_t **scan)
6228{
6229  regitem_T *rp;
6230
6231  rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
6232  *scan = rp->rs_scan;
6233
6234  regstack.ga_len -= (int)sizeof(regitem_T);
6235}
6236
6237// Save the current subexpr to "bp", so that they can be restored
6238// later by restore_subexpr().
6239static void save_subexpr(regbehind_T *bp)
6240  FUNC_ATTR_NONNULL_ALL
6241{
6242  // When "rex.need_clear_subexpr" is set we don't need to save the values, only
6243  // remember that this flag needs to be set again when restoring.
6244  bp->save_need_clear_subexpr = rex.need_clear_subexpr;
6245  if (rex.need_clear_subexpr) {
6246    return;
6247  }
6248
6249  for (int i = 0; i < NSUBEXP; i++) {
6250    if (REG_MULTI) {
6251      bp->save_start[i].se_u.pos = rex.reg_startpos[i];
6252      bp->save_end[i].se_u.pos = rex.reg_endpos[i];
6253    } else {
6254      bp->save_start[i].se_u.ptr = rex.reg_startp[i];
6255      bp->save_end[i].se_u.ptr = rex.reg_endp[i];
6256    }
6257  }
6258}
6259
6260// Restore the subexpr from "bp".
6261static void restore_subexpr(regbehind_T *bp)
6262  FUNC_ATTR_NONNULL_ALL
6263{
6264  // Only need to restore saved values when they are not to be cleared.
6265  rex.need_clear_subexpr = bp->save_need_clear_subexpr;
6266  if (rex.need_clear_subexpr) {
6267    return;
6268  }
6269
6270  for (int i = 0; i < NSUBEXP; i++) {
6271    if (REG_MULTI) {
6272      rex.reg_startpos[i] = bp->save_start[i].se_u.pos;
6273      rex.reg_endpos[i] = bp->save_end[i].se_u.pos;
6274    } else {
6275      rex.reg_startp[i] = bp->save_start[i].se_u.ptr;
6276      rex.reg_endp[i] = bp->save_end[i].se_u.ptr;
6277    }
6278  }
6279}
6280/// Main matching routine
6281///
6282/// Conceptually the strategy is simple: Check to see whether the current node
6283/// matches, push an item onto the regstack and loop to see whether the rest
6284/// matches, and then act accordingly.  In practice we make some effort to
6285/// avoid using the regstack, in particular by going through "ordinary" nodes
6286/// (that don't need to know whether the rest of the match failed) by a nested
6287/// loop.
6288///
6289/// @param scan       Current node.
6290/// @param tm         timeout limit or NULL
6291/// @param timed_out  flag set on timeout or NULL
6292///
6293/// @return - true when there is a match.  Leaves rex.input and rex.lnum
6294///         just after the last matched character.
6295///         - false when there is no match.  Leaves rex.input and rex.lnum in an
6296///         undefined state!
6297static bool regmatch(uint8_t *scan, const proftime_T *tm, int *timed_out)
6298{
6299  uint8_t *next;          // Next node.
6300  int op;
6301  int c;
6302  regitem_T *rp;
6303  int no;
6304  int status;                   // one of the RA_ values:
6305  int tm_count = 0;
6306
6307  // Make "regstack" and "backpos" empty.  They are allocated and freed in
6308  // bt_regexec_both() to reduce malloc()/free() calls.
6309  regstack.ga_len = 0;
6310  backpos.ga_len = 0;
6311
6312  // Repeat until "regstack" is empty.
6313  while (true) {
6314    // Some patterns may take a long time to match, e.g., "\([a-z]\+\)\+Q".
6315    // Allow interrupting them with CTRL-C.
6316    reg_breakcheck();
6317
6318#ifdef REGEXP_DEBUG
6319    if (scan != NULL && regnarrate) {
6320      fprintf(stderr, "%s", (char *)regprop(scan));
6321      fprintf(stderr, "%s", "(\n");
6322    }
6323#endif
6324
6325    // Repeat for items that can be matched sequentially, without using the
6326    // regstack.
6327    while (true) {
6328      if (got_int || scan == NULL) {
6329        status = RA_FAIL;
6330        break;
6331      }
6332      // Check for timeout once in a 100 times to avoid overhead.
6333      if (tm != NULL && ++tm_count == 100) {
6334        tm_count = 0;
6335        if (profile_passed_limit(*tm)) {
6336          if (timed_out != NULL) {
6337            *timed_out = true;
6338          }
6339          status = RA_FAIL;
6340          break;
6341        }
6342      }
6343      status = RA_CONT;
6344
6345#ifdef REGEXP_DEBUG
6346      if (regnarrate) {
6347        fprintf(stderr, "%s", (char *)regprop(scan));
6348        fprintf(stderr, "%s", "...\n");
6349        if (re_extmatch_in != NULL) {
6350          int i;
6351
6352          fprintf(stderr, _("External submatches:\n"));
6353          for (i = 0; i < NSUBEXP; i++) {
6354            fprintf(stderr, "%s", "    \"");
6355            if (re_extmatch_in->matches[i] != NULL) {
6356              fprintf(stderr, "%s", (char *)re_extmatch_in->matches[i]);
6357            }
6358            fprintf(stderr, "%s", "\"\n");
6359          }
6360        }
6361      }
6362#endif
6363      next = regnext(scan);
6364
6365      op = OP(scan);
6366      // Check for character class with NL added.
6367      if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI
6368          && *rex.input == NUL && rex.lnum <= rex.reg_maxline) {
6369        reg_nextline();
6370      } else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n') {
6371        ADVANCE_REGINPUT();
6372      } else {
6373        if (WITH_NL(op)) {
6374          op -= ADD_NL;
6375        }
6376        c = utf_ptr2char((char *)rex.input);
6377        switch (op) {
6378        case BOL:
6379          if (rex.input != rex.line) {
6380            status = RA_NOMATCH;
6381          }
6382          break;
6383
6384        case EOL:
6385          if (c != NUL) {
6386            status = RA_NOMATCH;
6387          }
6388          break;
6389
6390        case RE_BOF:
6391          // We're not at the beginning of the file when below the first
6392          // line where we started, not at the start of the line or we
6393          // didn't start at the first line of the buffer.
6394          if (rex.lnum != 0 || rex.input != rex.line
6395              || (REG_MULTI && rex.reg_firstlnum > 1)) {
6396            status = RA_NOMATCH;
6397          }
6398          break;
6399
6400        case RE_EOF:
6401          if (rex.lnum != rex.reg_maxline || c != NUL) {
6402            status = RA_NOMATCH;
6403          }
6404          break;
6405
6406        case CURSOR:
6407          // Check if the buffer is in a window and compare the
6408          // rex.reg_win->w_cursor position to the match position.
6409          if (rex.reg_win == NULL
6410              || (rex.lnum + rex.reg_firstlnum != rex.reg_win->w_cursor.lnum)
6411              || ((colnr_T)(rex.input - rex.line) !=
6412                  rex.reg_win->w_cursor.col)) {
6413            status = RA_NOMATCH;
6414          }
6415          break;
6416
6417        case RE_MARK:
6418          // Compare the mark position to the match position.
6419        {
6420          int mark = OPERAND(scan)[0];
6421          int cmp = OPERAND(scan)[1];
6422          pos_T *pos;
6423          size_t col = REG_MULTI ? (size_t)(rex.input - rex.line) : 0;
6424          fmark_T *fm = mark_get(rex.reg_buf, curwin, NULL, kMarkBufLocal, mark);
6425
6426          // Line may have been freed, get it again.
6427          if (REG_MULTI) {
6428            rex.line = (uint8_t *)reg_getline(rex.lnum);
6429            rex.input = rex.line + col;
6430          }
6431
6432          if (fm == NULL                    // mark doesn't exist
6433              || fm->mark.lnum <= 0) {           // mark isn't set in reg_buf
6434            status = RA_NOMATCH;
6435          } else {
6436            pos = &fm->mark;
6437            const colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum
6438                                    && pos->col == MAXCOL
6439                                    ? reg_getline_len(pos->lnum - rex.reg_firstlnum)
6440                                    : pos->col;
6441
6442            if (pos->lnum == rex.lnum + rex.reg_firstlnum
6443                ? (pos_col == (colnr_T)(rex.input - rex.line)
6444                   ? (cmp == '<' || cmp == '>')
6445                   : (pos_col < (colnr_T)(rex.input - rex.line)
6446                      ? cmp != '>'
6447                      : cmp != '<'))
6448                : (pos->lnum < rex.lnum + rex.reg_firstlnum
6449                   ? cmp != '>'
6450                   : cmp != '<')) {
6451              status = RA_NOMATCH;
6452            }
6453          }
6454        }
6455        break;
6456
6457        case RE_VISUAL:
6458          if (!reg_match_visual()) {
6459            status = RA_NOMATCH;
6460          }
6461          break;
6462
6463        case RE_LNUM:
6464          assert(rex.lnum + rex.reg_firstlnum >= 0
6465                 && (uintmax_t)(rex.lnum + rex.reg_firstlnum) <= UINT32_MAX);
6466          if (!REG_MULTI
6467              || !re_num_cmp((uint32_t)(rex.lnum + rex.reg_firstlnum), scan)) {
6468            status = RA_NOMATCH;
6469          }
6470          break;
6471
6472        case RE_COL:
6473          assert(rex.input - rex.line + 1 >= 0
6474                 && (uintmax_t)(rex.input - rex.line + 1) <= UINT32_MAX);
6475          if (!re_num_cmp((uint32_t)(rex.input - rex.line + 1), scan)) {
6476            status = RA_NOMATCH;
6477          }
6478          break;
6479
6480        case RE_VCOL: {
6481          win_T *wp = rex.reg_win == NULL ? curwin : rex.reg_win;
6482          linenr_T lnum = REG_MULTI ? rex.reg_firstlnum + rex.lnum : 1;
6483          if (REG_MULTI && (lnum <= 0 || lnum > wp->w_buffer->b_ml.ml_line_count)) {
6484            lnum = 1;
6485          }
6486          int vcol = win_linetabsize(wp, lnum, (char *)rex.line,
6487                                     (colnr_T)(rex.input - rex.line));
6488          if (!re_num_cmp((uint32_t)vcol + 1, scan)) {
6489            status = RA_NOMATCH;
6490          }
6491          break;
6492        }
6493        break;
6494
6495        case BOW:  // \<word; rex.input points to w
6496          if (c == NUL) {  // Can't match at end of line
6497            status = RA_NOMATCH;
6498          } else {
6499            // Get class of current and previous char (if it exists).
6500            const int this_class =
6501              mb_get_class_tab((char *)rex.input, rex.reg_buf->b_chartab);
6502            if (this_class <= 1) {
6503              status = RA_NOMATCH;  // Not on a word at all.
6504            } else if (reg_prev_class() == this_class) {
6505              status = RA_NOMATCH;  // Previous char is in same word.
6506            }
6507          }
6508          break;
6509
6510        case EOW:  // word\>; rex.input points after d
6511          if (rex.input == rex.line) {  // Can't match at start of line
6512            status = RA_NOMATCH;
6513          } else {
6514            int this_class, prev_class;
6515
6516            // Get class of current and previous char (if it exists).
6517            this_class = mb_get_class_tab((char *)rex.input, rex.reg_buf->b_chartab);
6518            prev_class = reg_prev_class();
6519            if (this_class == prev_class
6520                || prev_class == 0 || prev_class == 1) {
6521              status = RA_NOMATCH;
6522            }
6523          }
6524          break;  // Matched with EOW
6525
6526        case ANY:
6527          // ANY does not match new lines.
6528          if (c == NUL) {
6529            status = RA_NOMATCH;
6530          } else {
6531            ADVANCE_REGINPUT();
6532          }
6533          break;
6534
6535        case IDENT:
6536          if (!vim_isIDc(c)) {
6537            status = RA_NOMATCH;
6538          } else {
6539            ADVANCE_REGINPUT();
6540          }
6541          break;
6542
6543        case SIDENT:
6544          if (ascii_isdigit(*rex.input) || !vim_isIDc(c)) {
6545            status = RA_NOMATCH;
6546          } else {
6547            ADVANCE_REGINPUT();
6548          }
6549          break;
6550
6551        case KWORD:
6552          if (!vim_iswordp_buf((char *)rex.input, rex.reg_buf)) {
6553            status = RA_NOMATCH;
6554          } else {
6555            ADVANCE_REGINPUT();
6556          }
6557          break;
6558
6559        case SKWORD:
6560          if (ascii_isdigit(*rex.input)
6561              || !vim_iswordp_buf((char *)rex.input, rex.reg_buf)) {
6562            status = RA_NOMATCH;
6563          } else {
6564            ADVANCE_REGINPUT();
6565          }
6566          break;
6567
6568        case FNAME:
6569          if (!vim_isfilec(c)) {
6570            status = RA_NOMATCH;
6571          } else {
6572            ADVANCE_REGINPUT();
6573          }
6574          break;
6575
6576        case SFNAME:
6577          if (ascii_isdigit(*rex.input) || !vim_isfilec(c)) {
6578            status = RA_NOMATCH;
6579          } else {
6580            ADVANCE_REGINPUT();
6581          }
6582          break;
6583
6584        case PRINT:
6585          if (!vim_isprintc(utf_ptr2char((char *)rex.input))) {
6586            status = RA_NOMATCH;
6587          } else {
6588            ADVANCE_REGINPUT();
6589          }
6590          break;
6591
6592        case SPRINT:
6593          if (ascii_isdigit(*rex.input) || !vim_isprintc(utf_ptr2char((char *)rex.input))) {
6594            status = RA_NOMATCH;
6595          } else {
6596            ADVANCE_REGINPUT();
6597          }
6598          break;
6599
6600        case WHITE:
6601          if (!ascii_iswhite(c)) {
6602            status = RA_NOMATCH;
6603          } else {
6604            ADVANCE_REGINPUT();
6605          }
6606          break;
6607
6608        case NWHITE:
6609          if (c == NUL || ascii_iswhite(c)) {
6610            status = RA_NOMATCH;
6611          } else {
6612            ADVANCE_REGINPUT();
6613          }
6614          break;
6615
6616        case DIGIT:
6617          if (!ri_digit(c)) {
6618            status = RA_NOMATCH;
6619          } else {
6620            ADVANCE_REGINPUT();
6621          }
6622          break;
6623
6624        case NDIGIT:
6625          if (c == NUL || ri_digit(c)) {
6626            status = RA_NOMATCH;
6627          } else {
6628            ADVANCE_REGINPUT();
6629          }
6630          break;
6631
6632        case HEX:
6633          if (!ri_hex(c)) {
6634            status = RA_NOMATCH;
6635          } else {
6636            ADVANCE_REGINPUT();
6637          }
6638          break;
6639
6640        case NHEX:
6641          if (c == NUL || ri_hex(c)) {
6642            status = RA_NOMATCH;
6643          } else {
6644            ADVANCE_REGINPUT();
6645          }
6646          break;
6647
6648        case OCTAL:
6649          if (!ri_octal(c)) {
6650            status = RA_NOMATCH;
6651          } else {
6652            ADVANCE_REGINPUT();
6653          }
6654          break;
6655
6656        case NOCTAL:
6657          if (c == NUL || ri_octal(c)) {
6658            status = RA_NOMATCH;
6659          } else {
6660            ADVANCE_REGINPUT();
6661          }
6662          break;
6663
6664        case WORD:
6665          if (!ri_word(c)) {
6666            status = RA_NOMATCH;
6667          } else {
6668            ADVANCE_REGINPUT();
6669          }
6670          break;
6671
6672        case NWORD:
6673          if (c == NUL || ri_word(c)) {
6674            status = RA_NOMATCH;
6675          } else {
6676            ADVANCE_REGINPUT();
6677          }
6678          break;
6679
6680        case HEAD:
6681          if (!ri_head(c)) {
6682            status = RA_NOMATCH;
6683          } else {
6684            ADVANCE_REGINPUT();
6685          }
6686          break;
6687
6688        case NHEAD:
6689          if (c == NUL || ri_head(c)) {
6690            status = RA_NOMATCH;
6691          } else {
6692            ADVANCE_REGINPUT();
6693          }
6694          break;
6695
6696        case ALPHA:
6697          if (!ri_alpha(c)) {
6698            status = RA_NOMATCH;
6699          } else {
6700            ADVANCE_REGINPUT();
6701          }
6702          break;
6703
6704        case NALPHA:
6705          if (c == NUL || ri_alpha(c)) {
6706            status = RA_NOMATCH;
6707          } else {
6708            ADVANCE_REGINPUT();
6709          }
6710          break;
6711
6712        case LOWER:
6713          if (!ri_lower(c)) {
6714            status = RA_NOMATCH;
6715          } else {
6716            ADVANCE_REGINPUT();
6717          }
6718          break;
6719
6720        case NLOWER:
6721          if (c == NUL || ri_lower(c)) {
6722            status = RA_NOMATCH;
6723          } else {
6724            ADVANCE_REGINPUT();
6725          }
6726          break;
6727
6728        case UPPER:
6729          if (!ri_upper(c)) {
6730            status = RA_NOMATCH;
6731          } else {
6732            ADVANCE_REGINPUT();
6733          }
6734          break;
6735
6736        case NUPPER:
6737          if (c == NUL || ri_upper(c)) {
6738            status = RA_NOMATCH;
6739          } else {
6740            ADVANCE_REGINPUT();
6741          }
6742          break;
6743
6744        case EXACTLY: {
6745          int len;
6746          uint8_t *opnd;
6747
6748          opnd = OPERAND(scan);
6749          // Inline the first byte, for speed.
6750          if (*opnd != *rex.input
6751              && (!rex.reg_ic)) {
6752            status = RA_NOMATCH;
6753          } else if (*opnd == NUL) {
6754            // match empty string always works; happens when "~" is
6755            // empty.
6756          } else {
6757            if (opnd[1] == NUL && !rex.reg_ic) {
6758              len = 1;  // matched a single byte above
6759            } else {
6760              // Need to match first byte again for multi-byte.
6761              len = (int)strlen((char *)opnd);
6762              if (cstrncmp((char *)opnd, (char *)rex.input, &len) != 0) {
6763                status = RA_NOMATCH;
6764              }
6765            }
6766            // Check for following composing character, unless %C
6767            // follows (skips over all composing chars).
6768            if (status != RA_NOMATCH
6769                && utf_composinglike((char *)rex.input, (char *)rex.input + len, NULL)
6770                && !rex.reg_icombine
6771                && OP(next) != RE_COMPOSING) {
6772              // raaron: This code makes a composing character get
6773              // ignored, which is the correct behavior (sometimes)
6774              // for voweled Hebrew texts.
6775              status = RA_NOMATCH;
6776            }
6777            if (status != RA_NOMATCH) {
6778              rex.input += len;
6779            }
6780          }
6781        }
6782        break;
6783
6784        case ANYOF:
6785        case ANYBUT: {
6786          uint8_t *q = OPERAND(scan);
6787
6788          if (c == NUL) {
6789            status = RA_NOMATCH;
6790          } else if ((cstrchr((char *)q, c) == NULL) == (op == ANYOF)) {
6791            status = RA_NOMATCH;
6792          } else {  // Check following combining characters
6793            int len = utfc_ptr2len((char *)q) - utf_ptr2len((char *)q);
6794
6795            rex.input += utf_ptr2len((char *)rex.input);
6796            q += utf_ptr2len((char *)q);
6797
6798            if (len == 0) {
6799              break;
6800            }
6801
6802            for (int i = 0; i < len; i++) {
6803              if (q[i] != rex.input[i]) {
6804                status = RA_NOMATCH;
6805                break;
6806              }
6807            }
6808            rex.input += len;
6809          }
6810          break;
6811        }
6812
6813        case MULTIBYTECODE: {
6814          int i, len;
6815
6816          const uint8_t *opnd = OPERAND(scan);
6817          // Safety check (just in case 'encoding' was changed since
6818          // compiling the program).
6819          if ((len = utfc_ptr2len((char *)opnd)) < 2) {
6820            status = RA_NOMATCH;
6821            break;
6822          }
6823          const int opndc = utf_ptr2char((char *)opnd);
6824          if (utf_iscomposing_legacy(opndc)) {
6825            // When only a composing char is given match at any
6826            // position where that composing char appears.
6827            status = RA_NOMATCH;
6828            for (i = 0; rex.input[i] != NUL;
6829                 i += utf_ptr2len((char *)rex.input + i)) {
6830              const int inpc = utf_ptr2char((char *)rex.input + i);
6831              if (!utf_iscomposing_legacy(inpc)) {
6832                if (i > 0) {
6833                  break;
6834                }
6835              } else if (opndc == inpc) {
6836                // Include all following composing chars.
6837                len = i + utfc_ptr2len((char *)rex.input + i);
6838                status = RA_MATCH;
6839                break;
6840              }
6841            }
6842          } else {
6843            if (cstrncmp((char *)opnd, (char *)rex.input, &len) != 0) {
6844              status = RA_NOMATCH;
6845              break;
6846            }
6847          }
6848          rex.input += len;
6849        }
6850        break;
6851
6852        case RE_COMPOSING:
6853          // Skip composing characters.
6854          while (utf_iscomposing_legacy(utf_ptr2char((char *)rex.input))) {
6855            rex.input += utf_ptr2len((char *)rex.input);
6856          }
6857          break;
6858
6859        case NOTHING:
6860          break;
6861
6862        case BACK: {
6863          int i;
6864
6865          // When we run into BACK we need to check if we don't keep
6866          // looping without matching any input.  The second and later
6867          // times a BACK is encountered it fails if the input is still
6868          // at the same position as the previous time.
6869          // The positions are stored in "backpos" and found by the
6870          // current value of "scan", the position in the RE program.
6871          backpos_T *bp = (backpos_T *)backpos.ga_data;
6872          for (i = 0; i < backpos.ga_len; i++) {
6873            if (bp[i].bp_scan == scan) {
6874              break;
6875            }
6876          }
6877          if (i == backpos.ga_len) {
6878            backpos_T *p = GA_APPEND_VIA_PTR(backpos_T, &backpos);
6879            p->bp_scan = scan;
6880          } else if (reg_save_equal(&bp[i].bp_pos)) {
6881            // Still at same position as last time, fail.
6882            status = RA_NOMATCH;
6883          }
6884
6885          assert(status != RA_FAIL);
6886          if (status != RA_NOMATCH) {
6887            reg_save(&bp[i].bp_pos, &backpos);
6888          }
6889        }
6890        break;
6891
6892        case MOPEN + 0:     // Match start: \zs
6893        case MOPEN + 1:     // \(
6894        case MOPEN + 2:
6895        case MOPEN + 3:
6896        case MOPEN + 4:
6897        case MOPEN + 5:
6898        case MOPEN + 6:
6899        case MOPEN + 7:
6900        case MOPEN + 8:
6901        case MOPEN + 9:
6902          no = op - MOPEN;
6903          cleanup_subexpr();
6904          rp = regstack_push(RS_MOPEN, scan);
6905          if (rp == NULL) {
6906            status = RA_FAIL;
6907          } else {
6908            rp->rs_no = (int16_t)no;
6909            save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],
6910                    &rex.reg_startp[no]);
6911            // We simply continue and handle the result when done.
6912          }
6913          break;
6914
6915        case NOPEN:         // \%(
6916        case NCLOSE:        // \) after \%(
6917          if (regstack_push(RS_NOPEN, scan) == NULL) {
6918            status = RA_FAIL;
6919          }
6920          // We simply continue and handle the result when done.
6921          break;
6922
6923        case ZOPEN + 1:
6924        case ZOPEN + 2:
6925        case ZOPEN + 3:
6926        case ZOPEN + 4:
6927        case ZOPEN + 5:
6928        case ZOPEN + 6:
6929        case ZOPEN + 7:
6930        case ZOPEN + 8:
6931        case ZOPEN + 9:
6932          no = op - ZOPEN;
6933          cleanup_zsubexpr();
6934          rp = regstack_push(RS_ZOPEN, scan);
6935          if (rp == NULL) {
6936            status = RA_FAIL;
6937          } else {
6938            rp->rs_no = (int16_t)no;
6939            save_se(&rp->rs_un.sesave, &reg_startzpos[no],
6940                    &reg_startzp[no]);
6941            // We simply continue and handle the result when done.
6942          }
6943          break;
6944
6945        case MCLOSE + 0:    // Match end: \ze
6946        case MCLOSE + 1:    // \)
6947        case MCLOSE + 2:
6948        case MCLOSE + 3:
6949        case MCLOSE + 4:
6950        case MCLOSE + 5:
6951        case MCLOSE + 6:
6952        case MCLOSE + 7:
6953        case MCLOSE + 8:
6954        case MCLOSE + 9:
6955          no = op - MCLOSE;
6956          cleanup_subexpr();
6957          rp = regstack_push(RS_MCLOSE, scan);
6958          if (rp == NULL) {
6959            status = RA_FAIL;
6960          } else {
6961            rp->rs_no = (int16_t)no;
6962            save_se(&rp->rs_un.sesave, &rex.reg_endpos[no], &rex.reg_endp[no]);
6963            // We simply continue and handle the result when done.
6964          }
6965          break;
6966
6967        case ZCLOSE + 1:    // \) after \z(
6968        case ZCLOSE + 2:
6969        case ZCLOSE + 3:
6970        case ZCLOSE + 4:
6971        case ZCLOSE + 5:
6972        case ZCLOSE + 6:
6973        case ZCLOSE + 7:
6974        case ZCLOSE + 8:
6975        case ZCLOSE + 9:
6976          no = op - ZCLOSE;
6977          cleanup_zsubexpr();
6978          rp = regstack_push(RS_ZCLOSE, scan);
6979          if (rp == NULL) {
6980            status = RA_FAIL;
6981          } else {
6982            rp->rs_no = (int16_t)no;
6983            save_se(&rp->rs_un.sesave, &reg_endzpos[no],
6984                    &reg_endzp[no]);
6985            // We simply continue and handle the result when done.
6986          }
6987          break;
6988
6989        case BACKREF + 1:
6990        case BACKREF + 2:
6991        case BACKREF + 3:
6992        case BACKREF + 4:
6993        case BACKREF + 5:
6994        case BACKREF + 6:
6995        case BACKREF + 7:
6996        case BACKREF + 8:
6997        case BACKREF + 9: {
6998          int len;
6999
7000          no = op - BACKREF;
7001          cleanup_subexpr();
7002          if (!REG_MULTI) {  // Single-line regexp
7003            if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL) {
7004              // Backref was not set: Match an empty string.
7005              len = 0;
7006            } else {
7007              // Compare current input with back-ref in the same line.
7008              len = (int)(rex.reg_endp[no] - rex.reg_startp[no]);
7009              if (cstrncmp((char *)rex.reg_startp[no], (char *)rex.input, &len) != 0) {
7010                status = RA_NOMATCH;
7011              }
7012            }
7013          } else {  // Multi-line regexp
7014            if (rex.reg_startpos[no].lnum < 0 || rex.reg_endpos[no].lnum < 0) {
7015              // Backref was not set: Match an empty string.
7016              len = 0;
7017            } else {
7018              if (rex.reg_startpos[no].lnum == rex.lnum
7019                  && rex.reg_endpos[no].lnum == rex.lnum) {
7020                // Compare back-ref within the current line.
7021                len = rex.reg_endpos[no].col - rex.reg_startpos[no].col;
7022                if (cstrncmp((char *)rex.line + rex.reg_startpos[no].col,
7023                             (char *)rex.input, &len) != 0) {
7024                  status = RA_NOMATCH;
7025                }
7026              } else {
7027                // Messy situation: Need to compare between two lines.
7028                int r = match_with_backref(rex.reg_startpos[no].lnum,
7029                                           rex.reg_startpos[no].col,
7030                                           rex.reg_endpos[no].lnum,
7031                                           rex.reg_endpos[no].col,
7032                                           &len);
7033                if (r != RA_MATCH) {
7034                  status = r;
7035                }
7036              }
7037            }
7038          }
7039
7040          // Matched the backref, skip over it.
7041          rex.input += len;
7042        }
7043        break;
7044
7045        case ZREF + 1:
7046        case ZREF + 2:
7047        case ZREF + 3:
7048        case ZREF + 4:
7049        case ZREF + 5:
7050        case ZREF + 6:
7051        case ZREF + 7:
7052        case ZREF + 8:
7053        case ZREF + 9:
7054          cleanup_zsubexpr();
7055          no = op - ZREF;
7056          if (re_extmatch_in != NULL
7057              && re_extmatch_in->matches[no] != NULL) {
7058            int len = (int)strlen((char *)re_extmatch_in->matches[no]);
7059            if (cstrncmp((char *)re_extmatch_in->matches[no], (char *)rex.input, &len) != 0) {
7060              status = RA_NOMATCH;
7061            } else {
7062              rex.input += len;
7063            }
7064          } else {
7065            // Backref was not set: Match an empty string.
7066          }
7067          break;
7068
7069        case BRANCH:
7070          if (OP(next) != BRANCH) {     // No choice.
7071            next = OPERAND(scan);               // Avoid recursion.
7072          } else {
7073            rp = regstack_push(RS_BRANCH, scan);
7074            if (rp == NULL) {
7075              status = RA_FAIL;
7076            } else {
7077              status = RA_BREAK;                // rest is below
7078            }
7079          }
7080          break;
7081
7082        case BRACE_LIMITS:
7083          if (OP(next) == BRACE_SIMPLE) {
7084            bl_minval = OPERAND_MIN(scan);
7085            bl_maxval = OPERAND_MAX(scan);
7086          } else if (OP(next) >= BRACE_COMPLEX
7087                     && OP(next) < BRACE_COMPLEX + 10) {
7088            no = OP(next) - BRACE_COMPLEX;
7089            brace_min[no] = OPERAND_MIN(scan);
7090            brace_max[no] = OPERAND_MAX(scan);
7091            brace_count[no] = 0;
7092          } else {
7093            internal_error("BRACE_LIMITS");
7094            status = RA_FAIL;
7095          }
7096          break;
7097
7098        case BRACE_COMPLEX + 0:
7099        case BRACE_COMPLEX + 1:
7100        case BRACE_COMPLEX + 2:
7101        case BRACE_COMPLEX + 3:
7102        case BRACE_COMPLEX + 4:
7103        case BRACE_COMPLEX + 5:
7104        case BRACE_COMPLEX + 6:
7105        case BRACE_COMPLEX + 7:
7106        case BRACE_COMPLEX + 8:
7107        case BRACE_COMPLEX + 9:
7108          no = op - BRACE_COMPLEX;
7109          brace_count[no]++;
7110
7111          // If not matched enough times yet, try one more
7112          if (brace_count[no] <= (brace_min[no] <= brace_max[no]
7113                                  ? brace_min[no] : brace_max[no])) {
7114            rp = regstack_push(RS_BRCPLX_MORE, scan);
7115            if (rp == NULL) {
7116              status = RA_FAIL;
7117            } else {
7118              rp->rs_no = (int16_t)no;
7119              reg_save(&rp->rs_un.regsave, &backpos);
7120              next = OPERAND(scan);
7121              // We continue and handle the result when done.
7122            }
7123            break;
7124          }
7125
7126          // If matched enough times, may try matching some more
7127          if (brace_min[no] <= brace_max[no]) {
7128            // Range is the normal way around, use longest match
7129            if (brace_count[no] <= brace_max[no]) {
7130              rp = regstack_push(RS_BRCPLX_LONG, scan);
7131              if (rp == NULL) {
7132                status = RA_FAIL;
7133              } else {
7134                rp->rs_no = (int16_t)no;
7135                reg_save(&rp->rs_un.regsave, &backpos);
7136                next = OPERAND(scan);
7137                // We continue and handle the result when done.
7138              }
7139            }
7140          } else {
7141            // Range is backwards, use shortest match first
7142            if (brace_count[no] <= brace_min[no]) {
7143              rp = regstack_push(RS_BRCPLX_SHORT, scan);
7144              if (rp == NULL) {
7145                status = RA_FAIL;
7146              } else {
7147                reg_save(&rp->rs_un.regsave, &backpos);
7148                // We continue and handle the result when done.
7149              }
7150            }
7151          }
7152          break;
7153
7154        case BRACE_SIMPLE:
7155        case STAR:
7156        case PLUS: {
7157          regstar_T rst;
7158
7159          // Lookahead to avoid useless match attempts when we know
7160          // what character comes next.
7161          if (OP(next) == EXACTLY) {
7162            rst.nextb = *OPERAND(next);
7163            if (rex.reg_ic) {
7164              if (mb_isupper(rst.nextb)) {
7165                rst.nextb_ic = mb_tolower(rst.nextb);
7166              } else {
7167                rst.nextb_ic = mb_toupper(rst.nextb);
7168              }
7169            } else {
7170              rst.nextb_ic = rst.nextb;
7171            }
7172          } else {
7173            rst.nextb = NUL;
7174            rst.nextb_ic = NUL;
7175          }
7176          if (op != BRACE_SIMPLE) {
7177            rst.minval = (op == STAR) ? 0 : 1;
7178            rst.maxval = MAX_LIMIT;
7179          } else {
7180            rst.minval = bl_minval;
7181            rst.maxval = bl_maxval;
7182          }
7183
7184          // When maxval > minval, try matching as much as possible, up
7185          // to maxval.  When maxval < minval, try matching at least the
7186          // minimal number (since the range is backwards, that's also
7187          // maxval!).
7188          rst.count = regrepeat(OPERAND(scan), rst.maxval);
7189          if (got_int) {
7190            status = RA_FAIL;
7191            break;
7192          }
7193          if (rst.minval <= rst.maxval
7194              ? rst.count >= rst.minval : rst.count >= rst.maxval) {
7195            // It could match.  Prepare for trying to match what
7196            // follows.  The code is below.  Parameters are stored in
7197            // a regstar_T on the regstack.
7198            if ((int64_t)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
7199              emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
7200              status = RA_FAIL;
7201            } else {
7202              ga_grow(&regstack, sizeof(regstar_T));
7203              regstack.ga_len += (int)sizeof(regstar_T);
7204              rp = regstack_push(rst.minval <= rst.maxval ? RS_STAR_LONG : RS_STAR_SHORT, scan);
7205              if (rp == NULL) {
7206                status = RA_FAIL;
7207              } else {
7208                *(((regstar_T *)rp) - 1) = rst;
7209                status = RA_BREAK;                  // skip the restore bits
7210              }
7211            }
7212          } else {
7213            status = RA_NOMATCH;
7214          }
7215        }
7216        break;
7217
7218        case NOMATCH:
7219        case MATCH:
7220        case SUBPAT:
7221          rp = regstack_push(RS_NOMATCH, scan);
7222          if (rp == NULL) {
7223            status = RA_FAIL;
7224          } else {
7225            rp->rs_no = (int16_t)op;
7226            reg_save(&rp->rs_un.regsave, &backpos);
7227            next = OPERAND(scan);
7228            // We continue and handle the result when done.
7229          }
7230          break;
7231
7232        case BEHIND:
7233        case NOBEHIND:
7234          // Need a bit of room to store extra positions.
7235          if ((int64_t)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
7236            emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
7237            status = RA_FAIL;
7238          } else {
7239            ga_grow(&regstack, sizeof(regbehind_T));
7240            regstack.ga_len += (int)sizeof(regbehind_T);
7241            rp = regstack_push(RS_BEHIND1, scan);
7242            if (rp == NULL) {
7243              status = RA_FAIL;
7244            } else {
7245              // Need to save the subexpr to be able to restore them
7246              // when there is a match but we don't use it.
7247              save_subexpr(((regbehind_T *)rp) - 1);
7248
7249              rp->rs_no = (int16_t)op;
7250              reg_save(&rp->rs_un.regsave, &backpos);
7251              // First try if what follows matches.  If it does then we
7252              // check the behind match by looping.
7253            }
7254          }
7255          break;
7256
7257        case BHPOS:
7258          if (REG_MULTI) {
7259            if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)
7260                || behind_pos.rs_u.pos.lnum != rex.lnum) {
7261              status = RA_NOMATCH;
7262            }
7263          } else if (behind_pos.rs_u.ptr != rex.input) {
7264            status = RA_NOMATCH;
7265          }
7266          break;
7267
7268        case NEWL:
7269          if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline
7270               || rex.reg_line_lbr) && (c != '\n' || !rex.reg_line_lbr)) {
7271            status = RA_NOMATCH;
7272          } else if (rex.reg_line_lbr) {
7273            ADVANCE_REGINPUT();
7274          } else {
7275            reg_nextline();
7276          }
7277          break;
7278
7279        case END:
7280          status = RA_MATCH;    // Success!
7281          break;
7282
7283        default:
7284          iemsg(_(e_re_corr));
7285#ifdef REGEXP_DEBUG
7286          printf("Illegal op code %d\n", op);
7287#endif
7288          status = RA_FAIL;
7289          break;
7290        }
7291      }
7292
7293      // If we can't continue sequentially, break the inner loop.
7294      if (status != RA_CONT) {
7295        break;
7296      }
7297
7298      // Continue in inner loop, advance to next item.
7299      scan = next;
7300    }  // end of inner loop
7301
7302    // If there is something on the regstack execute the code for the state.
7303    // If the state is popped then loop and use the older state.
7304    while (!GA_EMPTY(&regstack) && status != RA_FAIL) {
7305      rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
7306      switch (rp->rs_state) {
7307      case RS_NOPEN:
7308        // Result is passed on as-is, simply pop the state.
7309        regstack_pop(&scan);
7310        break;
7311
7312      case RS_MOPEN:
7313        // Pop the state.  Restore pointers when there is no match.
7314        if (status == RA_NOMATCH) {
7315          restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],
7316                     &rex.reg_startp[rp->rs_no]);
7317        }
7318        regstack_pop(&scan);
7319        break;
7320
7321      case RS_ZOPEN:
7322        // Pop the state.  Restore pointers when there is no match.
7323        if (status == RA_NOMATCH) {
7324          restore_se(&rp->rs_un.sesave, &reg_startzpos[rp->rs_no],
7325                     &reg_startzp[rp->rs_no]);
7326        }
7327        regstack_pop(&scan);
7328        break;
7329
7330      case RS_MCLOSE:
7331        // Pop the state.  Restore pointers when there is no match.
7332        if (status == RA_NOMATCH) {
7333          restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],
7334                     &rex.reg_endp[rp->rs_no]);
7335        }
7336        regstack_pop(&scan);
7337        break;
7338
7339      case RS_ZCLOSE:
7340        // Pop the state.  Restore pointers when there is no match.
7341        if (status == RA_NOMATCH) {
7342          restore_se(&rp->rs_un.sesave, &reg_endzpos[rp->rs_no],
7343                     &reg_endzp[rp->rs_no]);
7344        }
7345        regstack_pop(&scan);
7346        break;
7347
7348      case RS_BRANCH:
7349        if (status == RA_MATCH) {
7350          // this branch matched, use it
7351          regstack_pop(&scan);
7352        } else {
7353          if (status != RA_BREAK) {
7354            // After a non-matching branch: try next one.
7355            reg_restore(&rp->rs_un.regsave, &backpos);
7356            scan = rp->rs_scan;
7357          }
7358          if (scan == NULL || OP(scan) != BRANCH) {
7359            // no more branches, didn't find a match
7360            status = RA_NOMATCH;
7361            regstack_pop(&scan);
7362          } else {
7363            // Prepare to try a branch.
7364            rp->rs_scan = regnext(scan);
7365            reg_save(&rp->rs_un.regsave, &backpos);
7366            scan = OPERAND(scan);
7367          }
7368        }
7369        break;
7370
7371      case RS_BRCPLX_MORE:
7372        // Pop the state.  Restore pointers when there is no match.
7373        if (status == RA_NOMATCH) {
7374          reg_restore(&rp->rs_un.regsave, &backpos);
7375          brace_count[rp->rs_no]--;             // decrement match count
7376        }
7377        regstack_pop(&scan);
7378        break;
7379
7380      case RS_BRCPLX_LONG:
7381        // Pop the state.  Restore pointers when there is no match.
7382        if (status == RA_NOMATCH) {
7383          // There was no match, but we did find enough matches.
7384          reg_restore(&rp->rs_un.regsave, &backpos);
7385          brace_count[rp->rs_no]--;
7386          // continue with the items after "\{}"
7387          status = RA_CONT;
7388        }
7389        regstack_pop(&scan);
7390        if (status == RA_CONT) {
7391          scan = regnext(scan);
7392        }
7393        break;
7394
7395      case RS_BRCPLX_SHORT:
7396        // Pop the state.  Restore pointers when there is no match.
7397        if (status == RA_NOMATCH) {
7398          // There was no match, try to match one more item.
7399          reg_restore(&rp->rs_un.regsave, &backpos);
7400        }
7401        regstack_pop(&scan);
7402        if (status == RA_NOMATCH) {
7403          scan = OPERAND(scan);
7404          status = RA_CONT;
7405        }
7406        break;
7407
7408      case RS_NOMATCH:
7409        // Pop the state.  If the operand matches for NOMATCH or
7410        // doesn't match for MATCH/SUBPAT, we fail.  Otherwise backup,
7411        // except for SUBPAT, and continue with the next item.
7412        if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH)) {
7413          status = RA_NOMATCH;
7414        } else {
7415          status = RA_CONT;
7416          if (rp->rs_no != SUBPAT) {            // zero-width
7417            reg_restore(&rp->rs_un.regsave, &backpos);
7418          }
7419        }
7420        regstack_pop(&scan);
7421        if (status == RA_CONT) {
7422          scan = regnext(scan);
7423        }
7424        break;
7425
7426      case RS_BEHIND1:
7427        if (status == RA_NOMATCH) {
7428          regstack_pop(&scan);
7429          regstack.ga_len -= (int)sizeof(regbehind_T);
7430        } else {
7431          // The stuff after BEHIND/NOBEHIND matches.  Now try if
7432          // the behind part does (not) match before the current
7433          // position in the input.  This must be done at every
7434          // position in the input and checking if the match ends at
7435          // the current position.
7436
7437          // save the position after the found match for next
7438          reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);
7439
7440          // Start looking for a match with operand at the current
7441          // position.  Go back one character until we find the
7442          // result, hitting the start of the line or the previous
7443          // line (for multi-line matching).
7444          // Set behind_pos to where the match should end, BHPOS
7445          // will match it.  Save the current value.
7446          (((regbehind_T *)rp) - 1)->save_behind = behind_pos;
7447          behind_pos = rp->rs_un.regsave;
7448
7449          rp->rs_state = RS_BEHIND2;
7450
7451          reg_restore(&rp->rs_un.regsave, &backpos);
7452          scan = OPERAND(rp->rs_scan) + 4;
7453        }
7454        break;
7455
7456      case RS_BEHIND2:
7457        // Looping for BEHIND / NOBEHIND match.
7458        if (status == RA_MATCH && reg_save_equal(&behind_pos)) {
7459          // found a match that ends where "next" started
7460          behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
7461          if (rp->rs_no == BEHIND) {
7462            reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
7463                        &backpos);
7464          } else {
7465            // But we didn't want a match.  Need to restore the
7466            // subexpr, because what follows matched, so they have
7467            // been set.
7468            status = RA_NOMATCH;
7469            restore_subexpr(((regbehind_T *)rp) - 1);
7470          }
7471          regstack_pop(&scan);
7472          regstack.ga_len -= (int)sizeof(regbehind_T);
7473        } else {
7474          int64_t limit;
7475
7476          // No match or a match that doesn't end where we want it: Go
7477          // back one character.  May go to previous line once.
7478          no = OK;
7479          limit = OPERAND_MIN(rp->rs_scan);
7480          if (REG_MULTI) {
7481            if (limit > 0
7482                && ((rp->rs_un.regsave.rs_u.pos.lnum
7483                     < behind_pos.rs_u.pos.lnum
7484                     ? (colnr_T)strlen((char *)rex.line)
7485                     : behind_pos.rs_u.pos.col)
7486                    - rp->rs_un.regsave.rs_u.pos.col >= limit)) {
7487              no = FAIL;
7488            } else if (rp->rs_un.regsave.rs_u.pos.col == 0) {
7489              if (rp->rs_un.regsave.rs_u.pos.lnum
7490                  < behind_pos.rs_u.pos.lnum
7491                  || reg_getline(--rp->rs_un.regsave.rs_u.pos.lnum)
7492                  == NULL) {
7493                no = FAIL;
7494              } else {
7495                reg_restore(&rp->rs_un.regsave, &backpos);
7496                rp->rs_un.regsave.rs_u.pos.col =
7497                  (colnr_T)strlen((char *)rex.line);
7498              }
7499            } else {
7500              const uint8_t *const line =
7501                (uint8_t *)reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);
7502
7503              rp->rs_un.regsave.rs_u.pos.col -=
7504                utf_head_off((char *)line,
7505                             (char *)line + rp->rs_un.regsave.rs_u.pos.col - 1)
7506                + 1;
7507            }
7508          } else {
7509            if (rp->rs_un.regsave.rs_u.ptr == rex.line) {
7510              no = FAIL;
7511            } else {
7512              MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);
7513              if (limit > 0
7514                  && (behind_pos.rs_u.ptr - rp->rs_un.regsave.rs_u.ptr) > (ptrdiff_t)limit) {
7515                no = FAIL;
7516              }
7517            }
7518          }
7519          if (no == OK) {
7520            // Advanced, prepare for finding match again.
7521            reg_restore(&rp->rs_un.regsave, &backpos);
7522            scan = OPERAND(rp->rs_scan) + 4;
7523            if (status == RA_MATCH) {
7524              // We did match, so subexpr may have been changed,
7525              // need to restore them for the next try.
7526              status = RA_NOMATCH;
7527              restore_subexpr(((regbehind_T *)rp) - 1);
7528            }
7529          } else {
7530            // Can't advance.  For NOBEHIND that's a match.
7531            behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
7532            if (rp->rs_no == NOBEHIND) {
7533              reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
7534                          &backpos);
7535              status = RA_MATCH;
7536            } else {
7537              // We do want a proper match.  Need to restore the
7538              // subexpr if we had a match, because they may have
7539              // been set.
7540              if (status == RA_MATCH) {
7541                status = RA_NOMATCH;
7542                restore_subexpr(((regbehind_T *)rp) - 1);
7543              }
7544            }
7545            regstack_pop(&scan);
7546            regstack.ga_len -= (int)sizeof(regbehind_T);
7547          }
7548        }
7549        break;
7550
7551      case RS_STAR_LONG:
7552      case RS_STAR_SHORT: {
7553        regstar_T *rst = ((regstar_T *)rp) - 1;
7554
7555        if (status == RA_MATCH) {
7556          regstack_pop(&scan);
7557          regstack.ga_len -= (int)sizeof(regstar_T);
7558          break;
7559        }
7560
7561        // Tried once already, restore input pointers.
7562        if (status != RA_BREAK) {
7563          reg_restore(&rp->rs_un.regsave, &backpos);
7564        }
7565
7566        // Repeat until we found a position where it could match.
7567        while (true) {
7568          if (status != RA_BREAK) {
7569            // Tried first position already, advance.
7570            if (rp->rs_state == RS_STAR_LONG) {
7571              // Trying for longest match, but couldn't or
7572              // didn't match -- back up one char.
7573              if (--rst->count < rst->minval) {
7574                break;
7575              }
7576              if (rex.input == rex.line) {
7577                // backup to last char of previous line
7578                if (rex.lnum == 0) {
7579                  status = RA_NOMATCH;
7580                  break;
7581                }
7582                rex.lnum--;
7583                rex.line = (uint8_t *)reg_getline(rex.lnum);
7584                // Just in case regrepeat() didn't count right.
7585                if (rex.line == NULL) {
7586                  break;
7587                }
7588                rex.input = rex.line + reg_getline_len(rex.lnum);
7589                reg_breakcheck();
7590              } else {
7591                MB_PTR_BACK(rex.line, rex.input);
7592              }
7593            } else {
7594              // Range is backwards, use shortest match first.
7595              // Careful: maxval and minval are exchanged!
7596              // Couldn't or didn't match: try advancing one
7597              // char.
7598              if (rst->count == rst->minval
7599                  || regrepeat(OPERAND(rp->rs_scan), 1L) == 0) {
7600                break;
7601              }
7602              rst->count++;
7603            }
7604            if (got_int) {
7605              break;
7606            }
7607          } else {
7608            status = RA_NOMATCH;
7609          }
7610
7611          // If it could match, try it.
7612          if (rst->nextb == NUL || *rex.input == rst->nextb
7613              || *rex.input == rst->nextb_ic) {
7614            reg_save(&rp->rs_un.regsave, &backpos);
7615            scan = regnext(rp->rs_scan);
7616            status = RA_CONT;
7617            break;
7618          }
7619        }
7620        if (status != RA_CONT) {
7621          // Failed.
7622          regstack_pop(&scan);
7623          regstack.ga_len -= (int)sizeof(regstar_T);
7624          status = RA_NOMATCH;
7625        }
7626      }
7627      break;
7628      }
7629
7630      // If we want to continue the inner loop or didn't pop a state
7631      // continue matching loop
7632      if (status == RA_CONT || rp == (regitem_T *)
7633          ((char *)regstack.ga_data + regstack.ga_len) - 1) {
7634        break;
7635      }
7636    }
7637
7638    // May need to continue with the inner loop, starting at "scan".
7639    if (status == RA_CONT) {
7640      continue;
7641    }
7642
7643    // If the regstack is empty or something failed we are done.
7644    if (GA_EMPTY(&regstack) || status == RA_FAIL) {
7645      if (scan == NULL) {
7646        // We get here only if there's trouble -- normally "case END" is
7647        // the terminating point.
7648        iemsg(_(e_re_corr));
7649#ifdef REGEXP_DEBUG
7650        printf("Premature EOL\n");
7651#endif
7652      }
7653      return status == RA_MATCH;
7654    }
7655  }  // End of loop until the regstack is empty.
7656
7657  // NOTREACHED
7658}
7659
7660/// Try match of "prog" with at rex.line["col"].
7661///
7662/// @param tm         timeout limit or NULL
7663/// @param timed_out  flag set on timeout or NULL
7664///
7665/// @return  0 for failure, or number of lines contained in the match.
7666static int regtry(bt_regprog_T *prog, colnr_T col, proftime_T *tm, int *timed_out)
7667{
7668  rex.input = rex.line + col;
7669  rex.need_clear_subexpr = true;
7670  // Clear the external match subpointers if necessaey.
7671  rex.need_clear_zsubexpr = (prog->reghasz == REX_SET);
7672
7673  if (regmatch(&prog->program[1], tm, timed_out) == 0) {
7674    return 0;
7675  }
7676
7677  cleanup_subexpr();
7678  if (REG_MULTI) {
7679    if (rex.reg_startpos[0].lnum < 0) {
7680      rex.reg_startpos[0].lnum = 0;
7681      rex.reg_startpos[0].col = col;
7682    }
7683    if (rex.reg_endpos[0].lnum < 0) {
7684      rex.reg_endpos[0].lnum = rex.lnum;
7685      rex.reg_endpos[0].col = (int)(rex.input - rex.line);
7686    } else {
7687      // Use line number of "\ze".
7688      rex.lnum = rex.reg_endpos[0].lnum;
7689    }
7690  } else {
7691    if (rex.reg_startp[0] == NULL) {
7692      rex.reg_startp[0] = rex.line + col;
7693    }
7694    if (rex.reg_endp[0] == NULL) {
7695      rex.reg_endp[0] = rex.input;
7696    }
7697  }
7698  // Package any found \z(...\) matches for export. Default is none.
7699  unref_extmatch(re_extmatch_out);
7700  re_extmatch_out = NULL;
7701
7702  if (prog->reghasz == REX_SET) {
7703    int i;
7704
7705    cleanup_zsubexpr();
7706    re_extmatch_out = make_extmatch();
7707    for (i = 0; i < NSUBEXP; i++) {
7708      if (REG_MULTI) {
7709        // Only accept single line matches.
7710        if (reg_startzpos[i].lnum >= 0
7711            && reg_endzpos[i].lnum == reg_startzpos[i].lnum
7712            && reg_endzpos[i].col >= reg_startzpos[i].col) {
7713          re_extmatch_out->matches[i] =
7714            (uint8_t *)xstrnsave(reg_getline(reg_startzpos[i].lnum) + reg_startzpos[i].col,
7715                                 (size_t)(reg_endzpos[i].col - reg_startzpos[i].col));
7716        }
7717      } else {
7718        if (reg_startzp[i] != NULL && reg_endzp[i] != NULL) {
7719          re_extmatch_out->matches[i] =
7720            (uint8_t *)xstrnsave((char *)reg_startzp[i], (size_t)(reg_endzp[i] - reg_startzp[i]));
7721        }
7722      }
7723    }
7724  }
7725  return 1 + rex.lnum;
7726}
7727
7728/// Match a regexp against a string ("line" points to the string) or multiple
7729/// lines (if "line" is NULL, use reg_getline()).
7730///
7731/// @param startcol   column to start looking for match
7732/// @param tm         timeout limit or NULL
7733/// @param timed_out  flag set on timeout or NULL
7734///
7735/// @return  0 for failure, or number of lines contained in the match.
7736static int bt_regexec_both(uint8_t *line, colnr_T startcol, proftime_T *tm, int *timed_out)
7737{
7738  bt_regprog_T *prog;
7739  uint8_t *s;
7740  colnr_T col = startcol;
7741  int retval = 0;
7742
7743  // Create "regstack" and "backpos" if they are not allocated yet.
7744  // We allocate *_INITIAL amount of bytes first and then set the grow size
7745  // to much bigger value to avoid many malloc calls in case of deep regular
7746  // expressions.
7747  if (regstack.ga_data == NULL) {
7748    // Use an item size of 1 byte, since we push different things
7749    // onto the regstack.
7750    ga_init(&regstack, 1, REGSTACK_INITIAL);
7751    ga_grow(&regstack, REGSTACK_INITIAL);
7752    ga_set_growsize(&regstack, REGSTACK_INITIAL * 8);
7753  }
7754
7755  if (backpos.ga_data == NULL) {
7756    ga_init(&backpos, sizeof(backpos_T), BACKPOS_INITIAL);
7757    ga_grow(&backpos, BACKPOS_INITIAL);
7758    ga_set_growsize(&backpos, BACKPOS_INITIAL * 8);
7759  }
7760
7761  if (REG_MULTI) {
7762    prog = (bt_regprog_T *)rex.reg_mmatch->regprog;
7763    line = (uint8_t *)reg_getline(0);
7764    rex.reg_startpos = rex.reg_mmatch->startpos;
7765    rex.reg_endpos = rex.reg_mmatch->endpos;
7766  } else {
7767    prog = (bt_regprog_T *)rex.reg_match->regprog;
7768    rex.reg_startp = (uint8_t **)rex.reg_match->startp;
7769    rex.reg_endp = (uint8_t **)rex.reg_match->endp;
7770  }
7771
7772  // Be paranoid...
7773  if (prog == NULL || line == NULL) {
7774    iemsg(_(e_null));
7775    goto theend;
7776  }
7777
7778  // Check validity of program.
7779  if (prog_magic_wrong()) {
7780    goto theend;
7781  }
7782
7783  // If the start column is past the maximum column: no need to try.
7784  if (rex.reg_maxcol > 0 && col >= rex.reg_maxcol) {
7785    goto theend;
7786  }
7787
7788  // If pattern contains "\c" or "\C": overrule value of rex.reg_ic
7789  if (prog->regflags & RF_ICASE) {
7790    rex.reg_ic = true;
7791  } else if (prog->regflags & RF_NOICASE) {
7792    rex.reg_ic = false;
7793  }
7794
7795  // If pattern contains "\Z" overrule value of rex.reg_icombine
7796  if (prog->regflags & RF_ICOMBINE) {
7797    rex.reg_icombine = true;
7798  }
7799
7800  // If there is a "must appear" string, look for it.
7801  if (prog->regmust != NULL) {
7802    int c = utf_ptr2char((char *)prog->regmust);
7803    s = line + col;
7804
7805    // This is used very often, esp. for ":global".  Use two versions of
7806    // the loop to avoid overhead of conditions.
7807    if (!rex.reg_ic) {
7808      while ((s = (uint8_t *)vim_strchr((char *)s, c)) != NULL) {
7809        if (cstrncmp((char *)s, (char *)prog->regmust, &prog->regmlen) == 0) {
7810          break;  // Found it.
7811        }
7812        MB_PTR_ADV(s);
7813      }
7814    } else {
7815      while ((s = (uint8_t *)cstrchr((char *)s, c)) != NULL) {
7816        if (cstrncmp((char *)s, (char *)prog->regmust, &prog->regmlen) == 0) {
7817          break;  // Found it.
7818        }
7819        MB_PTR_ADV(s);
7820      }
7821    }
7822    if (s == NULL) {  // Not present.
7823      goto theend;
7824    }
7825  }
7826
7827  rex.line = line;
7828  rex.lnum = 0;
7829  reg_toolong = false;
7830
7831  // Simplest case: Anchored match need be tried only once.
7832  if (prog->reganch) {
7833    int c = utf_ptr2char((char *)rex.line + col);
7834    if (prog->regstart == NUL
7835        || prog->regstart == c
7836        || (rex.reg_ic
7837            && (utf_fold(prog->regstart) == utf_fold(c)
7838                || (c < 255 && prog->regstart < 255
7839                    && mb_tolower(prog->regstart) == mb_tolower(c))))) {
7840      retval = regtry(prog, col, tm, timed_out);
7841    } else {
7842      retval = 0;
7843    }
7844  } else {
7845    int tm_count = 0;
7846    // Messy cases:  unanchored match.
7847    while (!got_int) {
7848      if (prog->regstart != NUL) {
7849        // Skip until the char we know it must start with.
7850        s = (uint8_t *)cstrchr((char *)rex.line + col, prog->regstart);
7851        if (s == NULL) {
7852          retval = 0;
7853          break;
7854        }
7855        col = (int)(s - rex.line);
7856      }
7857
7858      // Check for maximum column to try.
7859      if (rex.reg_maxcol > 0 && col >= rex.reg_maxcol) {
7860        retval = 0;
7861        break;
7862      }
7863
7864      retval = regtry(prog, col, tm, timed_out);
7865      if (retval > 0) {
7866        break;
7867      }
7868
7869      // if not currently on the first line, get it again
7870      if (rex.lnum != 0) {
7871        rex.lnum = 0;
7872        rex.line = (uint8_t *)reg_getline(0);
7873      }
7874      if (rex.line[col] == NUL) {
7875        break;
7876      }
7877      col += utfc_ptr2len((char *)rex.line + col);
7878      // Check for timeout once in a twenty times to avoid overhead.
7879      if (tm != NULL && ++tm_count == 20) {
7880        tm_count = 0;
7881        if (profile_passed_limit(*tm)) {
7882          if (timed_out != NULL) {
7883            *timed_out = true;
7884          }
7885          break;
7886        }
7887      }
7888    }
7889  }
7890
7891theend:
7892  // Free "reg_tofree" when it's a bit big.
7893  // Free regstack and backpos if they are bigger than their initial size.
7894  if (reg_tofreelen > 400) {
7895    XFREE_CLEAR(reg_tofree);
7896  }
7897  if (regstack.ga_maxlen > REGSTACK_INITIAL) {
7898    ga_clear(&regstack);
7899  }
7900  if (backpos.ga_maxlen > BACKPOS_INITIAL) {
7901    ga_clear(&backpos);
7902  }
7903
7904  if (retval > 0) {
7905    // Make sure the end is never before the start.  Can happen when \zs
7906    // and \ze are used.
7907    if (REG_MULTI) {
7908      const lpos_T *const start = &rex.reg_mmatch->startpos[0];
7909      const lpos_T *const end = &rex.reg_mmatch->endpos[0];
7910
7911      if (end->lnum < start->lnum
7912          || (end->lnum == start->lnum && end->col < start->col)) {
7913        rex.reg_mmatch->endpos[0] = rex.reg_mmatch->startpos[0];
7914      }
7915
7916      // startpos[0] may be set by "\zs", also return the column where
7917      // the whole pattern matched.
7918      rex.reg_mmatch->rmm_matchcol = col;
7919    } else {
7920      if (rex.reg_match->endp[0] < rex.reg_match->startp[0]) {
7921        rex.reg_match->endp[0] = rex.reg_match->startp[0];
7922      }
7923
7924      // startpos[0] may be set by "\zs", also return the column where
7925      // the whole pattern matched.
7926      rex.reg_match->rm_matchcol = col;
7927    }
7928  }
7929
7930  return retval;
7931}
7932
7933/// Match a regexp against a string.
7934/// "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
7935/// Uses curbuf for line count and 'iskeyword'.
7936/// If "line_lbr" is true, consider a "\n" in "line" to be a line break.
7937///
7938/// @param line  string to match against
7939/// @param col   column to start looking for match
7940///
7941/// @return  0 for failure, number of lines contained in the match otherwise.
7942static int bt_regexec_nl(regmatch_T *rmp, uint8_t *line, colnr_T col, bool line_lbr)
7943{
7944  rex.reg_match = rmp;
7945  rex.reg_mmatch = NULL;
7946  rex.reg_maxline = 0;
7947  rex.reg_line_lbr = line_lbr;
7948  rex.reg_buf = curbuf;
7949  rex.reg_win = NULL;
7950  rex.reg_ic = rmp->rm_ic;
7951  rex.reg_icombine = false;
7952  rex.reg_nobreak = rmp->regprog->re_flags & RE_NOBREAK;
7953  rex.reg_maxcol = 0;
7954
7955  int64_t r = bt_regexec_both(line, col, NULL, NULL);
7956  assert(r <= INT_MAX);
7957  return (int)r;
7958}
7959
7960/// Matches a regexp against multiple lines.
7961/// "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
7962/// Uses curbuf for line count and 'iskeyword'.
7963///
7964/// @param win Window in which to search or NULL
7965/// @param buf Buffer in which to search
7966/// @param lnum Number of line to start looking for match
7967/// @param col Column to start looking for match
7968/// @param tm Timeout limit or NULL
7969///
7970/// @return zero if there is no match and number of lines contained in the match
7971///         otherwise.
7972static int bt_regexec_multi(regmmatch_T *rmp, win_T *win, buf_T *buf, linenr_T lnum, colnr_T col,
7973                            proftime_T *tm, int *timed_out)
7974{
7975  init_regexec_multi(rmp, win, buf, lnum);
7976  return bt_regexec_both(NULL, col, tm, timed_out);
7977}
7978
7979// Compare a number with the operand of RE_LNUM, RE_COL or RE_VCOL.
7980static int re_num_cmp(uint32_t val, const uint8_t *scan)
7981{
7982  uint32_t n = (uint32_t)OPERAND_MIN(scan);
7983
7984  if (OPERAND_CMP(scan) == '>') {
7985    return val > n;
7986  }
7987  if (OPERAND_CMP(scan) == '<') {
7988    return val < n;
7989  }
7990  return val == n;
7991}
7992
7993#ifdef BT_REGEXP_DUMP
7994
7995// regdump - dump a regexp onto stdout in vaguely comprehensible form
7996static void regdump(uint8_t *pattern, bt_regprog_T *r)
7997{
7998  uint8_t *s;
7999  int op = EXACTLY;             // Arbitrary non-END op.
8000  uint8_t *next;
8001  uint8_t *end = NULL;
8002  FILE *f;
8003
8004# ifdef BT_REGEXP_LOG
8005  f = fopen("bt_regexp_log.log", "a");
8006# else
8007  f = stdout;
8008# endif
8009  if (f == NULL) {
8010    return;
8011  }
8012  fprintf(f, "-------------------------------------\n\r\nregcomp(%s):\r\n",
8013          pattern);
8014
8015  s = &r->program[1];
8016  // Loop until we find the END that isn't before a referred next (an END
8017  // can also appear in a NOMATCH operand).
8018  while ((op != END || s <= end) && s < r->program + r->regsz) {
8019    op = OP(s);
8020    fprintf(f, "%2d%s", (int)(s - r->program), regprop(s));     // Where, what.
8021    next = (s + 3 <= r->program + r->regsz) ? regnext(s) : NULL;
8022    if (next == NULL) {         // Next ptr.
8023      fprintf(f, "(0)");
8024    } else {
8025      fprintf(f, "(%d)", (int)((s - r->program) + (next - s)));
8026    }
8027    if (end < next) {
8028      end = next;
8029    }
8030    if (op == BRACE_LIMITS) {
8031      // Two ints
8032      fprintf(f, " minval %" PRId64 ", maxval %" PRId64,
8033              (int64_t)OPERAND_MIN(s), (int64_t)OPERAND_MAX(s));
8034      s += 8;
8035    } else if (op == BEHIND || op == NOBEHIND) {
8036      // one int
8037      fprintf(f, " count %" PRId64, (int64_t)OPERAND_MIN(s));
8038      s += 4;
8039    } else if (op == RE_LNUM || op == RE_COL || op == RE_VCOL) {
8040      // one int plus comparator
8041      fprintf(f, " count %" PRId64, (int64_t)OPERAND_MIN(s));
8042      s += 5;
8043    }
8044    s += 3;
8045    if (op == MULTIBYTECODE) {
8046      fprintf(f, " mbc=%d", utf_ptr2char(s));
8047      s += utfc_ptr2len(s);
8048    }
8049    if (op == ANYOF || op == ANYOF + ADD_NL
8050        || op == ANYBUT || op == ANYBUT + ADD_NL
8051        || op == EXACTLY) {
8052      // Literal string, where present.
8053      fprintf(f, "\nxxxxxxxxx\n");
8054      while (*s != NUL && s < r->program + r->regsz) {
8055        fprintf(f, "%c", *s);
8056        s += utfc_ptr2len(s);  // advance by full char including combining
8057      }
8058      fprintf(f, "\nxxxxxxxxx\n");
8059      s++;
8060    }
8061    fprintf(f, "\r\n");
8062  }
8063
8064  // Header fields of interest.
8065  if (r->regstart != NUL) {
8066    fprintf(f, "start `%s' 0x%x; ", r->regstart < 256
8067            ? (char *)transchar(r->regstart)
8068            : "multibyte", r->regstart);
8069  }
8070  if (r->reganch) {
8071    fprintf(f, "anchored; ");
8072  }
8073  if (r->regmust != NULL) {
8074    fprintf(f, "must have \"%s\"", r->regmust);
8075  }
8076  fprintf(f, "\r\n");
8077
8078# ifdef BT_REGEXP_LOG
8079  fclose(f);
8080# endif
8081}
8082#endif      // BT_REGEXP_DUMP
8083
8084#ifdef REGEXP_DEBUG
8085
8086// regprop - printable representation of opcode
8087static uint8_t *regprop(uint8_t *op)
8088{
8089  char *p;
8090  static char buf[50];
8091  static size_t buflen = 0;
8092
8093  STRCPY(buf, ":");
8094  buflen = 1;
8095
8096  switch ((int)OP(op)) {
8097  case BOL:
8098    p = "BOL";
8099    break;
8100  case EOL:
8101    p = "EOL";
8102    break;
8103  case RE_BOF:
8104    p = "BOF";
8105    break;
8106  case RE_EOF:
8107    p = "EOF";
8108    break;
8109  case CURSOR:
8110    p = "CURSOR";
8111    break;
8112  case RE_VISUAL:
8113    p = "RE_VISUAL";
8114    break;
8115  case RE_LNUM:
8116    p = "RE_LNUM";
8117    break;
8118  case RE_MARK:
8119    p = "RE_MARK";
8120    break;
8121  case RE_COL:
8122    p = "RE_COL";
8123    break;
8124  case RE_VCOL:
8125    p = "RE_VCOL";
8126    break;
8127  case BOW:
8128    p = "BOW";
8129    break;
8130  case EOW:
8131    p = "EOW";
8132    break;
8133  case ANY:
8134    p = "ANY";
8135    break;
8136  case ANY + ADD_NL:
8137    p = "ANY+NL";
8138    break;
8139  case ANYOF:
8140    p = "ANYOF";
8141    break;
8142  case ANYOF + ADD_NL:
8143    p = "ANYOF+NL";
8144    break;
8145  case ANYBUT:
8146    p = "ANYBUT";
8147    break;
8148  case ANYBUT + ADD_NL:
8149    p = "ANYBUT+NL";
8150    break;
8151  case IDENT:
8152    p = "IDENT";
8153    break;
8154  case IDENT + ADD_NL:
8155    p = "IDENT+NL";
8156    break;
8157  case SIDENT:
8158    p = "SIDENT";
8159    break;
8160  case SIDENT + ADD_NL:
8161    p = "SIDENT+NL";
8162    break;
8163  case KWORD:
8164    p = "KWORD";
8165    break;
8166  case KWORD + ADD_NL:
8167    p = "KWORD+NL";
8168    break;
8169  case SKWORD:
8170    p = "SKWORD";
8171    break;
8172  case SKWORD + ADD_NL:
8173    p = "SKWORD+NL";
8174    break;
8175  case FNAME:
8176    p = "FNAME";
8177    break;
8178  case FNAME + ADD_NL:
8179    p = "FNAME+NL";
8180    break;
8181  case SFNAME:
8182    p = "SFNAME";
8183    break;
8184  case SFNAME + ADD_NL:
8185    p = "SFNAME+NL";
8186    break;
8187  case PRINT:
8188    p = "PRINT";
8189    break;
8190  case PRINT + ADD_NL:
8191    p = "PRINT+NL";
8192    break;
8193  case SPRINT:
8194    p = "SPRINT";
8195    break;
8196  case SPRINT + ADD_NL:
8197    p = "SPRINT+NL";
8198    break;
8199  case WHITE:
8200    p = "WHITE";
8201    break;
8202  case WHITE + ADD_NL:
8203    p = "WHITE+NL";
8204    break;
8205  case NWHITE:
8206    p = "NWHITE";
8207    break;
8208  case NWHITE + ADD_NL:
8209    p = "NWHITE+NL";
8210    break;
8211  case DIGIT:
8212    p = "DIGIT";
8213    break;
8214  case DIGIT + ADD_NL:
8215    p = "DIGIT+NL";
8216    break;
8217  case NDIGIT:
8218    p = "NDIGIT";
8219    break;
8220  case NDIGIT + ADD_NL:
8221    p = "NDIGIT+NL";
8222    break;
8223  case HEX:
8224    p = "HEX";
8225    break;
8226  case HEX + ADD_NL:
8227    p = "HEX+NL";
8228    break;
8229  case NHEX:
8230    p = "NHEX";
8231    break;
8232  case NHEX + ADD_NL:
8233    p = "NHEX+NL";
8234    break;
8235  case OCTAL:
8236    p = "OCTAL";
8237    break;
8238  case OCTAL + ADD_NL:
8239    p = "OCTAL+NL";
8240    break;
8241  case NOCTAL:
8242    p = "NOCTAL";
8243    break;
8244  case NOCTAL + ADD_NL:
8245    p = "NOCTAL+NL";
8246    break;
8247  case WORD:
8248    p = "WORD";
8249    break;
8250  case WORD + ADD_NL:
8251    p = "WORD+NL";
8252    break;
8253  case NWORD:
8254    p = "NWORD";
8255    break;
8256  case NWORD + ADD_NL:
8257    p = "NWORD+NL";
8258    break;
8259  case HEAD:
8260    p = "HEAD";
8261    break;
8262  case HEAD + ADD_NL:
8263    p = "HEAD+NL";
8264    break;
8265  case NHEAD:
8266    p = "NHEAD";
8267    break;
8268  case NHEAD + ADD_NL:
8269    p = "NHEAD+NL";
8270    break;
8271  case ALPHA:
8272    p = "ALPHA";
8273    break;
8274  case ALPHA + ADD_NL:
8275    p = "ALPHA+NL";
8276    break;
8277  case NALPHA:
8278    p = "NALPHA";
8279    break;
8280  case NALPHA + ADD_NL:
8281    p = "NALPHA+NL";
8282    break;
8283  case LOWER:
8284    p = "LOWER";
8285    break;
8286  case LOWER + ADD_NL:
8287    p = "LOWER+NL";
8288    break;
8289  case NLOWER:
8290    p = "NLOWER";
8291    break;
8292  case NLOWER + ADD_NL:
8293    p = "NLOWER+NL";
8294    break;
8295  case UPPER:
8296    p = "UPPER";
8297    break;
8298  case UPPER + ADD_NL:
8299    p = "UPPER+NL";
8300    break;
8301  case NUPPER:
8302    p = "NUPPER";
8303    break;
8304  case NUPPER + ADD_NL:
8305    p = "NUPPER+NL";
8306    break;
8307  case BRANCH:
8308    p = "BRANCH";
8309    break;
8310  case EXACTLY:
8311    p = "EXACTLY";
8312    break;
8313  case NOTHING:
8314    p = "NOTHING";
8315    break;
8316  case BACK:
8317    p = "BACK";
8318    break;
8319  case END:
8320    p = "END";
8321    break;
8322  case MOPEN + 0:
8323    p = "MATCH START";
8324    break;
8325  case MOPEN + 1:
8326  case MOPEN + 2:
8327  case MOPEN + 3:
8328  case MOPEN + 4:
8329  case MOPEN + 5:
8330  case MOPEN + 6:
8331  case MOPEN + 7:
8332  case MOPEN + 8:
8333  case MOPEN + 9:
8334    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8335                               "MOPEN%d", OP(op) - MOPEN);
8336    p = NULL;
8337    break;
8338  case MCLOSE + 0:
8339    p = "MATCH END";
8340    break;
8341  case MCLOSE + 1:
8342  case MCLOSE + 2:
8343  case MCLOSE + 3:
8344  case MCLOSE + 4:
8345  case MCLOSE + 5:
8346  case MCLOSE + 6:
8347  case MCLOSE + 7:
8348  case MCLOSE + 8:
8349  case MCLOSE + 9:
8350    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8351                               "MCLOSE%d", OP(op) - MCLOSE);
8352    p = NULL;
8353    break;
8354  case BACKREF + 1:
8355  case BACKREF + 2:
8356  case BACKREF + 3:
8357  case BACKREF + 4:
8358  case BACKREF + 5:
8359  case BACKREF + 6:
8360  case BACKREF + 7:
8361  case BACKREF + 8:
8362  case BACKREF + 9:
8363    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8364                               "BACKREF%d", OP(op) - BACKREF);
8365    p = NULL;
8366    break;
8367  case NOPEN:
8368    p = "NOPEN";
8369    break;
8370  case NCLOSE:
8371    p = "NCLOSE";
8372    break;
8373  case ZOPEN + 1:
8374  case ZOPEN + 2:
8375  case ZOPEN + 3:
8376  case ZOPEN + 4:
8377  case ZOPEN + 5:
8378  case ZOPEN + 6:
8379  case ZOPEN + 7:
8380  case ZOPEN + 8:
8381  case ZOPEN + 9:
8382    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8383                               "ZOPEN%d", OP(op) - ZOPEN);
8384    p = NULL;
8385    break;
8386  case ZCLOSE + 1:
8387  case ZCLOSE + 2:
8388  case ZCLOSE + 3:
8389  case ZCLOSE + 4:
8390  case ZCLOSE + 5:
8391  case ZCLOSE + 6:
8392  case ZCLOSE + 7:
8393  case ZCLOSE + 8:
8394  case ZCLOSE + 9:
8395    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8396                               "ZCLOSE%d", OP(op) - ZCLOSE);
8397    p = NULL;
8398    break;
8399  case ZREF + 1:
8400  case ZREF + 2:
8401  case ZREF + 3:
8402  case ZREF + 4:
8403  case ZREF + 5:
8404  case ZREF + 6:
8405  case ZREF + 7:
8406  case ZREF + 8:
8407  case ZREF + 9:
8408    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8409                               "ZREF%d", OP(op) - ZREF);
8410    p = NULL;
8411    break;
8412  case STAR:
8413    p = "STAR";
8414    break;
8415  case PLUS:
8416    p = "PLUS";
8417    break;
8418  case NOMATCH:
8419    p = "NOMATCH";
8420    break;
8421  case MATCH:
8422    p = "MATCH";
8423    break;
8424  case BEHIND:
8425    p = "BEHIND";
8426    break;
8427  case NOBEHIND:
8428    p = "NOBEHIND";
8429    break;
8430  case SUBPAT:
8431    p = "SUBPAT";
8432    break;
8433  case BRACE_LIMITS:
8434    p = "BRACE_LIMITS";
8435    break;
8436  case BRACE_SIMPLE:
8437    p = "BRACE_SIMPLE";
8438    break;
8439  case BRACE_COMPLEX + 0:
8440  case BRACE_COMPLEX + 1:
8441  case BRACE_COMPLEX + 2:
8442  case BRACE_COMPLEX + 3:
8443  case BRACE_COMPLEX + 4:
8444  case BRACE_COMPLEX + 5:
8445  case BRACE_COMPLEX + 6:
8446  case BRACE_COMPLEX + 7:
8447  case BRACE_COMPLEX + 8:
8448  case BRACE_COMPLEX + 9:
8449    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8450                               "BRACE_COMPLEX%d", OP(op) - BRACE_COMPLEX);
8451    p = NULL;
8452    break;
8453  case MULTIBYTECODE:
8454    p = "MULTIBYTECODE";
8455    break;
8456  case NEWL:
8457    p = "NEWL";
8458    break;
8459  default:
8460    buflen += (size_t)snprintf(buf + buflen, sizeof(buf) - buflen,
8461                               "corrupt %d", OP(op));
8462    p = NULL;
8463    break;
8464  }
8465  if (p != NULL) {
8466    xstrlcpy(buf + buflen, p, sizeof(buf) - buflen);
8467  }
8468  return (uint8_t *)buf;
8469}
8470#endif      // REGEXP_DEBUG
8471
8472// }}}1
8473
8474// regexp_nfa.c {{{1
8475// NFA regular expression implementation.
8476
8477// Logging of NFA engine.
8478//
8479// The NFA engine can write four log files:
8480// - Error log: Contains NFA engine's fatal errors.
8481// - Dump log: Contains compiled NFA state machine's information.
8482// - Run log: Contains information of matching procedure.
8483// - Debug log: Contains detailed information of matching procedure. Can be
8484//   disabled by undefining NFA_REGEXP_DEBUG_LOG.
8485// The first one can also be used without debug mode.
8486// The last three are enabled when compiled as debug mode and individually
8487// disabled by commenting them out.
8488// The log files can get quite big!
8489// To disable all of this when compiling Vim for debugging, undefine REGEXP_DEBUG in
8490// regexp.c
8491#ifdef REGEXP_DEBUG
8492# define NFA_REGEXP_ERROR_LOG   "nfa_regexp_error.log"
8493# define NFA_REGEXP_DUMP_LOG    "nfa_regexp_dump.log"
8494# define NFA_REGEXP_RUN_LOG     "nfa_regexp_run.log"
8495# define NFA_REGEXP_DEBUG_LOG   "nfa_regexp_debug.log"
8496#endif
8497
8498// Added to NFA_ANY - NFA_NUPPER_IC to include a NL.
8499#define NFA_ADD_NL              31
8500
8501enum {
8502  NFA_SPLIT = -1024,
8503  NFA_MATCH,
8504  NFA_EMPTY,                        // matches 0-length
8505
8506  NFA_START_COLL,                   // [abc] start
8507  NFA_END_COLL,                     // [abc] end
8508  NFA_START_NEG_COLL,               // [^abc] start
8509  NFA_END_NEG_COLL,                 // [^abc] end (postfix only)
8510  NFA_RANGE,                        // range of the two previous items
8511                                    // (postfix only)
8512  NFA_RANGE_MIN,                    // low end of a range
8513  NFA_RANGE_MAX,                    // high end of a range
8514
8515  NFA_CONCAT,                       // concatenate two previous items (postfix
8516                                    // only)
8517  NFA_OR,                           // \| (postfix only)
8518  NFA_STAR,                         // greedy * (postfix only)
8519  NFA_STAR_NONGREEDY,               // non-greedy * (postfix only)
8520  NFA_QUEST,                        // greedy \? (postfix only)
8521  NFA_QUEST_NONGREEDY,              // non-greedy \? (postfix only)
8522
8523  NFA_BOL,                          // ^    Begin line
8524  NFA_EOL,                          // $    End line
8525  NFA_BOW,                          // \<   Begin word
8526  NFA_EOW,                          // \>   End word
8527  NFA_BOF,                          // \%^  Begin file
8528  NFA_EOF,                          // \%$  End file
8529  NFA_NEWL,
8530  NFA_ZSTART,                       // Used for \zs
8531  NFA_ZEND,                         // Used for \ze
8532  NFA_NOPEN,                        // Start of subexpression marked with \%(
8533  NFA_NCLOSE,                       // End of subexpr. marked with \%( ... \)
8534  NFA_START_INVISIBLE,
8535  NFA_START_INVISIBLE_FIRST,
8536  NFA_START_INVISIBLE_NEG,
8537  NFA_START_INVISIBLE_NEG_FIRST,
8538  NFA_START_INVISIBLE_BEFORE,
8539  NFA_START_INVISIBLE_BEFORE_FIRST,
8540  NFA_START_INVISIBLE_BEFORE_NEG,
8541  NFA_START_INVISIBLE_BEFORE_NEG_FIRST,
8542  NFA_START_PATTERN,
8543  NFA_END_INVISIBLE,
8544  NFA_END_INVISIBLE_NEG,
8545  NFA_END_PATTERN,
8546  NFA_COMPOSING,                    // Next nodes in NFA are part of the
8547                                    // composing multibyte char
8548  NFA_END_COMPOSING,                // End of a composing char in the NFA
8549  NFA_ANY_COMPOSING,                // \%C: Any composing characters.
8550  NFA_OPT_CHARS,                    // \%[abc]
8551
8552  // The following are used only in the postfix form, not in the NFA
8553  NFA_PREV_ATOM_NO_WIDTH,           // Used for \@=
8554  NFA_PREV_ATOM_NO_WIDTH_NEG,       // Used for \@!
8555  NFA_PREV_ATOM_JUST_BEFORE,        // Used for \@<=
8556  NFA_PREV_ATOM_JUST_BEFORE_NEG,    // Used for \@<!
8557  NFA_PREV_ATOM_LIKE_PATTERN,       // Used for \@>
8558
8559  NFA_BACKREF1,                     // \1
8560  NFA_BACKREF2,                     // \2
8561  NFA_BACKREF3,                     // \3
8562  NFA_BACKREF4,                     // \4
8563  NFA_BACKREF5,                     // \5
8564  NFA_BACKREF6,                     // \6
8565  NFA_BACKREF7,                     // \7
8566  NFA_BACKREF8,                     // \8
8567  NFA_BACKREF9,                     // \9
8568  NFA_ZREF1,                        // \z1
8569  NFA_ZREF2,                        // \z2
8570  NFA_ZREF3,                        // \z3
8571  NFA_ZREF4,                        // \z4
8572  NFA_ZREF5,                        // \z5
8573  NFA_ZREF6,                        // \z6
8574  NFA_ZREF7,                        // \z7
8575  NFA_ZREF8,                        // \z8
8576  NFA_ZREF9,                        // \z9
8577  NFA_SKIP,                         // Skip characters
8578
8579  NFA_MOPEN,
8580  NFA_MOPEN1,
8581  NFA_MOPEN2,
8582  NFA_MOPEN3,
8583  NFA_MOPEN4,
8584  NFA_MOPEN5,
8585  NFA_MOPEN6,
8586  NFA_MOPEN7,
8587  NFA_MOPEN8,
8588  NFA_MOPEN9,
8589
8590  NFA_MCLOSE,
8591  NFA_MCLOSE1,
8592  NFA_MCLOSE2,
8593  NFA_MCLOSE3,
8594  NFA_MCLOSE4,
8595  NFA_MCLOSE5,
8596  NFA_MCLOSE6,
8597  NFA_MCLOSE7,
8598  NFA_MCLOSE8,
8599  NFA_MCLOSE9,
8600
8601  NFA_ZOPEN,
8602  NFA_ZOPEN1,
8603  NFA_ZOPEN2,
8604  NFA_ZOPEN3,
8605  NFA_ZOPEN4,
8606  NFA_ZOPEN5,
8607  NFA_ZOPEN6,
8608  NFA_ZOPEN7,
8609  NFA_ZOPEN8,
8610  NFA_ZOPEN9,
8611
8612  NFA_ZCLOSE,
8613  NFA_ZCLOSE1,
8614  NFA_ZCLOSE2,
8615  NFA_ZCLOSE3,
8616  NFA_ZCLOSE4,
8617  NFA_ZCLOSE5,
8618  NFA_ZCLOSE6,
8619  NFA_ZCLOSE7,
8620  NFA_ZCLOSE8,
8621  NFA_ZCLOSE9,
8622
8623  // NFA_FIRST_NL
8624  NFA_ANY,              //      Match any one character.
8625  NFA_IDENT,            //      Match identifier char
8626  NFA_SIDENT,           //      Match identifier char but no digit
8627  NFA_KWORD,            //      Match keyword char
8628  NFA_SKWORD,           //      Match word char but no digit
8629  NFA_FNAME,            //      Match file name char
8630  NFA_SFNAME,           //      Match file name char but no digit
8631  NFA_PRINT,            //      Match printable char
8632  NFA_SPRINT,           //      Match printable char but no digit
8633  NFA_WHITE,            //      Match whitespace char
8634  NFA_NWHITE,           //      Match non-whitespace char
8635  NFA_DIGIT,            //      Match digit char
8636  NFA_NDIGIT,           //      Match non-digit char
8637  NFA_HEX,              //      Match hex char
8638  NFA_NHEX,             //      Match non-hex char
8639  NFA_OCTAL,            //      Match octal char
8640  NFA_NOCTAL,           //      Match non-octal char
8641  NFA_WORD,             //      Match word char
8642  NFA_NWORD,            //      Match non-word char
8643  NFA_HEAD,             //      Match head char
8644  NFA_NHEAD,            //      Match non-head char
8645  NFA_ALPHA,            //      Match alpha char
8646  NFA_NALPHA,           //      Match non-alpha char
8647  NFA_LOWER,            //      Match lowercase char
8648  NFA_NLOWER,           //      Match non-lowercase char
8649  NFA_UPPER,            //      Match uppercase char
8650  NFA_NUPPER,           //      Match non-uppercase char
8651  NFA_LOWER_IC,         //      Match [a-z]
8652  NFA_NLOWER_IC,        //      Match [^a-z]
8653  NFA_UPPER_IC,         //      Match [A-Z]
8654  NFA_NUPPER_IC,        //      Match [^A-Z]
8655
8656  NFA_FIRST_NL = NFA_ANY + NFA_ADD_NL,
8657  NFA_LAST_NL = NFA_NUPPER_IC + NFA_ADD_NL,
8658
8659  NFA_CURSOR,           //      Match cursor pos
8660  NFA_LNUM,             //      Match line number
8661  NFA_LNUM_GT,          //      Match > line number
8662  NFA_LNUM_LT,          //      Match < line number
8663  NFA_COL,              //      Match cursor column
8664  NFA_COL_GT,           //      Match > cursor column
8665  NFA_COL_LT,           //      Match < cursor column
8666  NFA_VCOL,             //      Match cursor virtual column
8667  NFA_VCOL_GT,          //      Match > cursor virtual column
8668  NFA_VCOL_LT,          //      Match < cursor virtual column
8669  NFA_MARK,             //      Match mark
8670  NFA_MARK_GT,          //      Match > mark
8671  NFA_MARK_LT,          //      Match < mark
8672  NFA_VISUAL,           //      Match Visual area
8673
8674  // Character classes [:alnum:] etc
8675  NFA_CLASS_ALNUM,
8676  NFA_CLASS_ALPHA,
8677  NFA_CLASS_BLANK,
8678  NFA_CLASS_CNTRL,
8679  NFA_CLASS_DIGIT,
8680  NFA_CLASS_GRAPH,
8681  NFA_CLASS_LOWER,
8682  NFA_CLASS_PRINT,
8683  NFA_CLASS_PUNCT,
8684  NFA_CLASS_SPACE,
8685  NFA_CLASS_UPPER,
8686  NFA_CLASS_XDIGIT,
8687  NFA_CLASS_TAB,
8688  NFA_CLASS_RETURN,
8689  NFA_CLASS_BACKSPACE,
8690  NFA_CLASS_ESCAPE,
8691  NFA_CLASS_IDENT,
8692  NFA_CLASS_KEYWORD,
8693  NFA_CLASS_FNAME,
8694};
8695
8696// Keep in sync with classchars.
8697static const int nfa_classcodes[] = {
8698  NFA_ANY, NFA_IDENT, NFA_SIDENT, NFA_KWORD, NFA_SKWORD,
8699  NFA_FNAME, NFA_SFNAME, NFA_PRINT, NFA_SPRINT,
8700  NFA_WHITE, NFA_NWHITE, NFA_DIGIT, NFA_NDIGIT,
8701  NFA_HEX, NFA_NHEX, NFA_OCTAL, NFA_NOCTAL,
8702  NFA_WORD, NFA_NWORD, NFA_HEAD, NFA_NHEAD,
8703  NFA_ALPHA, NFA_NALPHA, NFA_LOWER, NFA_NLOWER,
8704  NFA_UPPER, NFA_NUPPER
8705};
8706
8707static const char e_nul_found[] = N_("E865: (NFA) Regexp end encountered prematurely");
8708static const char e_misplaced[] = N_("E866: (NFA regexp) Misplaced %c");
8709static const char e_ill_char_class[] = N_("E877: (NFA regexp) Invalid character class: %" PRId64);
8710static const char e_value_too_large[] = N_("E951: \\% value too large");
8711
8712// Variables only used in nfa_regcomp() and descendants.
8713static int nfa_re_flags;  ///< re_flags passed to nfa_regcomp().
8714static int *post_start;   ///< holds the postfix form of r.e.
8715static size_t post_start_len;  ///< size of allocated post_start (in ints)
8716static int *post_end;
8717static int *post_ptr;
8718static int nfa_reg_parse_depth;  // nesting depth in nfa_reg()
8719
8720// The postfix list (post_start) and fragment stack (nfa_stack) are reused
8721// across compilations; a buffer that grew past these sizes for a big pattern
8722// is freed afterwards instead of being kept, to avoid holding much memory.
8723#define NFA_POSTFIX_KEEP        10000   // number of ints (~40 Kbyte)
8724#define NFA_STACK_KEEP          4000    // number of Frag_T (~64 Kbyte)
8725
8726// Set when the pattern should use the NFA engine.
8727// E.g. [[:upper:]] only allows 8bit characters for BT engine,
8728// while NFA engine handles multibyte characters correctly.
8729static bool wants_nfa;
8730
8731static int nstate;  ///< Number of states in the NFA. Also used when executing.
8732static int istate;  ///< Index in the state vector, used in alloc_state()
8733
8734// If not NULL match must end at this position
8735static save_se_T *nfa_endp = NULL;
8736
8737// 0 for first call to nfa_regmatch(), 1 for recursive call.
8738static int nfa_ll_index = 0;
8739
8740// Helper functions used when doing re2post() ... regatom() parsing
8741#define EMIT(c) \
8742  do { \
8743    if (post_ptr >= post_end) { \
8744      realloc_post_list(); \
8745    } \
8746    *post_ptr++ = c; \
8747  } while (0)
8748
8749/// Initialize internal variables before NFA compilation.
8750///
8751/// @param re_flags  @see vim_regcomp()
8752static void nfa_regcomp_start(uint8_t *expr, int re_flags)
8753{
8754  size_t postfix_size;
8755  size_t nstate_max;
8756
8757  nstate = 0;
8758  istate = 0;
8759  // A reasonable estimation for maximum size
8760  nstate_max = (strlen((char *)expr) + 1) * 25;
8761
8762  // Some items blow up in size, such as [A-z].  Add more space for that.
8763  // When it is still not enough realloc_post_list() will be used.
8764  nstate_max += 1000;
8765
8766  // Size for postfix representation of expr.
8767  postfix_size = sizeof(int) * nstate_max;
8768
8769  // Reuse the postfix buffer across compilations, only growing it when the
8770  // estimate exceeds the current size; it is freed in free_regexp_stuff().
8771  if (post_start == NULL || post_start_len < nstate_max) {
8772    xfree(post_start);
8773    post_start = xmalloc(postfix_size);
8774    post_start_len = nstate_max;
8775  }
8776  post_ptr = post_start;
8777  post_end = post_start + post_start_len;
8778  wants_nfa = false;
8779  rex.nfa_has_zend = false;
8780  rex.nfa_has_backref = false;
8781  nfa_reg_parse_depth = 0;
8782
8783  // shared with BT engine
8784  regcomp_start(expr, re_flags);
8785}
8786
8787// Figure out if the NFA state list starts with an anchor, must match at start
8788// of the line.
8789static int nfa_get_reganch(nfa_state_T *start, int depth)
8790{
8791  nfa_state_T *p = start;
8792
8793  if (depth > 4) {
8794    return 0;
8795  }
8796
8797  while (p != NULL) {
8798    switch (p->c) {
8799    case NFA_BOL:
8800    case NFA_BOF:
8801      return 1;           // yes!
8802
8803    case NFA_ZSTART:
8804    case NFA_ZEND:
8805    case NFA_CURSOR:
8806    case NFA_VISUAL:
8807
8808    case NFA_MOPEN:
8809    case NFA_MOPEN1:
8810    case NFA_MOPEN2:
8811    case NFA_MOPEN3:
8812    case NFA_MOPEN4:
8813    case NFA_MOPEN5:
8814    case NFA_MOPEN6:
8815    case NFA_MOPEN7:
8816    case NFA_MOPEN8:
8817    case NFA_MOPEN9:
8818    case NFA_NOPEN:
8819    case NFA_ZOPEN:
8820    case NFA_ZOPEN1:
8821    case NFA_ZOPEN2:
8822    case NFA_ZOPEN3:
8823    case NFA_ZOPEN4:
8824    case NFA_ZOPEN5:
8825    case NFA_ZOPEN6:
8826    case NFA_ZOPEN7:
8827    case NFA_ZOPEN8:
8828    case NFA_ZOPEN9:
8829      p = p->out;
8830      break;
8831
8832    case NFA_SPLIT:
8833      return nfa_get_reganch(p->out, depth + 1)
8834             && nfa_get_reganch(p->out1, depth + 1);
8835
8836    default:
8837      return 0;           // noooo
8838    }
8839  }
8840  return 0;
8841}
8842
8843// Figure out if the NFA state list starts with a character which must match
8844// at start of the match.
8845static int nfa_get_regstart(nfa_state_T *start, int depth)
8846{
8847  nfa_state_T *p = start;
8848
8849  if (depth > 4) {
8850    return 0;
8851  }
8852
8853  while (p != NULL) {
8854    switch (p->c) {
8855    // all kinds of zero-width matches
8856    case NFA_BOL:
8857    case NFA_BOF:
8858    case NFA_BOW:
8859    case NFA_EOW:
8860    case NFA_ZSTART:
8861    case NFA_ZEND:
8862    case NFA_CURSOR:
8863    case NFA_VISUAL:
8864    case NFA_LNUM:
8865    case NFA_LNUM_GT:
8866    case NFA_LNUM_LT:
8867    case NFA_COL:
8868    case NFA_COL_GT:
8869    case NFA_COL_LT:
8870    case NFA_VCOL:
8871    case NFA_VCOL_GT:
8872    case NFA_VCOL_LT:
8873    case NFA_MARK:
8874    case NFA_MARK_GT:
8875    case NFA_MARK_LT:
8876
8877    case NFA_MOPEN:
8878    case NFA_MOPEN1:
8879    case NFA_MOPEN2:
8880    case NFA_MOPEN3:
8881    case NFA_MOPEN4:
8882    case NFA_MOPEN5:
8883    case NFA_MOPEN6:
8884    case NFA_MOPEN7:
8885    case NFA_MOPEN8:
8886    case NFA_MOPEN9:
8887    case NFA_NOPEN:
8888    case NFA_ZOPEN:
8889    case NFA_ZOPEN1:
8890    case NFA_ZOPEN2:
8891    case NFA_ZOPEN3:
8892    case NFA_ZOPEN4:
8893    case NFA_ZOPEN5:
8894    case NFA_ZOPEN6:
8895    case NFA_ZOPEN7:
8896    case NFA_ZOPEN8:
8897    case NFA_ZOPEN9:
8898      p = p->out;
8899      break;
8900
8901    case NFA_SPLIT: {
8902      int c1 = nfa_get_regstart(p->out, depth + 1);
8903      int c2 = nfa_get_regstart(p->out1, depth + 1);
8904
8905      if (c1 == c2) {
8906        return c1;             // yes!
8907      }
8908      return 0;
8909    }
8910
8911    default:
8912      if (p->c > 0) {
8913        return p->c;             // yes!
8914      }
8915      return 0;
8916    }
8917  }
8918  return 0;
8919}
8920
8921// Figure out if the NFA state list contains just literal text and nothing
8922// else.  If so return a string in allocated memory with what must match after
8923// regstart.  Otherwise return NULL.
8924static uint8_t *nfa_get_match_text(nfa_state_T *start)
8925{
8926  nfa_state_T *p = start;
8927  int len = 0;
8928  uint8_t *ret;
8929  uint8_t *s;
8930
8931  if (p->c != NFA_MOPEN) {
8932    return NULL;     // just in case
8933  }
8934  p = p->out;
8935  while (p->c > 0) {
8936    len += utf_char2len(p->c);
8937    p = p->out;
8938  }
8939  if (p->c != NFA_MCLOSE || p->out->c != NFA_MATCH) {
8940    return NULL;
8941  }
8942
8943  ret = xmalloc((size_t)len);
8944  p = start->out->out;     // skip first char, it goes into regstart
8945  s = ret;
8946  while (p->c > 0) {
8947    s += utf_char2bytes(p->c, (char *)s);
8948    p = p->out;
8949  }
8950  *s = NUL;
8951
8952  return ret;
8953}
8954
8955// Allocate more space for post_start.  Called when
8956// running above the estimated number of states.
8957static void realloc_post_list(void)
8958{
8959  // For weird patterns the number of states can be very high. Increasing by
8960  // 50% seems a reasonable compromise between memory use and speed.
8961  const size_t new_max = (size_t)(post_end - post_start) * 3 / 2;
8962  int *new_start = xrealloc(post_start, new_max * sizeof(int));
8963  post_ptr = new_start + (post_ptr - post_start);
8964  post_end = new_start + new_max;
8965  post_start = new_start;
8966  post_start_len = new_max;
8967}
8968
8969// Search between "start" and "end" and try to recognize a
8970// character class in expanded form. For example [0-9].
8971// On success, return the id the character class to be emitted.
8972// On failure, return 0 (=FAIL)
8973// Start points to the first char of the range, while end should point
8974// to the closing brace.
8975// Keep in mind that 'ignorecase' applies at execution time, thus [a-z] may
8976// need to be interpreted as [a-zA-Z].
8977static int nfa_recognize_char_class(uint8_t *start, const uint8_t *end, int extra_newl)
8978{
8979  bool newl;
8980  int config = get_char_class_bits(start, end, &newl);
8981
8982  if (config < 0) {
8983    return FAIL;
8984  }
8985
8986  if (extra_newl == true) {
8987    newl = true;
8988  }
8989
8990  if (newl == true) {
8991    extra_newl = NFA_ADD_NL;
8992  }
8993
8994  switch (config) {
8995  case CLASS_o9:
8996    return extra_newl + NFA_DIGIT;
8997  case CLASS_not |  CLASS_o9:
8998    return extra_newl + NFA_NDIGIT;
8999  case CLASS_af | CLASS_AF | CLASS_o9:
9000    return extra_newl + NFA_HEX;
9001  case CLASS_not | CLASS_af | CLASS_AF | CLASS_o9:
9002    return extra_newl + NFA_NHEX;
9003  case CLASS_o7:
9004    return extra_newl + NFA_OCTAL;
9005  case CLASS_not | CLASS_o7:
9006    return extra_newl + NFA_NOCTAL;
9007  case CLASS_az | CLASS_AZ | CLASS_o9 | CLASS_underscore:
9008    return extra_newl + NFA_WORD;
9009  case CLASS_not | CLASS_az | CLASS_AZ | CLASS_o9 | CLASS_underscore:
9010    return extra_newl + NFA_NWORD;
9011  case CLASS_az | CLASS_AZ | CLASS_underscore:
9012    return extra_newl + NFA_HEAD;
9013  case CLASS_not | CLASS_az | CLASS_AZ | CLASS_underscore:
9014    return extra_newl + NFA_NHEAD;
9015  case CLASS_az | CLASS_AZ:
9016    return extra_newl + NFA_ALPHA;
9017  case CLASS_not | CLASS_az | CLASS_AZ:
9018    return extra_newl + NFA_NALPHA;
9019  case CLASS_az:
9020    return extra_newl + NFA_LOWER_IC;
9021  case CLASS_not | CLASS_az:
9022    return extra_newl + NFA_NLOWER_IC;
9023  case CLASS_AZ:
9024    return extra_newl + NFA_UPPER_IC;
9025  case CLASS_not | CLASS_AZ:
9026    return extra_newl + NFA_NUPPER_IC;
9027  }
9028  return FAIL;
9029}
9030
9031// Produce the bytes for equivalence class "c".
9032// Currently only handles latin1, latin9 and utf-8.
9033// Emits bytes in postfix notation: 'a,b,NFA_OR,c,NFA_OR' is
9034// equivalent to 'a OR b OR c'
9035//
9036// NOTE! When changing this function, also update reg_equi_class()
9037static void nfa_emit_equi_class(int c)
9038{
9039#define EMIT2(c)   EMIT(c); EMIT(NFA_CONCAT);
9040
9041  {
9042#define A_grave 0xc0
9043#define A_acute 0xc1
9044#define A_circumflex 0xc2
9045#define A_virguilla 0xc3
9046#define A_diaeresis 0xc4
9047#define A_ring 0xc5
9048#define C_cedilla 0xc7
9049#define E_grave 0xc8
9050#define E_acute 0xc9
9051#define E_circumflex 0xca
9052#define E_diaeresis 0xcb
9053#define I_grave 0xcc
9054#define I_acute 0xcd
9055#define I_circumflex 0xce
9056#define I_diaeresis 0xcf
9057#define N_virguilla 0xd1
9058#define O_grave 0xd2
9059#define O_acute 0xd3
9060#define O_circumflex 0xd4
9061#define O_virguilla 0xd5
9062#define O_diaeresis 0xd6
9063#define O_slash 0xd8
9064#define U_grave 0xd9
9065#define U_acute 0xda
9066#define U_circumflex 0xdb
9067#define U_diaeresis 0xdc
9068#define Y_acute 0xdd
9069#define a_grave 0xe0
9070#define a_acute 0xe1
9071#define a_circumflex 0xe2
9072#define a_virguilla 0xe3
9073#define a_diaeresis 0xe4
9074#define a_ring 0xe5
9075#define c_cedilla 0xe7
9076#define e_grave 0xe8
9077#define e_acute 0xe9
9078#define e_circumflex 0xea
9079#define e_diaeresis 0xeb
9080#define i_grave 0xec
9081#define i_acute 0xed
9082#define i_circumflex 0xee
9083#define i_diaeresis 0xef
9084#define n_virguilla 0xf1
9085#define o_grave 0xf2
9086#define o_acute 0xf3
9087#define o_circumflex 0xf4
9088#define o_virguilla 0xf5
9089#define o_diaeresis 0xf6
9090#define o_slash 0xf8
9091#define u_grave 0xf9
9092#define u_acute 0xfa
9093#define u_circumflex 0xfb
9094#define u_diaeresis 0xfc
9095#define y_acute 0xfd
9096#define y_diaeresis 0xff
9097    switch (c) {
9098    case 'A':
9099    case A_grave:
9100    case A_acute:
9101    case A_circumflex:
9102    case A_virguilla:
9103    case A_diaeresis:
9104    case A_ring:
9105    case 0x100:
9106    case 0x102:
9107    case 0x104:
9108    case 0x1cd:
9109    case 0x1de:
9110    case 0x1e0:
9111    case 0x1fa:
9112    case 0x200:
9113    case 0x202:
9114    case 0x226:
9115    case 0x23a:
9116    case 0x1e00:
9117    case 0x1ea0:
9118    case 0x1ea2:
9119    case 0x1ea4:
9120    case 0x1ea6:
9121    case 0x1ea8:
9122    case 0x1eaa:
9123    case 0x1eac:
9124    case 0x1eae:
9125    case 0x1eb0:
9126    case 0x1eb2:
9127    case 0x1eb4:
9128    case 0x1eb6:
9129      EMIT2('A') EMIT2(A_grave) EMIT2(A_acute)
9130      EMIT2(A_circumflex) EMIT2(A_virguilla)
9131      EMIT2(A_diaeresis) EMIT2(A_ring)
9132      EMIT2(0x100) EMIT2(0x102) EMIT2(0x104)
9133      EMIT2(0x1cd) EMIT2(0x1de) EMIT2(0x1e0)
9134      EMIT2(0x1fa) EMIT2(0x200) EMIT2(0x202)
9135      EMIT2(0x226) EMIT2(0x23a) EMIT2(0x1e00)
9136      EMIT2(0x1ea0) EMIT2(0x1ea2) EMIT2(0x1ea4)
9137      EMIT2(0x1ea6) EMIT2(0x1ea8) EMIT2(0x1eaa)
9138      EMIT2(0x1eac) EMIT2(0x1eae) EMIT2(0x1eb0)
9139      EMIT2(0x1eb2) EMIT2(0x1eb6) EMIT2(0x1eb4)
9140      return;
9141
9142    case 'B':
9143    case 0x181:
9144    case 0x243:
9145    case 0x1e02:
9146    case 0x1e04:
9147    case 0x1e06:
9148      EMIT2('B')
9149      EMIT2(0x181) EMIT2(0x243) EMIT2(0x1e02)
9150      EMIT2(0x1e04) EMIT2(0x1e06)
9151      return;
9152
9153    case 'C':
9154    case C_cedilla:
9155    case 0x106:
9156    case 0x108:
9157    case 0x10a:
9158    case 0x10c:
9159    case 0x187:
9160    case 0x23b:
9161    case 0x1e08:
9162    case 0xa792:
9163      EMIT2('C') EMIT2(C_cedilla)
9164      EMIT2(0x106) EMIT2(0x108) EMIT2(0x10a)
9165      EMIT2(0x10c) EMIT2(0x187) EMIT2(0x23b)
9166      EMIT2(0x1e08) EMIT2(0xa792)
9167      return;
9168
9169    case 'D':
9170    case 0x10e:
9171    case 0x110:
9172    case 0x18a:
9173    case 0x1e0a:
9174    case 0x1e0c:
9175    case 0x1e0e:
9176    case 0x1e10:
9177    case 0x1e12:
9178      EMIT2('D') EMIT2(0x10e) EMIT2(0x110) EMIT2(0x18a)
9179      EMIT2(0x1e0a) EMIT2(0x1e0c) EMIT2(0x1e0e)
9180      EMIT2(0x1e10) EMIT2(0x1e12)
9181      return;
9182
9183    case 'E':
9184    case E_grave:
9185    case E_acute:
9186    case E_circumflex:
9187    case E_diaeresis:
9188    case 0x112:
9189    case 0x114:
9190    case 0x116:
9191    case 0x118:
9192    case 0x11a:
9193    case 0x204:
9194    case 0x206:
9195    case 0x228:
9196    case 0x246:
9197    case 0x1e14:
9198    case 0x1e16:
9199    case 0x1e18:
9200    case 0x1e1a:
9201    case 0x1e1c:
9202    case 0x1eb8:
9203    case 0x1eba:
9204    case 0x1ebc:
9205    case 0x1ebe:
9206    case 0x1ec0:
9207    case 0x1ec2:
9208    case 0x1ec4:
9209    case 0x1ec6:
9210      EMIT2('E') EMIT2(E_grave) EMIT2(E_acute)
9211      EMIT2(E_circumflex) EMIT2(E_diaeresis)
9212      EMIT2(0x112) EMIT2(0x114) EMIT2(0x116)
9213      EMIT2(0x118) EMIT2(0x11a) EMIT2(0x204)
9214      EMIT2(0x206) EMIT2(0x228) EMIT2(0x246)
9215      EMIT2(0x1e14) EMIT2(0x1e16) EMIT2(0x1e18)
9216      EMIT2(0x1e1a) EMIT2(0x1e1c) EMIT2(0x1eb8)
9217      EMIT2(0x1eba) EMIT2(0x1ebc) EMIT2(0x1ebe)
9218      EMIT2(0x1ec0) EMIT2(0x1ec2) EMIT2(0x1ec4)
9219      EMIT2(0x1ec6)
9220      return;
9221
9222    case 'F':
9223    case 0x191:
9224    case 0x1e1e:
9225    case 0xa798:
9226      EMIT2('F') EMIT2(0x191) EMIT2(0x1e1e) EMIT2(0xa798)
9227      return;
9228
9229    case 'G':
9230    case 0x11c:
9231    case 0x11e:
9232    case 0x120:
9233    case 0x122:
9234    case 0x193:
9235    case 0x1e4:
9236    case 0x1e6:
9237    case 0x1f4:
9238    case 0x1e20:
9239    case 0xa7a0:
9240      EMIT2('G') EMIT2(0x11c) EMIT2(0x11e) EMIT2(0x120)
9241      EMIT2(0x122) EMIT2(0x193) EMIT2(0x1e4)
9242      EMIT2(0x1e6) EMIT2(0x1f4) EMIT2(0x1e20)
9243      EMIT2(0xa7a0)
9244      return;
9245
9246    case 'H':
9247    case 0x124:
9248    case 0x126:
9249    case 0x21e:
9250    case 0x1e22:
9251    case 0x1e24:
9252    case 0x1e26:
9253    case 0x1e28:
9254    case 0x1e2a:
9255    case 0x2c67:
9256      EMIT2('H') EMIT2(0x124) EMIT2(0x126) EMIT2(0x21e)
9257      EMIT2(0x1e22) EMIT2(0x1e24) EMIT2(0x1e26)
9258      EMIT2(0x1e28) EMIT2(0x1e2a) EMIT2(0x2c67)
9259      return;
9260
9261    case 'I':
9262    case I_grave:
9263    case I_acute:
9264    case I_circumflex:
9265    case I_diaeresis:
9266    case 0x128:
9267    case 0x12a:
9268    case 0x12c:
9269    case 0x12e:
9270    case 0x130:
9271    case 0x197:
9272    case 0x1cf:
9273    case 0x208:
9274    case 0x20a:
9275    case 0x1e2c:
9276    case 0x1e2e:
9277    case 0x1ec8:
9278    case 0x1eca:
9279      EMIT2('I') EMIT2(I_grave) EMIT2(I_acute)
9280      EMIT2(I_circumflex) EMIT2(I_diaeresis)
9281      EMIT2(0x128) EMIT2(0x12a) EMIT2(0x12c)
9282      EMIT2(0x12e) EMIT2(0x130) EMIT2(0x197)
9283      EMIT2(0x1cf) EMIT2(0x208) EMIT2(0x20a)
9284      EMIT2(0x1e2c) EMIT2(0x1e2e) EMIT2(0x1ec8)
9285      EMIT2(0x1eca)
9286      return;
9287
9288    case 'J':
9289    case 0x134:
9290    case 0x248:
9291      EMIT2('J') EMIT2(0x134) EMIT2(0x248)
9292      return;
9293
9294    case 'K':
9295    case 0x136:
9296    case 0x198:
9297    case 0x1e8:
9298    case 0x1e30:
9299    case 0x1e32:
9300    case 0x1e34:
9301    case 0x2c69:
9302    case 0xa740:
9303      EMIT2('K') EMIT2(0x136) EMIT2(0x198) EMIT2(0x1e8)
9304      EMIT2(0x1e30) EMIT2(0x1e32) EMIT2(0x1e34)
9305      EMIT2(0x2c69) EMIT2(0xa740)
9306      return;
9307
9308    case 'L':
9309    case 0x139:
9310    case 0x13b:
9311    case 0x13d:
9312    case 0x13f:
9313    case 0x141:
9314    case 0x23d:
9315    case 0x1e36:
9316    case 0x1e38:
9317    case 0x1e3a:
9318    case 0x1e3c:
9319    case 0x2c60:
9320      EMIT2('L') EMIT2(0x139) EMIT2(0x13b)
9321      EMIT2(0x13d) EMIT2(0x13f) EMIT2(0x141)
9322      EMIT2(0x23d) EMIT2(0x1e36) EMIT2(0x1e38)
9323      EMIT2(0x1e3a) EMIT2(0x1e3c) EMIT2(0x2c60)
9324      return;
9325
9326    case 'M':
9327    case 0x1e3e:
9328    case 0x1e40:
9329    case 0x1e42:
9330      EMIT2('M') EMIT2(0x1e3e) EMIT2(0x1e40)
9331      EMIT2(0x1e42)
9332      return;
9333
9334    case 'N':
9335    case N_virguilla:
9336    case 0x143:
9337    case 0x145:
9338    case 0x147:
9339    case 0x1f8:
9340    case 0x1e44:
9341    case 0x1e46:
9342    case 0x1e48:
9343    case 0x1e4a:
9344    case 0xa7a4:
9345      EMIT2('N') EMIT2(N_virguilla)
9346      EMIT2(0x143) EMIT2(0x145) EMIT2(0x147)
9347      EMIT2(0x1f8) EMIT2(0x1e44) EMIT2(0x1e46)
9348      EMIT2(0x1e48) EMIT2(0x1e4a) EMIT2(0xa7a4)
9349      return;
9350
9351    case 'O':
9352    case O_grave:
9353    case O_acute:
9354    case O_circumflex:
9355    case O_virguilla:
9356    case O_diaeresis:
9357    case O_slash:
9358    case 0x14c:
9359    case 0x14e:
9360    case 0x150:
9361    case 0x19f:
9362    case 0x1a0:
9363    case 0x1d1:
9364    case 0x1ea:
9365    case 0x1ec:
9366    case 0x1fe:
9367    case 0x20c:
9368    case 0x20e:
9369    case 0x22a:
9370    case 0x22c:
9371    case 0x22e:
9372    case 0x230:
9373    case 0x1e4c:
9374    case 0x1e4e:
9375    case 0x1e50:
9376    case 0x1e52:
9377    case 0x1ecc:
9378    case 0x1ece:
9379    case 0x1ed0:
9380    case 0x1ed2:
9381    case 0x1ed4:
9382    case 0x1ed6:
9383    case 0x1ed8:
9384    case 0x1eda:
9385    case 0x1edc:
9386    case 0x1ede:
9387    case 0x1ee0:
9388    case 0x1ee2:
9389      EMIT2('O') EMIT2(O_grave) EMIT2(O_acute)
9390      EMIT2(O_circumflex) EMIT2(O_virguilla)
9391      EMIT2(O_diaeresis) EMIT2(O_slash)
9392      EMIT2(0x14c) EMIT2(0x14e) EMIT2(0x150)
9393      EMIT2(0x19f) EMIT2(0x1a0) EMIT2(0x1d1)
9394      EMIT2(0x1ea) EMIT2(0x1ec) EMIT2(0x1fe)
9395      EMIT2(0x20c) EMIT2(0x20e) EMIT2(0x22a)
9396      EMIT2(0x22c) EMIT2(0x22e) EMIT2(0x230)
9397      EMIT2(0x1e4c) EMIT2(0x1e4e) EMIT2(0x1e50)
9398      EMIT2(0x1e52) EMIT2(0x1ecc) EMIT2(0x1ece)
9399      EMIT2(0x1ed0) EMIT2(0x1ed2) EMIT2(0x1ed4)
9400      EMIT2(0x1ed6) EMIT2(0x1ed8) EMIT2(0x1eda)
9401      EMIT2(0x1edc) EMIT2(0x1ede) EMIT2(0x1ee0)
9402      EMIT2(0x1ee2)
9403      return;
9404
9405    case 'P':
9406    case 0x1a4:
9407    case 0x1e54:
9408    case 0x1e56:
9409    case 0x2c63:
9410      EMIT2('P') EMIT2(0x1a4) EMIT2(0x1e54) EMIT2(0x1e56)
9411      EMIT2(0x2c63)
9412      return;
9413
9414    case 'Q':
9415    case 0x24a:
9416      EMIT2('Q') EMIT2(0x24a)
9417      return;
9418
9419    case 'R':
9420    case 0x154:
9421    case 0x156:
9422    case 0x158:
9423    case 0x210:
9424    case 0x212:
9425    case 0x24c:
9426    case 0x1e58:
9427    case 0x1e5a:
9428    case 0x1e5c:
9429    case 0x1e5e:
9430    case 0x2c64:
9431    case 0xa7a6:
9432      EMIT2('R') EMIT2(0x154) EMIT2(0x156) EMIT2(0x158)
9433      EMIT2(0x210) EMIT2(0x212) EMIT2(0x24c) EMIT2(0x1e58)
9434      EMIT2(0x1e5a) EMIT2(0x1e5c) EMIT2(0x1e5e) EMIT2(0x2c64)
9435      EMIT2(0xa7a6)
9436      return;
9437
9438    case 'S':
9439    case 0x15a:
9440    case 0x15c:
9441    case 0x15e:
9442    case 0x160:
9443    case 0x218:
9444    case 0x1e60:
9445    case 0x1e62:
9446    case 0x1e64:
9447    case 0x1e66:
9448    case 0x1e68:
9449    case 0x2c7e:
9450    case 0xa7a8:
9451      EMIT2('S') EMIT2(0x15a) EMIT2(0x15c) EMIT2(0x15e)
9452      EMIT2(0x160) EMIT2(0x218) EMIT2(0x1e60) EMIT2(0x1e62)
9453      EMIT2(0x1e64) EMIT2(0x1e66) EMIT2(0x1e68) EMIT2(0x2c7e)
9454      EMIT2(0xa7a8)
9455      return;
9456
9457    case 'T':
9458    case 0x162:
9459    case 0x164:
9460    case 0x166:
9461    case 0x1ac:
9462    case 0x1ae:
9463    case 0x21a:
9464    case 0x23e:
9465    case 0x1e6a:
9466    case 0x1e6c:
9467    case 0x1e6e:
9468    case 0x1e70:
9469      EMIT2('T') EMIT2(0x162) EMIT2(0x164) EMIT2(0x166)
9470      EMIT2(0x1ac) EMIT2(0x1ae) EMIT2(0x23e) EMIT2(0x21a)
9471      EMIT2(0x1e6a) EMIT2(0x1e6c) EMIT2(0x1e6e) EMIT2(0x1e70)
9472      return;
9473
9474    case 'U':
9475    case U_grave:
9476    case U_acute:
9477    case U_diaeresis:
9478    case U_circumflex:
9479    case 0x168:
9480    case 0x16a:
9481    case 0x16c:
9482    case 0x16e:
9483    case 0x170:
9484    case 0x172:
9485    case 0x1af:
9486    case 0x1d3:
9487    case 0x1d5:
9488    case 0x1d7:
9489    case 0x1d9:
9490    case 0x1db:
9491    case 0x214:
9492    case 0x216:
9493    case 0x244:
9494    case 0x1e72:
9495    case 0x1e74:
9496    case 0x1e76:
9497    case 0x1e78:
9498    case 0x1e7a:
9499    case 0x1ee4:
9500    case 0x1ee6:
9501    case 0x1ee8:
9502    case 0x1eea:
9503    case 0x1eec:
9504    case 0x1eee:
9505    case 0x1ef0:
9506      EMIT2('U') EMIT2(U_grave) EMIT2(U_acute)
9507      EMIT2(U_diaeresis) EMIT2(U_circumflex)
9508      EMIT2(0x168) EMIT2(0x16a)
9509      EMIT2(0x16c) EMIT2(0x16e) EMIT2(0x170)
9510      EMIT2(0x172) EMIT2(0x1af) EMIT2(0x1d3)
9511      EMIT2(0x1d5) EMIT2(0x1d7) EMIT2(0x1d9)
9512      EMIT2(0x1db) EMIT2(0x214) EMIT2(0x216)
9513      EMIT2(0x244) EMIT2(0x1e72) EMIT2(0x1e74)
9514      EMIT2(0x1e76) EMIT2(0x1e78) EMIT2(0x1e7a)
9515      EMIT2(0x1ee4) EMIT2(0x1ee6) EMIT2(0x1ee8)
9516      EMIT2(0x1eea) EMIT2(0x1eec) EMIT2(0x1eee)
9517      EMIT2(0x1ef0)
9518      return;
9519
9520    case 'V':
9521    case 0x1b2:
9522    case 0x1e7c:
9523    case 0x1e7e:
9524      EMIT2('V') EMIT2(0x1b2) EMIT2(0x1e7c) EMIT2(0x1e7e)
9525      return;
9526
9527    case 'W':
9528    case 0x174:
9529    case 0x1e80:
9530    case 0x1e82:
9531    case 0x1e84:
9532    case 0x1e86:
9533    case 0x1e88:
9534      EMIT2('W') EMIT2(0x174) EMIT2(0x1e80) EMIT2(0x1e82)
9535      EMIT2(0x1e84) EMIT2(0x1e86) EMIT2(0x1e88)
9536      return;
9537
9538    case 'X':
9539    case 0x1e8a:
9540    case 0x1e8c:
9541      EMIT2('X') EMIT2(0x1e8a) EMIT2(0x1e8c)
9542      return;
9543
9544    case 'Y':
9545    case Y_acute:
9546    case 0x176:
9547    case 0x178:
9548    case 0x1b3:
9549    case 0x232:
9550    case 0x24e:
9551    case 0x1e8e:
9552    case 0x1ef2:
9553    case 0x1ef4:
9554    case 0x1ef6:
9555    case 0x1ef8:
9556      EMIT2('Y') EMIT2(Y_acute)
9557      EMIT2(0x176) EMIT2(0x178) EMIT2(0x1b3)
9558      EMIT2(0x232) EMIT2(0x24e) EMIT2(0x1e8e)
9559      EMIT2(0x1ef2) EMIT2(0x1ef4) EMIT2(0x1ef6)
9560      EMIT2(0x1ef8)
9561      return;
9562
9563    case 'Z':
9564    case 0x179:
9565    case 0x17b:
9566    case 0x17d:
9567    case 0x1b5:
9568    case 0x1e90:
9569    case 0x1e92:
9570    case 0x1e94:
9571    case 0x2c6b:
9572      EMIT2('Z') EMIT2(0x179) EMIT2(0x17b) EMIT2(0x17d)
9573      EMIT2(0x1b5) EMIT2(0x1e90) EMIT2(0x1e92)
9574      EMIT2(0x1e94) EMIT2(0x2c6b)
9575      return;
9576
9577    case 'a':
9578    case a_grave:
9579    case a_acute:
9580    case a_circumflex:
9581    case a_virguilla:
9582    case a_diaeresis:
9583    case a_ring:
9584    case 0x101:
9585    case 0x103:
9586    case 0x105:
9587    case 0x1ce:
9588    case 0x1df:
9589    case 0x1e1:
9590    case 0x1fb:
9591    case 0x201:
9592    case 0x203:
9593    case 0x227:
9594    case 0x1d8f:
9595    case 0x1e01:
9596    case 0x1e9a:
9597    case 0x1ea1:
9598    case 0x1ea3:
9599    case 0x1ea5:
9600    case 0x1ea7:
9601    case 0x1ea9:
9602    case 0x1eab:
9603    case 0x1ead:
9604    case 0x1eaf:
9605    case 0x1eb1:
9606    case 0x1eb3:
9607    case 0x1eb5:
9608    case 0x1eb7:
9609    case 0x2c65:
9610      EMIT2('a') EMIT2(a_grave) EMIT2(a_acute)
9611      EMIT2(a_circumflex) EMIT2(a_virguilla)
9612      EMIT2(a_diaeresis) EMIT2(a_ring)
9613      EMIT2(0x101) EMIT2(0x103) EMIT2(0x105)
9614      EMIT2(0x1ce) EMIT2(0x1df) EMIT2(0x1e1)
9615      EMIT2(0x1fb) EMIT2(0x201) EMIT2(0x203)
9616      EMIT2(0x227) EMIT2(0x1d8f) EMIT2(0x1e01)
9617      EMIT2(0x1e9a) EMIT2(0x1ea1) EMIT2(0x1ea3)
9618      EMIT2(0x1ea5) EMIT2(0x1ea7) EMIT2(0x1ea9)
9619      EMIT2(0x1eab) EMIT2(0x1ead) EMIT2(0x1eaf)
9620      EMIT2(0x1eb1) EMIT2(0x1eb3) EMIT2(0x1eb5)
9621      EMIT2(0x1eb7) EMIT2(0x2c65)
9622      return;
9623
9624    case 'b':
9625    case 0x180:
9626    case 0x253:
9627    case 0x1d6c:
9628    case 0x1d80:
9629    case 0x1e03:
9630    case 0x1e05:
9631    case 0x1e07:
9632      EMIT2('b') EMIT2(0x180) EMIT2(0x253) EMIT2(0x1d6c)
9633      EMIT2(0x1d80) EMIT2(0x1e03) EMIT2(0x1e05) EMIT2(0x1e07)
9634      return;
9635
9636    case 'c':
9637    case c_cedilla:
9638    case 0x107:
9639    case 0x109:
9640    case 0x10b:
9641    case 0x10d:
9642    case 0x188:
9643    case 0x23c:
9644    case 0x1e09:
9645    case 0xa793:
9646    case 0xa794:
9647      EMIT2('c') EMIT2(c_cedilla)
9648      EMIT2(0x107) EMIT2(0x109) EMIT2(0x10b)
9649      EMIT2(0x10d) EMIT2(0x188) EMIT2(0x23c)
9650      EMIT2(0x1e09) EMIT2(0xa793) EMIT2(0xa794)
9651      return;
9652
9653    case 'd':
9654    case 0x10f:
9655    case 0x111:
9656    case 0x257:
9657    case 0x1d6d:
9658    case 0x1d81:
9659    case 0x1d91:
9660    case 0x1e0b:
9661    case 0x1e0d:
9662    case 0x1e0f:
9663    case 0x1e11:
9664    case 0x1e13:
9665      EMIT2('d') EMIT2(0x10f) EMIT2(0x111)
9666      EMIT2(0x257) EMIT2(0x1d6d) EMIT2(0x1d81)
9667      EMIT2(0x1d91) EMIT2(0x1e0b) EMIT2(0x1e0d)
9668      EMIT2(0x1e0f) EMIT2(0x1e11) EMIT2(0x1e13)
9669      return;
9670
9671    case 'e':
9672    case e_grave:
9673    case e_acute:
9674    case e_circumflex:
9675    case e_diaeresis:
9676    case 0x113:
9677    case 0x115:
9678    case 0x117:
9679    case 0x119:
9680    case 0x11b:
9681    case 0x205:
9682    case 0x207:
9683    case 0x229:
9684    case 0x247:
9685    case 0x1d92:
9686    case 0x1e15:
9687    case 0x1e17:
9688    case 0x1e19:
9689    case 0x1e1b:
9690    case 0x1e1d:
9691    case 0x1eb9:
9692    case 0x1ebb:
9693    case 0x1ebd:
9694    case 0x1ebf:
9695    case 0x1ec1:
9696    case 0x1ec3:
9697    case 0x1ec5:
9698    case 0x1ec7:
9699      EMIT2('e') EMIT2(e_grave) EMIT2(e_acute)
9700      EMIT2(e_circumflex) EMIT2(e_diaeresis)
9701      EMIT2(0x113) EMIT2(0x115)
9702      EMIT2(0x117) EMIT2(0x119) EMIT2(0x11b)
9703      EMIT2(0x205) EMIT2(0x207) EMIT2(0x229)
9704      EMIT2(0x247) EMIT2(0x1d92) EMIT2(0x1e15)
9705      EMIT2(0x1e17) EMIT2(0x1e19) EMIT2(0x1e1b)
9706      EMIT2(0x1e1d) EMIT2(0x1eb9) EMIT2(0x1ebb)
9707      EMIT2(0x1ebd) EMIT2(0x1ebf) EMIT2(0x1ec1)
9708      EMIT2(0x1ec3) EMIT2(0x1ec5) EMIT2(0x1ec7)
9709      return;
9710
9711    case 'f':
9712    case 0x192:
9713    case 0x1d6e:
9714    case 0x1d82:
9715    case 0x1e1f:
9716    case 0xa799:
9717      EMIT2('f') EMIT2(0x192) EMIT2(0x1d6e) EMIT2(0x1d82)
9718      EMIT2(0x1e1f) EMIT2(0xa799)
9719      return;
9720
9721    case 'g':
9722    case 0x11d:
9723    case 0x11f:
9724    case 0x121:
9725    case 0x123:
9726    case 0x1e5:
9727    case 0x1e7:
9728    case 0x1f5:
9729    case 0x260:
9730    case 0x1d83:
9731    case 0x1e21:
9732    case 0xa7a1:
9733      EMIT2('g') EMIT2(0x11d) EMIT2(0x11f) EMIT2(0x121)
9734      EMIT2(0x123) EMIT2(0x1e5) EMIT2(0x1e7)
9735      EMIT2(0x1f5) EMIT2(0x260) EMIT2(0x1d83)
9736      EMIT2(0x1e21) EMIT2(0xa7a1)
9737      return;
9738
9739    case 'h':
9740    case 0x125:
9741    case 0x127:
9742    case 0x21f:
9743    case 0x1e23:
9744    case 0x1e25:
9745    case 0x1e27:
9746    case 0x1e29:
9747    case 0x1e2b:
9748    case 0x1e96:
9749    case 0x2c68:
9750    case 0xa795:
9751      EMIT2('h') EMIT2(0x125) EMIT2(0x127) EMIT2(0x21f)
9752      EMIT2(0x1e23) EMIT2(0x1e25) EMIT2(0x1e27)
9753      EMIT2(0x1e29) EMIT2(0x1e2b) EMIT2(0x1e96)
9754      EMIT2(0x2c68) EMIT2(0xa795)
9755      return;
9756
9757    case 'i':
9758    case i_grave:
9759    case i_acute:
9760    case i_circumflex:
9761    case i_diaeresis:
9762    case 0x129:
9763    case 0x12b:
9764    case 0x12d:
9765    case 0x12f:
9766    case 0x1d0:
9767    case 0x209:
9768    case 0x20b:
9769    case 0x268:
9770    case 0x1d96:
9771    case 0x1e2d:
9772    case 0x1e2f:
9773    case 0x1ec9:
9774    case 0x1ecb:
9775      EMIT2('i') EMIT2(i_grave) EMIT2(i_acute)
9776      EMIT2(i_circumflex) EMIT2(i_diaeresis)
9777      EMIT2(0x129) EMIT2(0x12b) EMIT2(0x12d)
9778      EMIT2(0x12f) EMIT2(0x1d0) EMIT2(0x209)
9779      EMIT2(0x20b) EMIT2(0x268) EMIT2(0x1d96)
9780      EMIT2(0x1e2d) EMIT2(0x1e2f) EMIT2(0x1ec9)
9781      EMIT2(0x1ecb)
9782      return;
9783
9784    case 'j':
9785    case 0x135:
9786    case 0x1f0:
9787    case 0x249:
9788      EMIT2('j') EMIT2(0x135) EMIT2(0x1f0) EMIT2(0x249)
9789      return;
9790
9791    case 'k':
9792    case 0x137:
9793    case 0x199:
9794    case 0x1e9:
9795    case 0x1d84:
9796    case 0x1e31:
9797    case 0x1e33:
9798    case 0x1e35:
9799    case 0x2c6a:
9800    case 0xa741:
9801      EMIT2('k') EMIT2(0x137) EMIT2(0x199) EMIT2(0x1e9)
9802      EMIT2(0x1d84) EMIT2(0x1e31) EMIT2(0x1e33)
9803      EMIT2(0x1e35) EMIT2(0x2c6a) EMIT2(0xa741)
9804      return;
9805
9806    case 'l':
9807    case 0x13a:
9808    case 0x13c:
9809    case 0x13e:
9810    case 0x140:
9811    case 0x142:
9812    case 0x19a:
9813    case 0x1e37:
9814    case 0x1e39:
9815    case 0x1e3b:
9816    case 0x1e3d:
9817    case 0x2c61:
9818      EMIT2('l') EMIT2(0x13a) EMIT2(0x13c)
9819      EMIT2(0x13e) EMIT2(0x140) EMIT2(0x142)
9820      EMIT2(0x19a) EMIT2(0x1e37) EMIT2(0x1e39)
9821      EMIT2(0x1e3b) EMIT2(0x1e3d) EMIT2(0x2c61)
9822      return;
9823
9824    case 'm':
9825    case 0x1d6f:
9826    case 0x1e3f:
9827    case 0x1e41:
9828    case 0x1e43:
9829      EMIT2('m') EMIT2(0x1d6f) EMIT2(0x1e3f)
9830      EMIT2(0x1e41) EMIT2(0x1e43)
9831      return;
9832
9833    case 'n':
9834    case n_virguilla:
9835    case 0x144:
9836    case 0x146:
9837    case 0x148:
9838    case 0x149:
9839    case 0x1f9:
9840    case 0x1d70:
9841    case 0x1d87:
9842    case 0x1e45:
9843    case 0x1e47:
9844    case 0x1e49:
9845    case 0x1e4b:
9846    case 0xa7a5:
9847      EMIT2('n') EMIT2(n_virguilla)
9848      EMIT2(0x144) EMIT2(0x146) EMIT2(0x148)
9849      EMIT2(0x149) EMIT2(0x1f9) EMIT2(0x1d70)
9850      EMIT2(0x1d87) EMIT2(0x1e45) EMIT2(0x1e47)
9851      EMIT2(0x1e49) EMIT2(0x1e4b) EMIT2(0xa7a5)
9852      return;
9853
9854    case 'o':
9855    case o_grave:
9856    case o_acute:
9857    case o_circumflex:
9858    case o_virguilla:
9859    case o_diaeresis:
9860    case o_slash:
9861    case 0x14d:
9862    case 0x14f:
9863    case 0x151:
9864    case 0x1a1:
9865    case 0x1d2:
9866    case 0x1eb:
9867    case 0x1ed:
9868    case 0x1ff:
9869    case 0x20d:
9870    case 0x20f:
9871    case 0x22b:
9872    case 0x22d:
9873    case 0x22f:
9874    case 0x231:
9875    case 0x275:
9876    case 0x1e4d:
9877    case 0x1e4f:
9878    case 0x1e51:
9879    case 0x1e53:
9880    case 0x1ecd:
9881    case 0x1ecf:
9882    case 0x1ed1:
9883    case 0x1ed3:
9884    case 0x1ed5:
9885    case 0x1ed7:
9886    case 0x1ed9:
9887    case 0x1edb:
9888    case 0x1edd:
9889    case 0x1edf:
9890    case 0x1ee1:
9891    case 0x1ee3:
9892      EMIT2('o') EMIT2(o_grave) EMIT2(o_acute)
9893      EMIT2(o_circumflex) EMIT2(o_virguilla)
9894      EMIT2(o_diaeresis) EMIT2(o_slash)
9895      EMIT2(0x14d) EMIT2(0x14f) EMIT2(0x151)
9896      EMIT2(0x1a1) EMIT2(0x1d2) EMIT2(0x1eb)
9897      EMIT2(0x1ed) EMIT2(0x1ff) EMIT2(0x20d)
9898      EMIT2(0x20f) EMIT2(0x22b) EMIT2(0x22d)
9899      EMIT2(0x22f) EMIT2(0x231) EMIT2(0x275)
9900      EMIT2(0x1e4d) EMIT2(0x1e4f) EMIT2(0x1e51)
9901      EMIT2(0x1e53) EMIT2(0x1ecd) EMIT2(0x1ecf)
9902      EMIT2(0x1ed1) EMIT2(0x1ed3) EMIT2(0x1ed5)
9903      EMIT2(0x1ed7) EMIT2(0x1ed9) EMIT2(0x1edb)
9904      EMIT2(0x1edd) EMIT2(0x1edf) EMIT2(0x1ee1)
9905      EMIT2(0x1ee3)
9906      return;
9907
9908    case 'p':
9909    case 0x1a5:
9910    case 0x1d71:
9911    case 0x1d7d:
9912    case 0x1d88:
9913    case 0x1e55:
9914    case 0x1e57:
9915      EMIT2('p') EMIT2(0x1a5) EMIT2(0x1d71) EMIT2(0x1d7d)
9916      EMIT2(0x1d88) EMIT2(0x1e55) EMIT2(0x1e57)
9917      return;
9918
9919    case 'q':
9920    case 0x24b:
9921    case 0x2a0:
9922      EMIT2('q') EMIT2(0x24b) EMIT2(0x2a0)
9923      return;
9924
9925    case 'r':
9926    case 0x155:
9927    case 0x157:
9928    case 0x159:
9929    case 0x211:
9930    case 0x213:
9931    case 0x24d:
9932    case 0x27d:
9933    case 0x1d72:
9934    case 0x1d73:
9935    case 0x1d89:
9936    case 0x1e59:
9937    case 0x1e5b:
9938    case 0x1e5d:
9939    case 0x1e5f:
9940    case 0xa7a7:
9941      EMIT2('r') EMIT2(0x155) EMIT2(0x157) EMIT2(0x159)
9942      EMIT2(0x211) EMIT2(0x213) EMIT2(0x24d) EMIT2(0x27d)
9943      EMIT2(0x1d72) EMIT2(0x1d73) EMIT2(0x1d89) EMIT2(0x1e59)
9944      EMIT2(0x1e5b) EMIT2(0x1e5d) EMIT2(0x1e5f) EMIT2(0xa7a7)
9945      return;
9946
9947    case 's':
9948    case 0x15b:
9949    case 0x15d:
9950    case 0x15f:
9951    case 0x161:
9952    case 0x219:
9953    case 0x23f:
9954    case 0x1d74:
9955    case 0x1d8a:
9956    case 0x1e61:
9957    case 0x1e63:
9958    case 0x1e65:
9959    case 0x1e67:
9960    case 0x1e69:
9961    case 0xa7a9:
9962      EMIT2('s') EMIT2(0x15b) EMIT2(0x15d) EMIT2(0x15f)
9963      EMIT2(0x161) EMIT2(0x219) EMIT2(0x23f) EMIT2(0x1d74)
9964      EMIT2(0x1d8a) EMIT2(0x1e61) EMIT2(0x1e63) EMIT2(0x1e65)
9965      EMIT2(0x1e67) EMIT2(0x1e69) EMIT2(0xa7a9)
9966      return;
9967
9968    case 't':
9969    case 0x163:
9970    case 0x165:
9971    case 0x167:
9972    case 0x1ab:
9973    case 0x1ad:
9974    case 0x21b:
9975    case 0x288:
9976    case 0x1d75:
9977    case 0x1e6b:
9978    case 0x1e6d:
9979    case 0x1e6f:
9980    case 0x1e71:
9981    case 0x1e97:
9982    case 0x2c66:
9983      EMIT2('t') EMIT2(0x163) EMIT2(0x165) EMIT2(0x167)
9984      EMIT2(0x1ab) EMIT2(0x1ad) EMIT2(0x21b) EMIT2(0x288)
9985      EMIT2(0x1d75) EMIT2(0x1e6b) EMIT2(0x1e6d) EMIT2(0x1e6f)
9986      EMIT2(0x1e71) EMIT2(0x1e97) EMIT2(0x2c66)
9987      return;
9988
9989    case 'u':
9990    case u_grave:
9991    case u_acute:
9992    case u_circumflex:
9993    case u_diaeresis:
9994    case 0x169:
9995    case 0x16b:
9996    case 0x16d:
9997    case 0x16f:
9998    case 0x171:
9999    case 0x173:
10000    case 0x1b0:
10001    case 0x1d4:
10002    case 0x1d6:
10003    case 0x1d8:
10004    case 0x1da:
10005    case 0x1dc:
10006    case 0x215:
10007    case 0x217:
10008    case 0x289:
10009    case 0x1d7e:
10010    case 0x1d99:
10011    case 0x1e73:
10012    case 0x1e75:
10013    case 0x1e77:
10014    case 0x1e79:
10015    case 0x1e7b:
10016    case 0x1ee5:
10017    case 0x1ee7:
10018    case 0x1ee9:
10019    case 0x1eeb:
10020    case 0x1eed:
10021    case 0x1eef:
10022    case 0x1ef1:
10023      EMIT2('u') EMIT2(u_grave) EMIT2(u_acute)
10024      EMIT2(u_circumflex) EMIT2(u_diaeresis)
10025      EMIT2(0x169) EMIT2(0x16b)
10026      EMIT2(0x16d) EMIT2(0x16f) EMIT2(0x171)
10027      EMIT2(0x173) EMIT2(0x1d6) EMIT2(0x1d8)
10028      EMIT2(0x215) EMIT2(0x217) EMIT2(0x1b0)
10029      EMIT2(0x1d4) EMIT2(0x1da) EMIT2(0x1dc)
10030      EMIT2(0x289) EMIT2(0x1e73) EMIT2(0x1d7e)
10031      EMIT2(0x1d99) EMIT2(0x1e75) EMIT2(0x1e77)
10032      EMIT2(0x1e79) EMIT2(0x1e7b) EMIT2(0x1ee5)
10033      EMIT2(0x1ee7) EMIT2(0x1ee9) EMIT2(0x1eeb)
10034      EMIT2(0x1eed) EMIT2(0x1eef) EMIT2(0x1ef1)
10035      return;
10036
10037    case 'v':
10038    case 0x28b:
10039    case 0x1d8c:
10040    case 0x1e7d:
10041    case 0x1e7f:
10042      EMIT2('v') EMIT2(0x28b) EMIT2(0x1d8c) EMIT2(0x1e7d)
10043      EMIT2(0x1e7f)
10044      return;
10045
10046    case 'w':
10047    case 0x175:
10048    case 0x1e81:
10049    case 0x1e83:
10050    case 0x1e85:
10051    case 0x1e87:
10052    case 0x1e89:
10053    case 0x1e98:
10054      EMIT2('w') EMIT2(0x175) EMIT2(0x1e81) EMIT2(0x1e83)
10055      EMIT2(0x1e85) EMIT2(0x1e87) EMIT2(0x1e89) EMIT2(0x1e98)
10056      return;
10057
10058    case 'x':
10059    case 0x1e8b:
10060    case 0x1e8d:
10061      EMIT2('x') EMIT2(0x1e8b) EMIT2(0x1e8d)
10062      return;
10063
10064    case 'y':
10065    case y_acute:
10066    case y_diaeresis:
10067    case 0x177:
10068    case 0x1b4:
10069    case 0x233:
10070    case 0x24f:
10071    case 0x1e8f:
10072    case 0x1e99:
10073    case 0x1ef3:
10074    case 0x1ef5:
10075    case 0x1ef7:
10076    case 0x1ef9:
10077      EMIT2('y') EMIT2(y_acute) EMIT2(y_diaeresis)
10078      EMIT2(0x177) EMIT2(0x1b4) EMIT2(0x233) EMIT2(0x24f)
10079      EMIT2(0x1e8f) EMIT2(0x1e99) EMIT2(0x1ef3)
10080      EMIT2(0x1ef5) EMIT2(0x1ef7) EMIT2(0x1ef9)
10081      return;
10082
10083    case 'z':
10084    case 0x17a:
10085    case 0x17c:
10086    case 0x17e:
10087    case 0x1b6:
10088    case 0x1d76:
10089    case 0x1d8e:
10090    case 0x1e91:
10091    case 0x1e93:
10092    case 0x1e95:
10093    case 0x2c6c:
10094      EMIT2('z') EMIT2(0x17a) EMIT2(0x17c) EMIT2(0x17e)
10095      EMIT2(0x1b6) EMIT2(0x1d76) EMIT2(0x1d8e) EMIT2(0x1e91)
10096      EMIT2(0x1e93) EMIT2(0x1e95) EMIT2(0x2c6c)
10097      return;
10098
10099      // default: character itself
10100    }
10101  }
10102
10103  EMIT2(c);
10104#undef EMIT2
10105}
10106
10107// Code to parse regular expression.
10108//
10109// We try to reuse parsing functions in regexp.c to
10110// minimize surprise and keep the syntax consistent.
10111
10112// Parse the lowest level.
10113//
10114// An atom can be one of a long list of items.  Many atoms match one character
10115// in the text.  It is often an ordinary character or a character class.
10116// Braces can be used to make a pattern into an atom.  The "\z(\)" construct
10117// is only for syntax highlighting.
10118//
10119// atom    ::=     ordinary-atom
10120//     or  \( pattern \)
10121//     or  \%( pattern \)
10122//     or  \z( pattern \)
10123static int nfa_regatom(void)
10124{
10125  int c;
10126  int charclass;
10127  int equiclass;
10128  int collclass;
10129  int got_coll_char;
10130  uint8_t *p;
10131  uint8_t *endp;
10132  uint8_t *old_regparse = (uint8_t *)regparse;
10133  int extra = 0;
10134  int emit_range;
10135  int negated;
10136  int startc = -1;
10137  int save_prev_at_start = prev_at_start;
10138
10139  c = getchr();
10140  switch (c) {
10141  case NUL:
10142    EMSG_RET_FAIL(_(e_nul_found));
10143
10144  case Magic('^'):
10145    EMIT(NFA_BOL);
10146    break;
10147
10148  case Magic('$'):
10149    EMIT(NFA_EOL);
10150    had_eol = true;
10151    break;
10152
10153  case Magic('<'):
10154    EMIT(NFA_BOW);
10155    break;
10156
10157  case Magic('>'):
10158    EMIT(NFA_EOW);
10159    break;
10160
10161  case Magic('_'):
10162    c = no_Magic(getchr());
10163    if (c == NUL) {
10164      EMSG_RET_FAIL(_(e_nul_found));
10165    }
10166
10167    if (c == '^') {             // "\_^" is start-of-line
10168      EMIT(NFA_BOL);
10169      break;
10170    }
10171    if (c == '$') {             // "\_$" is end-of-line
10172      EMIT(NFA_EOL);
10173      had_eol = true;
10174      break;
10175    }
10176
10177    extra = NFA_ADD_NL;
10178
10179    // "\_[" is collection plus newline
10180    if (c == '[') {
10181      goto collection;
10182    }
10183
10184    // "\_x" is character class plus newline
10185    FALLTHROUGH;
10186
10187  // Character classes.
10188  case Magic('.'):
10189  case Magic('i'):
10190  case Magic('I'):
10191  case Magic('k'):
10192  case Magic('K'):
10193  case Magic('f'):
10194  case Magic('F'):
10195  case Magic('p'):
10196  case Magic('P'):
10197  case Magic('s'):
10198  case Magic('S'):
10199  case Magic('d'):
10200  case Magic('D'):
10201  case Magic('x'):
10202  case Magic('X'):
10203  case Magic('o'):
10204  case Magic('O'):
10205  case Magic('w'):
10206  case Magic('W'):
10207  case Magic('h'):
10208  case Magic('H'):
10209  case Magic('a'):
10210  case Magic('A'):
10211  case Magic('l'):
10212  case Magic('L'):
10213  case Magic('u'):
10214  case Magic('U'):
10215    p = (uint8_t *)vim_strchr((char *)classchars, no_Magic(c));
10216    if (p == NULL) {
10217      if (extra == NFA_ADD_NL) {
10218        semsg(_(e_ill_char_class), (int64_t)c);
10219        rc_did_emsg = true;
10220        return FAIL;
10221      }
10222      siemsg("INTERNAL: Unknown character class char: %d", c);
10223      return FAIL;
10224    }
10225    // When '.' is followed by a composing char ignore the dot, so that
10226    // the composing char is matched here.
10227    if (c == Magic('.') && utf_iscomposing_legacy(peekchr())) {
10228      old_regparse = (uint8_t *)regparse;
10229      c = getchr();
10230      goto nfa_do_multibyte;
10231    }
10232    EMIT(nfa_classcodes[p - classchars]);
10233    if (extra == NFA_ADD_NL) {
10234      EMIT(NFA_NEWL);
10235      EMIT(NFA_OR);
10236      regflags |= RF_HASNL;
10237    }
10238    break;
10239
10240  case Magic('n'):
10241    if (reg_string) {
10242      // In a string "\n" matches a newline character.
10243      EMIT(NL);
10244    } else {
10245      // In buffer text "\n" matches the end of a line.
10246      EMIT(NFA_NEWL);
10247      regflags |= RF_HASNL;
10248    }
10249    break;
10250
10251  case Magic('('):
10252    if (nfa_reg(REG_PAREN) == FAIL) {
10253      return FAIL;                  // cascaded error
10254    }
10255    break;
10256
10257  case Magic('|'):
10258  case Magic('&'):
10259  case Magic(')'):
10260    semsg(_(e_misplaced), (char)no_Magic(c));
10261    return FAIL;
10262
10263  case Magic('='):
10264  case Magic('?'):
10265  case Magic('+'):
10266  case Magic('@'):
10267  case Magic('*'):
10268  case Magic('{'):
10269    // these should follow an atom, not form an atom
10270    semsg(_(e_misplaced), (char)no_Magic(c));
10271    return FAIL;
10272
10273  case Magic('~'): {
10274    uint8_t *lp;
10275
10276    // Previous substitute pattern.
10277    // Generated as "\%(pattern\)".
10278    if (reg_prev_sub == NULL) {
10279      emsg(_(e_nopresub));
10280      return FAIL;
10281    }
10282    for (lp = (uint8_t *)reg_prev_sub; *lp != NUL; lp += utf_ptr2len((char *)lp)) {
10283      EMIT(utf_ptr2char((char *)lp));
10284      if (lp != (uint8_t *)reg_prev_sub) {
10285        EMIT(NFA_CONCAT);
10286      }
10287    }
10288    EMIT(NFA_NOPEN);
10289    break;
10290  }
10291
10292  case Magic('1'):
10293  case Magic('2'):
10294  case Magic('3'):
10295  case Magic('4'):
10296  case Magic('5'):
10297  case Magic('6'):
10298  case Magic('7'):
10299  case Magic('8'):
10300  case Magic('9'): {
10301    int refnum = no_Magic(c) - '1';
10302
10303    if (!seen_endbrace(refnum + 1)) {
10304      return FAIL;
10305    }
10306    EMIT(NFA_BACKREF1 + refnum);
10307    rex.nfa_has_backref = true;
10308  }
10309  break;
10310
10311  case Magic('z'):
10312    c = no_Magic(getchr());
10313    switch (c) {
10314    case 's':
10315      EMIT(NFA_ZSTART);
10316      if (!re_mult_next("\\zs")) {
10317        return false;
10318      }
10319      break;
10320    case 'e':
10321      EMIT(NFA_ZEND);
10322      rex.nfa_has_zend = true;
10323      if (!re_mult_next("\\ze")) {
10324        return false;
10325      }
10326      break;
10327    case '1':
10328    case '2':
10329    case '3':
10330    case '4':
10331    case '5':
10332    case '6':
10333    case '7':
10334    case '8':
10335    case '9':
10336      // \z1...\z9
10337      if ((reg_do_extmatch & REX_USE) == 0) {
10338        EMSG_RET_FAIL(_(e_z1_not_allowed));
10339      }
10340      EMIT(NFA_ZREF1 + (no_Magic(c) - '1'));
10341      // No need to set rex.nfa_has_backref, the sub-matches don't
10342      // change when \z1 .. \z9 matches or not.
10343      re_has_z = REX_USE;
10344      break;
10345    case '(':
10346      // \z(
10347      if (reg_do_extmatch != REX_SET) {
10348        EMSG_RET_FAIL(_(e_z_not_allowed));
10349      }
10350      if (nfa_reg(REG_ZPAREN) == FAIL) {
10351        return FAIL;                        // cascaded error
10352      }
10353      re_has_z = REX_SET;
10354      break;
10355    default:
10356      semsg(_("E867: (NFA) Unknown operator '\\z%c'"),
10357            no_Magic(c));
10358      return FAIL;
10359    }
10360    break;
10361
10362  case Magic('%'):
10363    c = no_Magic(getchr());
10364    switch (c) {
10365    // () without a back reference
10366    case '(':
10367      if (nfa_reg(REG_NPAREN) == FAIL) {
10368        return FAIL;
10369      }
10370      EMIT(NFA_NOPEN);
10371      break;
10372
10373    case 'd':               // %d123 decimal
10374    case 'o':               // %o123 octal
10375    case 'x':               // %xab hex 2
10376    case 'u':               // %uabcd hex 4
10377    case 'U':               // %U1234abcd hex 8
10378    {
10379      int64_t nr;
10380
10381      switch (c) {
10382      case 'd':
10383        nr = getdecchrs(); break;
10384      case 'o':
10385        nr = getoctchrs(); break;
10386      case 'x':
10387        nr = gethexchrs(2); break;
10388      case 'u':
10389        nr = gethexchrs(4); break;
10390      case 'U':
10391        nr = gethexchrs(8); break;
10392      default:
10393        nr = -1; break;
10394      }
10395
10396      if (nr < 0 || nr > INT_MAX) {
10397        EMSG2_RET_FAIL(_("E678: Invalid character after %s%%[dxouU]"),
10398                       reg_magic == MAGIC_ALL);
10399      }
10400      // A NUL is stored in the text as NL
10401      // TODO(vim): what if a composing character follows?
10402      EMIT(nr == 0 ? 0x0a : (int)nr);
10403    }
10404    break;
10405
10406    // Catch \%^ and \%$ regardless of where they appear in the
10407    // pattern -- regardless of whether or not it makes sense.
10408    case '^':
10409      EMIT(NFA_BOF);
10410      break;
10411
10412    case '$':
10413      EMIT(NFA_EOF);
10414      break;
10415
10416    case '#':
10417      if (regparse[0] == '=' && regparse[1] >= 48
10418          && regparse[1] <= 50) {
10419        // misplaced \%#=1
10420        semsg(_(e_atom_engine_must_be_at_start_of_pattern), regparse[1]);
10421        return FAIL;
10422      }
10423      EMIT(NFA_CURSOR);
10424      break;
10425
10426    case 'V':
10427      EMIT(NFA_VISUAL);
10428      break;
10429
10430    case 'C':
10431      EMIT(NFA_ANY_COMPOSING);
10432      break;
10433
10434    case '[': {
10435      int n;
10436
10437      // \%[abc]
10438      for (n = 0; (c = peekchr()) != ']'; n++) {
10439        if (c == NUL) {
10440          EMSG2_RET_FAIL(_(e_missing_sb),
10441                         reg_magic == MAGIC_ALL);
10442        }
10443        // recursive call!
10444        if (nfa_regatom() == FAIL) {
10445          return FAIL;
10446        }
10447      }
10448      (void)getchr();  // get the ]
10449      if (n == 0) {
10450        EMSG2_RET_FAIL(_(e_empty_sb), reg_magic == MAGIC_ALL);
10451      }
10452      EMIT(NFA_OPT_CHARS);
10453      EMIT(n);
10454
10455      // Emit as "\%(\%[abc]\)" to be able to handle
10456      // "\%[abc]*" which would cause the empty string to be
10457      // matched an unlimited number of times. NFA_NOPEN is
10458      // added only once at a position, while NFA_SPLIT is
10459      // added multiple times.  This is more efficient than
10460      // not allowing NFA_SPLIT multiple times, it is used
10461      // a lot.
10462      EMIT(NFA_NOPEN);
10463      break;
10464    }
10465
10466    default: {
10467      int64_t n = 0;
10468      const int cmp = c;
10469      bool cur = false;
10470      bool got_digit = false;
10471
10472      if (c == '<' || c == '>') {
10473        c = getchr();
10474      }
10475      if (no_Magic(c) == '.') {
10476        cur = true;
10477        c = getchr();
10478      }
10479      while (ascii_isdigit(c)) {
10480        if (cur) {
10481          semsg(_(e_regexp_number_after_dot_pos_search_chr), no_Magic(c));
10482          return FAIL;
10483        }
10484        if (n > (INT32_MAX - (c - '0')) / 10) {
10485          // overflow.
10486          emsg(_(e_value_too_large));
10487          return FAIL;
10488        }
10489        n = n * 10 + (c - '0');
10490        c = getchr();
10491        got_digit = true;
10492      }
10493      if (c == 'l' || c == 'c' || c == 'v') {
10494        int32_t limit = INT32_MAX;
10495
10496        if (!cur && !got_digit) {
10497          semsg(_(e_nfa_regexp_missing_value_in_chr), no_Magic(c));
10498          return FAIL;
10499        }
10500        if (c == 'l') {
10501          if (cur) {
10502            n = curwin->w_cursor.lnum;
10503          }
10504          // \%{n}l  \%{n}<l  \%{n}>l
10505          EMIT(cmp == '<' ? NFA_LNUM_LT
10506                          : cmp == '>' ? NFA_LNUM_GT : NFA_LNUM);
10507          if (save_prev_at_start) {
10508            at_start = true;
10509          }
10510        } else if (c == 'c') {
10511          if (cur) {
10512            n = curwin->w_cursor.col;
10513            n++;
10514          }
10515          // \%{n}c  \%{n}<c  \%{n}>c
10516          EMIT(cmp == '<' ? NFA_COL_LT
10517                          : cmp == '>' ? NFA_COL_GT : NFA_COL);
10518        } else {
10519          if (cur) {
10520            colnr_T vcol = 0;
10521            getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &vcol, 0);
10522            n = ++vcol;
10523          }
10524          // \%{n}v  \%{n}<v  \%{n}>v
10525          EMIT(cmp == '<' ? NFA_VCOL_LT
10526                          : cmp == '>' ? NFA_VCOL_GT : NFA_VCOL);
10527          limit = INT32_MAX / MB_MAXBYTES;
10528        }
10529        if (n >= limit) {
10530          emsg(_(e_value_too_large));
10531          return FAIL;
10532        }
10533        EMIT((int)n);
10534        break;
10535      } else if (no_Magic(c) == '\'' && n == 0) {
10536        // \%'m  \%<'m  \%>'m
10537        EMIT(cmp == '<' ? NFA_MARK_LT
10538                        : cmp == '>' ? NFA_MARK_GT : NFA_MARK);
10539        EMIT(getchr());
10540        break;
10541      }
10542    }
10543      semsg(_("E867: (NFA) Unknown operator '\\%%%c'"),
10544            no_Magic(c));
10545      return FAIL;
10546    }
10547    break;
10548
10549  case Magic('['):
10550collection:
10551    // [abc]  uses NFA_START_COLL - NFA_END_COLL
10552    // [^abc] uses NFA_START_NEG_COLL - NFA_END_NEG_COLL
10553    // Each character is produced as a regular state, using
10554    // NFA_CONCAT to bind them together.
10555    // Besides normal characters there can be:
10556    // - character classes  NFA_CLASS_*
10557    // - ranges, two characters followed by NFA_RANGE.
10558
10559    p = (uint8_t *)regparse;
10560    endp = (uint8_t *)skip_anyof((char *)p);
10561    if (*endp == ']') {
10562      bool range_endpoint;
10563      // Try to reverse engineer character classes. For example,
10564      // recognize that [0-9] stands for \d and [A-Za-z_] for \h,
10565      // and perform the necessary substitutions in the NFA.
10566      int result = nfa_recognize_char_class((uint8_t *)regparse, endp, extra == NFA_ADD_NL);
10567      if (result != FAIL) {
10568        if (result >= NFA_FIRST_NL && result <= NFA_LAST_NL) {
10569          EMIT(result - NFA_ADD_NL);
10570          EMIT(NFA_NEWL);
10571          EMIT(NFA_OR);
10572        } else {
10573          EMIT(result);
10574        }
10575        regparse = (char *)endp;
10576        MB_PTR_ADV(regparse);
10577        return OK;
10578      }
10579      // Failed to recognize a character class. Use the simple
10580      // version that turns [abc] into 'a' OR 'b' OR 'c'
10581      negated = false;
10582      if (*regparse == '^') {                           // negated range
10583        negated = true;
10584        MB_PTR_ADV(regparse);
10585        EMIT(NFA_START_NEG_COLL);
10586      } else {
10587        EMIT(NFA_START_COLL);
10588      }
10589      if (*regparse == '-') {
10590        startc = '-';
10591        EMIT(startc);
10592        EMIT(NFA_CONCAT);
10593        MB_PTR_ADV(regparse);
10594      }
10595      // Emit the OR branches for each character in the []
10596      emit_range = false;
10597      while ((uint8_t *)regparse < endp) {
10598        int oldstartc = startc;
10599        range_endpoint = false;
10600        startc = -1;
10601        got_coll_char = false;
10602        if (*regparse == '[') {
10603          // Check for [: :], [= =], [. .]
10604          equiclass = collclass = 0;
10605          charclass = get_char_class(&regparse);
10606          if (charclass == CLASS_NONE) {
10607            equiclass = get_equi_class(&regparse);
10608            if (equiclass == 0) {
10609              collclass = get_coll_element(&regparse);
10610            }
10611          }
10612
10613          // Character class like [:alpha:]
10614          if (charclass != CLASS_NONE) {
10615            switch (charclass) {
10616            case CLASS_ALNUM:
10617              EMIT(NFA_CLASS_ALNUM);
10618              break;
10619            case CLASS_ALPHA:
10620              EMIT(NFA_CLASS_ALPHA);
10621              break;
10622            case CLASS_BLANK:
10623              EMIT(NFA_CLASS_BLANK);
10624              break;
10625            case CLASS_CNTRL:
10626              EMIT(NFA_CLASS_CNTRL);
10627              break;
10628            case CLASS_DIGIT:
10629              EMIT(NFA_CLASS_DIGIT);
10630              break;
10631            case CLASS_GRAPH:
10632              EMIT(NFA_CLASS_GRAPH);
10633              break;
10634            case CLASS_LOWER:
10635              wants_nfa = true;
10636              EMIT(NFA_CLASS_LOWER);
10637              break;
10638            case CLASS_PRINT:
10639              EMIT(NFA_CLASS_PRINT);
10640              break;
10641            case CLASS_PUNCT:
10642              EMIT(NFA_CLASS_PUNCT);
10643              break;
10644            case CLASS_SPACE:
10645              EMIT(NFA_CLASS_SPACE);
10646              break;
10647            case CLASS_UPPER:
10648              wants_nfa = true;
10649              EMIT(NFA_CLASS_UPPER);
10650              break;
10651            case CLASS_XDIGIT:
10652              EMIT(NFA_CLASS_XDIGIT);
10653              break;
10654            case CLASS_TAB:
10655              EMIT(NFA_CLASS_TAB);
10656              break;
10657            case CLASS_RETURN:
10658              EMIT(NFA_CLASS_RETURN);
10659              break;
10660            case CLASS_BACKSPACE:
10661              EMIT(NFA_CLASS_BACKSPACE);
10662              break;
10663            case CLASS_ESCAPE:
10664              EMIT(NFA_CLASS_ESCAPE);
10665              break;
10666            case CLASS_IDENT:
10667              EMIT(NFA_CLASS_IDENT);
10668              break;
10669            case CLASS_KEYWORD:
10670              EMIT(NFA_CLASS_KEYWORD);
10671              break;
10672            case CLASS_FNAME:
10673              EMIT(NFA_CLASS_FNAME);
10674              break;
10675            }
10676            EMIT(NFA_CONCAT);
10677            continue;
10678          }
10679          // Try equivalence class [=a=] and the like
10680          if (equiclass != 0) {
10681            nfa_emit_equi_class(equiclass);
10682            continue;
10683          }
10684          // Try collating class like [. .]
10685          if (collclass != 0) {
10686            startc = collclass;                  // allow [.a.]-x as a range
10687            // Will emit the proper atom at the end of the
10688            // while loop.
10689          }
10690        }
10691        // Try a range like 'a-x' or '\t-z'. Also allows '-' as a
10692        // start character.
10693        if (*regparse == '-' && oldstartc != -1) {
10694          emit_range = true;
10695          startc = oldstartc;
10696          MB_PTR_ADV(regparse);
10697          continue;                         // reading the end of the range
10698        }
10699
10700        // Now handle simple and escaped characters.
10701        // Only "\]", "\^", "\]" and "\\" are special in Vi.  Vim
10702        // accepts "\t", "\e", etc., but only when the 'l' flag in
10703        // 'cpoptions' is not included.
10704        if (*regparse == '\\'
10705            && (uint8_t *)regparse + 1 <= endp
10706            && (vim_strchr(REGEXP_INRANGE, (uint8_t)regparse[1]) != NULL
10707                || (!reg_cpo_lit
10708                    && vim_strchr(REGEXP_ABBR, (uint8_t)regparse[1])
10709                    != NULL))) {
10710          MB_PTR_ADV(regparse);
10711
10712          if (*regparse == 'n') {
10713            startc = (reg_string || emit_range || regparse[1] == '-')
10714                     ? NL : NFA_NEWL;
10715          } else if (*regparse == 'd'
10716                     || *regparse == 'o'
10717                     || *regparse == 'x'
10718                     || *regparse == 'u'
10719                     || *regparse == 'U') {
10720            // TODO(RE): This needs more testing
10721            startc = coll_get_char();
10722            // max UTF-8 Codepoint is U+10FFFF,
10723            // but allow values until INT_MAX
10724            if (startc == INT_MAX) {
10725              EMSG_RET_FAIL(_(e_unicode_val_too_large));
10726            }
10727            got_coll_char = true;
10728            MB_PTR_BACK(old_regparse, regparse);
10729          } else {
10730            // \r,\t,\e,\b
10731            startc = backslash_trans(*regparse);
10732          }
10733        }
10734
10735        // Normal printable char
10736        if (startc == -1) {
10737          startc = utf_ptr2char(regparse);
10738        }
10739
10740        // Previous char was '-', so this char is end of range.
10741        if (emit_range) {
10742          int endc = startc;
10743          range_endpoint = true;
10744          startc = oldstartc;
10745          if (startc > endc) {
10746            EMSG_RET_FAIL(_(e_reverse_range));
10747          }
10748
10749          if (endc > startc + 2) {
10750            // Emit a range instead of the sequence of
10751            // individual characters.
10752            if (startc == 0) {
10753              // \x00 is translated to \x0a, start at \x01.
10754              EMIT(1);
10755            } else {
10756              post_ptr--;                   // remove NFA_CONCAT
10757            }
10758            EMIT(endc);
10759            EMIT(NFA_RANGE);
10760            EMIT(NFA_CONCAT);
10761          } else if (utf_char2len(startc) > 1
10762                     || utf_char2len(endc) > 1) {
10763            // Emit the characters in the range.
10764            // "startc" was already emitted, so skip it.
10765            for (c = startc + 1; c <= endc; c++) {
10766              EMIT(c);
10767              EMIT(NFA_CONCAT);
10768            }
10769          } else {
10770            // Emit the range. "startc" was already emitted, so
10771            // skip it.
10772            for (c = startc + 1; c <= endc; c++) {
10773              EMIT(c);
10774              EMIT(NFA_CONCAT);
10775            }
10776          }
10777          emit_range = false;
10778          startc = -1;
10779        } else {
10780          // This char (startc) is not part of a range. Just
10781          // emit it.
10782          // Normally, simply emit startc. But if we get char
10783          // code=0 from a collating char, then replace it with
10784          // 0x0a.
10785          // This is needed to completely mimic the behaviour of
10786          // the backtracking engine.
10787          if (startc == NFA_NEWL) {
10788            // Line break can't be matched as part of the
10789            // collection, add an OR below. But not for negated
10790            // range.
10791            if (!negated) {
10792              extra = NFA_ADD_NL;
10793            }
10794          } else {
10795            if (got_coll_char == true && startc == 0) {
10796              EMIT(0x0a);
10797              EMIT(NFA_CONCAT);
10798            } else {
10799              EMIT(startc);
10800              if (utf_ptr2len(regparse) == utfc_ptr2len(regparse)) {
10801                EMIT(NFA_CONCAT);
10802              }
10803            }
10804          }
10805        }
10806
10807        int plen;
10808        //
10809        // If this character was consumed as the end of a range, do not emit its
10810        // composing characters separately.  Range handling only uses the base
10811        // codepoint; emitting the composing part again would duplicate the
10812        // character in the postfix stream and corrupt the NFA stack.
10813        //
10814        if (!range_endpoint
10815            && utf_ptr2len(regparse) != (plen = utfc_ptr2len(regparse))) {
10816          int i = utf_ptr2len(regparse);
10817
10818          c = utf_ptr2char(regparse + i);
10819
10820          // Add composing characters
10821          while (true) {
10822            if (c == 0) {
10823              // \x00 is translated to \x0a, start at \x01.
10824              EMIT(1);
10825            } else {
10826              EMIT(c);
10827            }
10828            EMIT(NFA_CONCAT);
10829            if ((i += utf_char2len(c)) >= plen) {
10830              break;
10831            }
10832            c = utf_ptr2char(regparse + i);
10833          }
10834          EMIT(NFA_COMPOSING);
10835          EMIT(NFA_CONCAT);
10836        }
10837        MB_PTR_ADV(regparse);
10838      }           // while (p < endp)
10839
10840      MB_PTR_BACK(old_regparse, regparse);
10841      if (*regparse == '-') {               // if last, '-' is just a char
10842        EMIT('-');
10843        EMIT(NFA_CONCAT);
10844      }
10845
10846      // skip the trailing ]
10847      regparse = (char *)endp;
10848      MB_PTR_ADV(regparse);
10849
10850      // Mark end of the collection.
10851      if (negated == true) {
10852        EMIT(NFA_END_NEG_COLL);
10853      } else {
10854        EMIT(NFA_END_COLL);
10855      }
10856
10857      // \_[] also matches \n but it's not negated
10858      if (extra == NFA_ADD_NL) {
10859        EMIT(reg_string ? NL : NFA_NEWL);
10860        EMIT(NFA_OR);
10861      }
10862
10863      return OK;
10864    }         // if exists closing ]
10865
10866    if (reg_strict) {
10867      EMSG_RET_FAIL(_(e_missingbracket));
10868    }
10869    FALLTHROUGH;
10870
10871  default: {
10872    int plen;
10873
10874nfa_do_multibyte:
10875    // plen is length of current char with composing chars
10876    if (utf_char2len(c) != (plen = utfc_ptr2len((char *)old_regparse))
10877        || utf_iscomposing_legacy(c)) {
10878      int i = 0;
10879
10880      // A base character plus composing characters, or just one
10881      // or more composing characters.
10882      // This requires creating a separate atom as if enclosing
10883      // the characters in (), where NFA_COMPOSING is the ( and
10884      // NFA_END_COMPOSING is the ). Note that right now we are
10885      // building the postfix form, not the NFA itself;
10886      // a composing char could be: a, b, c, NFA_COMPOSING
10887      // where 'b' and 'c' are chars with codes > 256.
10888      while (true) {
10889        EMIT(c);
10890        if (i > 0) {
10891          EMIT(NFA_CONCAT);
10892        }
10893        if ((i += utf_char2len(c)) >= plen) {
10894          break;
10895        }
10896        c = utf_ptr2char((char *)old_regparse + i);
10897      }
10898      EMIT(NFA_COMPOSING);
10899      regparse = (char *)old_regparse + plen;
10900    } else {
10901      c = no_Magic(c);
10902      EMIT(c);
10903    }
10904    return OK;
10905  }
10906  }
10907
10908  return OK;
10909}
10910
10911// Parse something followed by possible [*+=].
10912//
10913// A piece is an atom, possibly followed by a multi, an indication of how many
10914// times the atom can be matched.  Example: "a*" matches any sequence of "a"
10915// characters: "", "a", "aa", etc.
10916//
10917// piece   ::=      atom
10918//      or  atom  multi
10919static int nfa_regpiece(void)
10920{
10921  int i;
10922  int op;
10923  int ret;
10924  int minval, maxval;
10925  bool greedy = true;  // Braces are prefixed with '-' ?
10926  parse_state_T old_state;
10927  parse_state_T new_state;
10928  int64_t c2;
10929  int old_post_pos;
10930  int my_post_start;
10931  int quest;
10932
10933  // Save the current parse state, so that we can use it if <atom>{m,n} is
10934  // next.
10935  save_parse_state(&old_state);
10936
10937  // store current pos in the postfix form, for \{m,n} involving 0s
10938  my_post_start = (int)(post_ptr - post_start);
10939
10940  ret = nfa_regatom();
10941  if (ret == FAIL) {
10942    return FAIL;            // cascaded error
10943  }
10944  op = peekchr();
10945  if (re_multi_type(op) == NOT_MULTI) {
10946    return OK;
10947  }
10948
10949  skipchr();
10950  switch (op) {
10951  case Magic('*'):
10952    EMIT(NFA_STAR);
10953    break;
10954
10955  case Magic('+'):
10956    // Trick: Normally, (a*)\+ would match the whole input "aaa".  The
10957    // first and only submatch would be "aaa". But the backtracking
10958    // engine interprets the plus as "try matching one more time", and
10959    // a* matches a second time at the end of the input, the empty
10960    // string.
10961    // The submatch will be the empty string.
10962    //
10963    // In order to be consistent with the old engine, we replace
10964    // <atom>+ with <atom><atom>*
10965    restore_parse_state(&old_state);
10966    curchr = -1;
10967    if (nfa_regatom() == FAIL) {
10968      return FAIL;
10969    }
10970    EMIT(NFA_STAR);
10971    EMIT(NFA_CONCAT);
10972    skipchr();                  // skip the \+
10973    break;
10974
10975  case Magic('@'):
10976    c2 = getdecchrs();
10977    op = no_Magic(getchr());
10978    i = 0;
10979    switch (op) {
10980    case '=':
10981      // \@=
10982      i = NFA_PREV_ATOM_NO_WIDTH;
10983      break;
10984    case '!':
10985      // \@!
10986      i = NFA_PREV_ATOM_NO_WIDTH_NEG;
10987      break;
10988    case '<':
10989      op = no_Magic(getchr());
10990      if (op == '=') {
10991        // \@<=
10992        i = NFA_PREV_ATOM_JUST_BEFORE;
10993      } else if (op == '!') {
10994        // \@<!
10995        i = NFA_PREV_ATOM_JUST_BEFORE_NEG;
10996      }
10997      break;
10998    case '>':
10999      // \@>
11000      i = NFA_PREV_ATOM_LIKE_PATTERN;
11001      break;
11002    }
11003    if (i == 0) {
11004      semsg(_("E869: (NFA) Unknown operator '\\@%c'"), op);
11005      return FAIL;
11006    }
11007    EMIT(i);
11008    if (i == NFA_PREV_ATOM_JUST_BEFORE
11009        || i == NFA_PREV_ATOM_JUST_BEFORE_NEG) {
11010      EMIT((int)c2);
11011    }
11012    break;
11013
11014  case Magic('?'):
11015  case Magic('='):
11016    EMIT(NFA_QUEST);
11017    break;
11018
11019  case Magic('{'):
11020    // a{2,5} will expand to 'aaa?a?a?'
11021    // a{-1,3} will expand to 'aa??a??', where ?? is the nongreedy
11022    // version of '?'
11023    // \v(ab){2,3} will expand to '(ab)(ab)(ab)?', where all the
11024    // parenthesis have the same id
11025
11026    greedy = true;
11027    c2 = peekchr();
11028    if (c2 == '-' || c2 == Magic('-')) {
11029      skipchr();
11030      greedy = false;
11031    }
11032    if (!read_limits(&minval, &maxval)) {
11033      EMSG_RET_FAIL(_("E870: (NFA regexp) Error reading repetition limits"));
11034    }
11035
11036    //  <atom>{0,inf}, <atom>{0,} and <atom>{}  are equivalent to
11037    //  <atom>*
11038    if (minval == 0 && maxval == MAX_LIMIT) {
11039      if (greedy) {
11040        // \{}, \{0,}
11041        EMIT(NFA_STAR);
11042      } else {
11043        // \{-}, \{-0,}
11044        EMIT(NFA_STAR_NONGREEDY);
11045      }
11046      break;
11047    }
11048
11049    // Special case: x{0} or x{-0}
11050    if (maxval == 0) {
11051      // Ignore result of previous call to nfa_regatom()
11052      post_ptr = post_start + my_post_start;
11053      // NFA_EMPTY is 0-length and works everywhere
11054      EMIT(NFA_EMPTY);
11055      return OK;
11056    }
11057
11058    // The engine is very inefficient (uses too many states) when the
11059    // maximum is much larger than the minimum and when the maximum is
11060    // large.  However, when maxval is MAX_LIMIT, it is okay, as this
11061    // will emit NFA_STAR.
11062    // Bail out if we can use the other engine, but only, when the
11063    // pattern does not need the NFA engine like (e.g. [[:upper:]]\{2,\}
11064    // does not work with characters > 8 bit with the BT engine)
11065    if ((nfa_re_flags & RE_AUTO)
11066        && (maxval > 500 || maxval > minval + 200)
11067        && (maxval != MAX_LIMIT && minval < 200)
11068        && !wants_nfa) {
11069      return FAIL;
11070    }
11071
11072    // Ignore previous call to nfa_regatom()
11073    post_ptr = post_start + my_post_start;
11074    // Save parse state after the repeated atom and the \{}
11075    save_parse_state(&new_state);
11076
11077    quest = (greedy == true ? NFA_QUEST : NFA_QUEST_NONGREEDY);
11078    for (i = 0; i < maxval; i++) {
11079      // Goto beginning of the repeated atom
11080      restore_parse_state(&old_state);
11081      old_post_pos = (int)(post_ptr - post_start);
11082      if (nfa_regatom() == FAIL) {
11083        return FAIL;
11084      }
11085      // after "minval" times, atoms are optional
11086      if (i + 1 > minval) {
11087        if (maxval == MAX_LIMIT) {
11088          if (greedy) {
11089            EMIT(NFA_STAR);
11090          } else {
11091            EMIT(NFA_STAR_NONGREEDY);
11092          }
11093        } else {
11094          EMIT(quest);
11095        }
11096      }
11097      if (old_post_pos != my_post_start) {
11098        EMIT(NFA_CONCAT);
11099      }
11100      if (i + 1 > minval && maxval == MAX_LIMIT) {
11101        break;
11102      }
11103    }
11104
11105    // Go to just after the repeated atom and the \{}
11106    restore_parse_state(&new_state);
11107    curchr = -1;
11108
11109    break;
11110
11111  default:
11112    break;
11113  }     // end switch
11114
11115  if (re_multi_type(peekchr()) != NOT_MULTI) {
11116    // Can't have a multi follow a multi.
11117    EMSG_RET_FAIL(_("E871: (NFA regexp) Can't have a multi follow a multi"));
11118  }
11119
11120  return OK;
11121}
11122
11123// Parse one or more pieces, concatenated.  It matches a match for the
11124// first piece, followed by a match for the second piece, etc.  Example:
11125// "f[0-9]b", first matches "f", then a digit and then "b".
11126//
11127// concat  ::=      piece
11128//      or  piece piece
11129//      or  piece piece piece
11130//      etc.
11131static int nfa_regconcat(void)
11132{
11133  bool cont = true;
11134  bool first = true;
11135
11136  while (cont) {
11137    switch (peekchr()) {
11138    case NUL:
11139    case Magic('|'):
11140    case Magic('&'):
11141    case Magic(')'):
11142      cont = false;
11143      break;
11144
11145    case Magic('Z'):
11146      regflags |= RF_ICOMBINE;
11147      skipchr_keepstart();
11148      break;
11149    case Magic('c'):
11150      regflags |= RF_ICASE;
11151      skipchr_keepstart();
11152      break;
11153    case Magic('C'):
11154      regflags |= RF_NOICASE;
11155      skipchr_keepstart();
11156      break;
11157    case Magic('v'):
11158      reg_magic = MAGIC_ALL;
11159      skipchr_keepstart();
11160      curchr = -1;
11161      break;
11162    case Magic('m'):
11163      reg_magic = MAGIC_ON;
11164      skipchr_keepstart();
11165      curchr = -1;
11166      break;
11167    case Magic('M'):
11168      reg_magic = MAGIC_OFF;
11169      skipchr_keepstart();
11170      curchr = -1;
11171      break;
11172    case Magic('V'):
11173      reg_magic = MAGIC_NONE;
11174      skipchr_keepstart();
11175      curchr = -1;
11176      break;
11177
11178    default:
11179      if (nfa_regpiece() == FAIL) {
11180        return FAIL;
11181      }
11182      if (first == false) {
11183        EMIT(NFA_CONCAT);
11184      } else {
11185        first = false;
11186      }
11187      break;
11188    }
11189  }
11190
11191  return OK;
11192}
11193
11194// Parse a branch, one or more concats, separated by "\&".  It matches the
11195// last concat, but only if all the preceding concats also match at the same
11196// position.  Examples:
11197//      "foobeep\&..." matches "foo" in "foobeep".
11198//      ".*Peter\&.*Bob" matches in a line containing both "Peter" and "Bob"
11199//
11200// branch ::=       concat
11201//              or  concat \& concat
11202//              or  concat \& concat \& concat
11203//              etc.
11204static int nfa_regbranch(void)
11205{
11206  int old_post_pos;
11207
11208  old_post_pos = (int)(post_ptr - post_start);
11209
11210  // First branch, possibly the only one
11211  if (nfa_regconcat() == FAIL) {
11212    return FAIL;
11213  }
11214
11215  // Try next concats
11216  while (peekchr() == Magic('&')) {
11217    skipchr();
11218    // if concat is empty do emit a node
11219    if (old_post_pos == (int)(post_ptr - post_start)) {
11220      EMIT(NFA_EMPTY);
11221    }
11222    EMIT(NFA_NOPEN);
11223    EMIT(NFA_PREV_ATOM_NO_WIDTH);
11224    old_post_pos = (int)(post_ptr - post_start);
11225    if (nfa_regconcat() == FAIL) {
11226      return FAIL;
11227    }
11228    // if concat is empty do emit a node
11229    if (old_post_pos == (int)(post_ptr - post_start)) {
11230      EMIT(NFA_EMPTY);
11231    }
11232    EMIT(NFA_CONCAT);
11233  }
11234
11235  // if a branch is empty, emit one node for it
11236  if (old_post_pos == (int)(post_ptr - post_start)) {
11237    EMIT(NFA_EMPTY);
11238  }
11239
11240  return OK;
11241}
11242
11243///  Parse a pattern, one or more branches, separated by "\|".  It matches
11244///  anything that matches one of the branches.  Example: "foo\|beep" matches
11245///  "foo" and matches "beep".  If more than one branch matches, the first one
11246///  is used.
11247///
11248///  pattern ::=     branch
11249///      or  branch \| branch
11250///      or  branch \| branch \| branch
11251///      etc.
11252///
11253/// @param paren  REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN
11254static int nfa_reg(int paren)
11255{
11256  int parno = 0;
11257  int status = FAIL;
11258
11259  if (paren == REG_PAREN) {
11260    if (regnpar >= NSUBEXP) {   // Too many `('
11261      EMSG_RET_FAIL(_("E872: (NFA regexp) Too many '('"));
11262    }
11263    parno = regnpar++;
11264  } else if (paren == REG_ZPAREN) {
11265    // Make a ZOPEN node.
11266    if (regnzpar >= NSUBEXP) {
11267      EMSG_RET_FAIL(_("E879: (NFA regexp) Too many \\z("));
11268    }
11269    parno = regnzpar++;
11270  }
11271
11272  if (nfa_reg_parse_depth >= REG_MAX_PAREN_DEPTH) {
11273    EMSG_RET_FAIL(_(e_command_too_complex));
11274  }
11275  nfa_reg_parse_depth++;
11276
11277  if (nfa_regbranch() == FAIL) {
11278    goto theend;            // cascaded error
11279  }
11280  while (peekchr() == Magic('|')) {
11281    skipchr();
11282    if (nfa_regbranch() == FAIL) {
11283      goto theend;          // cascaded error
11284    }
11285    EMIT(NFA_OR);
11286  }
11287
11288  // Check for proper termination.
11289  if (paren != REG_NOPAREN && getchr() != Magic(')')) {
11290    if (paren == REG_NPAREN) {
11291      semsg(_(e_unmatched_str_percent_open), reg_magic == MAGIC_ALL ? "" : "\\");
11292    } else {
11293      semsg(_(e_unmatched_str_open), reg_magic == MAGIC_ALL ? "" : "\\");
11294    }
11295    rc_did_emsg = true;
11296    goto theend;
11297  } else if (paren == REG_NOPAREN && peekchr() != NUL) {
11298    if (peekchr() == Magic(')')) {
11299      semsg(_(e_unmatched_str_close), reg_magic == MAGIC_ALL ? "" : "\\");
11300    } else {
11301      emsg(_("E873: (NFA regexp) proper termination error"));
11302    }
11303    rc_did_emsg = true;
11304    goto theend;
11305  }
11306  // Here we set the flag allowing back references to this set of
11307  // parentheses.
11308  if (paren == REG_PAREN) {
11309    had_endbrace[parno] = true;  // have seen the close paren
11310    EMIT(NFA_MOPEN + parno);
11311  } else if (paren == REG_ZPAREN) {
11312    EMIT(NFA_ZOPEN + parno);
11313  }
11314
11315  status = OK;
11316
11317theend:
11318  nfa_reg_parse_depth--;
11319  return status;
11320}
11321
11322#ifdef REGEXP_DEBUG
11323static uint8_t code[50];
11324
11325static void nfa_set_code(int c)
11326{
11327  int addnl = false;
11328
11329  if (c >= NFA_FIRST_NL && c <= NFA_LAST_NL) {
11330    addnl = true;
11331    c -= NFA_ADD_NL;
11332  }
11333
11334  STRCPY(code, "");
11335  switch (c) {
11336  case NFA_MATCH:
11337    STRCPY(code, "NFA_MATCH "); break;
11338  case NFA_SPLIT:
11339    STRCPY(code, "NFA_SPLIT "); break;
11340  case NFA_CONCAT:
11341    STRCPY(code, "NFA_CONCAT "); break;
11342  case NFA_NEWL:
11343    STRCPY(code, "NFA_NEWL "); break;
11344  case NFA_ZSTART:
11345    STRCPY(code, "NFA_ZSTART"); break;
11346  case NFA_ZEND:
11347    STRCPY(code, "NFA_ZEND"); break;
11348
11349  case NFA_BACKREF1:
11350    STRCPY(code, "NFA_BACKREF1"); break;
11351  case NFA_BACKREF2:
11352    STRCPY(code, "NFA_BACKREF2"); break;
11353  case NFA_BACKREF3:
11354    STRCPY(code, "NFA_BACKREF3"); break;
11355  case NFA_BACKREF4:
11356    STRCPY(code, "NFA_BACKREF4"); break;
11357  case NFA_BACKREF5:
11358    STRCPY(code, "NFA_BACKREF5"); break;
11359  case NFA_BACKREF6:
11360    STRCPY(code, "NFA_BACKREF6"); break;
11361  case NFA_BACKREF7:
11362    STRCPY(code, "NFA_BACKREF7"); break;
11363  case NFA_BACKREF8:
11364    STRCPY(code, "NFA_BACKREF8"); break;
11365  case NFA_BACKREF9:
11366    STRCPY(code, "NFA_BACKREF9"); break;
11367  case NFA_ZREF1:
11368    STRCPY(code, "NFA_ZREF1"); break;
11369  case NFA_ZREF2:
11370    STRCPY(code, "NFA_ZREF2"); break;
11371  case NFA_ZREF3:
11372    STRCPY(code, "NFA_ZREF3"); break;
11373  case NFA_ZREF4:
11374    STRCPY(code, "NFA_ZREF4"); break;
11375  case NFA_ZREF5:
11376    STRCPY(code, "NFA_ZREF5"); break;
11377  case NFA_ZREF6:
11378    STRCPY(code, "NFA_ZREF6"); break;
11379  case NFA_ZREF7:
11380    STRCPY(code, "NFA_ZREF7"); break;
11381  case NFA_ZREF8:
11382    STRCPY(code, "NFA_ZREF8"); break;
11383  case NFA_ZREF9:
11384    STRCPY(code, "NFA_ZREF9"); break;
11385  case NFA_SKIP:
11386    STRCPY(code, "NFA_SKIP"); break;
11387
11388  case NFA_PREV_ATOM_NO_WIDTH:
11389    STRCPY(code, "NFA_PREV_ATOM_NO_WIDTH"); break;
11390  case NFA_PREV_ATOM_NO_WIDTH_NEG:
11391    STRCPY(code, "NFA_PREV_ATOM_NO_WIDTH_NEG"); break;
11392  case NFA_PREV_ATOM_JUST_BEFORE:
11393    STRCPY(code, "NFA_PREV_ATOM_JUST_BEFORE"); break;
11394  case NFA_PREV_ATOM_JUST_BEFORE_NEG:
11395    STRCPY(code, "NFA_PREV_ATOM_JUST_BEFORE_NEG"); break;
11396  case NFA_PREV_ATOM_LIKE_PATTERN:
11397    STRCPY(code, "NFA_PREV_ATOM_LIKE_PATTERN"); break;
11398
11399  case NFA_NOPEN:
11400    STRCPY(code, "NFA_NOPEN"); break;
11401  case NFA_NCLOSE:
11402    STRCPY(code, "NFA_NCLOSE"); break;
11403  case NFA_START_INVISIBLE:
11404    STRCPY(code, "NFA_START_INVISIBLE"); break;
11405  case NFA_START_INVISIBLE_FIRST:
11406    STRCPY(code, "NFA_START_INVISIBLE_FIRST"); break;
11407  case NFA_START_INVISIBLE_NEG:
11408    STRCPY(code, "NFA_START_INVISIBLE_NEG"); break;
11409  case NFA_START_INVISIBLE_NEG_FIRST:
11410    STRCPY(code, "NFA_START_INVISIBLE_NEG_FIRST"); break;
11411  case NFA_START_INVISIBLE_BEFORE:
11412    STRCPY(code, "NFA_START_INVISIBLE_BEFORE"); break;
11413  case NFA_START_INVISIBLE_BEFORE_FIRST:
11414    STRCPY(code, "NFA_START_INVISIBLE_BEFORE_FIRST"); break;
11415  case NFA_START_INVISIBLE_BEFORE_NEG:
11416    STRCPY(code, "NFA_START_INVISIBLE_BEFORE_NEG"); break;
11417  case NFA_START_INVISIBLE_BEFORE_NEG_FIRST:
11418    STRCPY(code, "NFA_START_INVISIBLE_BEFORE_NEG_FIRST"); break;
11419  case NFA_START_PATTERN:
11420    STRCPY(code, "NFA_START_PATTERN"); break;
11421  case NFA_END_INVISIBLE:
11422    STRCPY(code, "NFA_END_INVISIBLE"); break;
11423  case NFA_END_INVISIBLE_NEG:
11424    STRCPY(code, "NFA_END_INVISIBLE_NEG"); break;
11425  case NFA_END_PATTERN:
11426    STRCPY(code, "NFA_END_PATTERN"); break;
11427
11428  case NFA_COMPOSING:
11429    STRCPY(code, "NFA_COMPOSING"); break;
11430  case NFA_END_COMPOSING:
11431    STRCPY(code, "NFA_END_COMPOSING"); break;
11432  case NFA_OPT_CHARS:
11433    STRCPY(code, "NFA_OPT_CHARS"); break;
11434
11435  case NFA_MOPEN:
11436  case NFA_MOPEN1:
11437  case NFA_MOPEN2:
11438  case NFA_MOPEN3:
11439  case NFA_MOPEN4:
11440  case NFA_MOPEN5:
11441  case NFA_MOPEN6:
11442  case NFA_MOPEN7:
11443  case NFA_MOPEN8:
11444  case NFA_MOPEN9:
11445    STRCPY(code, "NFA_MOPEN(x)");
11446    code[10] = c - NFA_MOPEN + '0';
11447    break;
11448  case NFA_MCLOSE:
11449  case NFA_MCLOSE1:
11450  case NFA_MCLOSE2:
11451  case NFA_MCLOSE3:
11452  case NFA_MCLOSE4:
11453  case NFA_MCLOSE5:
11454  case NFA_MCLOSE6:
11455  case NFA_MCLOSE7:
11456  case NFA_MCLOSE8:
11457  case NFA_MCLOSE9:
11458    STRCPY(code, "NFA_MCLOSE(x)");
11459    code[11] = c - NFA_MCLOSE + '0';
11460    break;
11461  case NFA_ZOPEN:
11462  case NFA_ZOPEN1:
11463  case NFA_ZOPEN2:
11464  case NFA_ZOPEN3:
11465  case NFA_ZOPEN4:
11466  case NFA_ZOPEN5:
11467  case NFA_ZOPEN6:
11468  case NFA_ZOPEN7:
11469  case NFA_ZOPEN8:
11470  case NFA_ZOPEN9:
11471    STRCPY(code, "NFA_ZOPEN(x)");
11472    code[10] = c - NFA_ZOPEN + '0';
11473    break;
11474  case NFA_ZCLOSE:
11475  case NFA_ZCLOSE1:
11476  case NFA_ZCLOSE2:
11477  case NFA_ZCLOSE3:
11478  case NFA_ZCLOSE4:
11479  case NFA_ZCLOSE5:
11480  case NFA_ZCLOSE6:
11481  case NFA_ZCLOSE7:
11482  case NFA_ZCLOSE8:
11483  case NFA_ZCLOSE9:
11484    STRCPY(code, "NFA_ZCLOSE(x)");
11485    code[11] = c - NFA_ZCLOSE + '0';
11486    break;
11487  case NFA_EOL:
11488    STRCPY(code, "NFA_EOL "); break;
11489  case NFA_BOL:
11490    STRCPY(code, "NFA_BOL "); break;
11491  case NFA_EOW:
11492    STRCPY(code, "NFA_EOW "); break;
11493  case NFA_BOW:
11494    STRCPY(code, "NFA_BOW "); break;
11495  case NFA_EOF:
11496    STRCPY(code, "NFA_EOF "); break;
11497  case NFA_BOF:
11498    STRCPY(code, "NFA_BOF "); break;
11499  case NFA_LNUM:
11500    STRCPY(code, "NFA_LNUM "); break;
11501  case NFA_LNUM_GT:
11502    STRCPY(code, "NFA_LNUM_GT "); break;
11503  case NFA_LNUM_LT:
11504    STRCPY(code, "NFA_LNUM_LT "); break;
11505  case NFA_COL:
11506    STRCPY(code, "NFA_COL "); break;
11507  case NFA_COL_GT:
11508    STRCPY(code, "NFA_COL_GT "); break;
11509  case NFA_COL_LT:
11510    STRCPY(code, "NFA_COL_LT "); break;
11511  case NFA_VCOL:
11512    STRCPY(code, "NFA_VCOL "); break;
11513  case NFA_VCOL_GT:
11514    STRCPY(code, "NFA_VCOL_GT "); break;
11515  case NFA_VCOL_LT:
11516    STRCPY(code, "NFA_VCOL_LT "); break;
11517  case NFA_MARK:
11518    STRCPY(code, "NFA_MARK "); break;
11519  case NFA_MARK_GT:
11520    STRCPY(code, "NFA_MARK_GT "); break;
11521  case NFA_MARK_LT:
11522    STRCPY(code, "NFA_MARK_LT "); break;
11523  case NFA_CURSOR:
11524    STRCPY(code, "NFA_CURSOR "); break;
11525  case NFA_VISUAL:
11526    STRCPY(code, "NFA_VISUAL "); break;
11527  case NFA_ANY_COMPOSING:
11528    STRCPY(code, "NFA_ANY_COMPOSING "); break;
11529
11530  case NFA_STAR:
11531    STRCPY(code, "NFA_STAR "); break;
11532  case NFA_STAR_NONGREEDY:
11533    STRCPY(code, "NFA_STAR_NONGREEDY "); break;
11534  case NFA_QUEST:
11535    STRCPY(code, "NFA_QUEST"); break;
11536  case NFA_QUEST_NONGREEDY:
11537    STRCPY(code, "NFA_QUEST_NON_GREEDY"); break;
11538  case NFA_EMPTY:
11539    STRCPY(code, "NFA_EMPTY"); break;
11540  case NFA_OR:
11541    STRCPY(code, "NFA_OR"); break;
11542
11543  case NFA_START_COLL:
11544    STRCPY(code, "NFA_START_COLL"); break;
11545  case NFA_END_COLL:
11546    STRCPY(code, "NFA_END_COLL"); break;
11547  case NFA_START_NEG_COLL:
11548    STRCPY(code, "NFA_START_NEG_COLL"); break;
11549  case NFA_END_NEG_COLL:
11550    STRCPY(code, "NFA_END_NEG_COLL"); break;
11551  case NFA_RANGE:
11552    STRCPY(code, "NFA_RANGE"); break;
11553  case NFA_RANGE_MIN:
11554    STRCPY(code, "NFA_RANGE_MIN"); break;
11555  case NFA_RANGE_MAX:
11556    STRCPY(code, "NFA_RANGE_MAX"); break;
11557
11558  case NFA_CLASS_ALNUM:
11559    STRCPY(code, "NFA_CLASS_ALNUM"); break;
11560  case NFA_CLASS_ALPHA:
11561    STRCPY(code, "NFA_CLASS_ALPHA"); break;
11562  case NFA_CLASS_BLANK:
11563    STRCPY(code, "NFA_CLASS_BLANK"); break;
11564  case NFA_CLASS_CNTRL:
11565    STRCPY(code, "NFA_CLASS_CNTRL"); break;
11566  case NFA_CLASS_DIGIT:
11567    STRCPY(code, "NFA_CLASS_DIGIT"); break;
11568  case NFA_CLASS_GRAPH:
11569    STRCPY(code, "NFA_CLASS_GRAPH"); break;
11570  case NFA_CLASS_LOWER:
11571    STRCPY(code, "NFA_CLASS_LOWER"); break;
11572  case NFA_CLASS_PRINT:
11573    STRCPY(code, "NFA_CLASS_PRINT"); break;
11574  case NFA_CLASS_PUNCT:
11575    STRCPY(code, "NFA_CLASS_PUNCT"); break;
11576  case NFA_CLASS_SPACE:
11577    STRCPY(code, "NFA_CLASS_SPACE"); break;
11578  case NFA_CLASS_UPPER:
11579    STRCPY(code, "NFA_CLASS_UPPER"); break;
11580  case NFA_CLASS_XDIGIT:
11581    STRCPY(code, "NFA_CLASS_XDIGIT"); break;
11582  case NFA_CLASS_TAB:
11583    STRCPY(code, "NFA_CLASS_TAB"); break;
11584  case NFA_CLASS_RETURN:
11585    STRCPY(code, "NFA_CLASS_RETURN"); break;
11586  case NFA_CLASS_BACKSPACE:
11587    STRCPY(code, "NFA_CLASS_BACKSPACE"); break;
11588  case NFA_CLASS_ESCAPE:
11589    STRCPY(code, "NFA_CLASS_ESCAPE"); break;
11590  case NFA_CLASS_IDENT:
11591    STRCPY(code, "NFA_CLASS_IDENT"); break;
11592  case NFA_CLASS_KEYWORD:
11593    STRCPY(code, "NFA_CLASS_KEYWORD"); break;
11594  case NFA_CLASS_FNAME:
11595    STRCPY(code, "NFA_CLASS_FNAME"); break;
11596
11597  case NFA_ANY:
11598    STRCPY(code, "NFA_ANY"); break;
11599  case NFA_IDENT:
11600    STRCPY(code, "NFA_IDENT"); break;
11601  case NFA_SIDENT:
11602    STRCPY(code, "NFA_SIDENT"); break;
11603  case NFA_KWORD:
11604    STRCPY(code, "NFA_KWORD"); break;
11605  case NFA_SKWORD:
11606    STRCPY(code, "NFA_SKWORD"); break;
11607  case NFA_FNAME:
11608    STRCPY(code, "NFA_FNAME"); break;
11609  case NFA_SFNAME:
11610    STRCPY(code, "NFA_SFNAME"); break;
11611  case NFA_PRINT:
11612    STRCPY(code, "NFA_PRINT"); break;
11613  case NFA_SPRINT:
11614    STRCPY(code, "NFA_SPRINT"); break;
11615  case NFA_WHITE:
11616    STRCPY(code, "NFA_WHITE"); break;
11617  case NFA_NWHITE:
11618    STRCPY(code, "NFA_NWHITE"); break;
11619  case NFA_DIGIT:
11620    STRCPY(code, "NFA_DIGIT"); break;
11621  case NFA_NDIGIT:
11622    STRCPY(code, "NFA_NDIGIT"); break;
11623  case NFA_HEX:
11624    STRCPY(code, "NFA_HEX"); break;
11625  case NFA_NHEX:
11626    STRCPY(code, "NFA_NHEX"); break;
11627  case NFA_OCTAL:
11628    STRCPY(code, "NFA_OCTAL"); break;
11629  case NFA_NOCTAL:
11630    STRCPY(code, "NFA_NOCTAL"); break;
11631  case NFA_WORD:
11632    STRCPY(code, "NFA_WORD"); break;
11633  case NFA_NWORD:
11634    STRCPY(code, "NFA_NWORD"); break;
11635  case NFA_HEAD:
11636    STRCPY(code, "NFA_HEAD"); break;
11637  case NFA_NHEAD:
11638    STRCPY(code, "NFA_NHEAD"); break;
11639  case NFA_ALPHA:
11640    STRCPY(code, "NFA_ALPHA"); break;
11641  case NFA_NALPHA:
11642    STRCPY(code, "NFA_NALPHA"); break;
11643  case NFA_LOWER:
11644    STRCPY(code, "NFA_LOWER"); break;
11645  case NFA_NLOWER:
11646    STRCPY(code, "NFA_NLOWER"); break;
11647  case NFA_UPPER:
11648    STRCPY(code, "NFA_UPPER"); break;
11649  case NFA_NUPPER:
11650    STRCPY(code, "NFA_NUPPER"); break;
11651  case NFA_LOWER_IC:
11652    STRCPY(code, "NFA_LOWER_IC"); break;
11653  case NFA_NLOWER_IC:
11654    STRCPY(code, "NFA_NLOWER_IC"); break;
11655  case NFA_UPPER_IC:
11656    STRCPY(code, "NFA_UPPER_IC"); break;
11657  case NFA_NUPPER_IC:
11658    STRCPY(code, "NFA_NUPPER_IC"); break;
11659
11660  default:
11661    STRCPY(code, "CHAR(x)");
11662    code[5] = c;
11663  }
11664
11665  if (addnl == true) {
11666    strcat(code, " + NEWLINE ");
11667  }
11668}
11669
11670static FILE *log_fd;
11671static const uint8_t e_log_open_failed[] =
11672  N_("Could not open temporary log file for writing, displaying on stderr... ");
11673
11674// Print the postfix notation of the current regexp.
11675static void nfa_postfix_dump(uint8_t *expr, int retval)
11676{
11677  int *p;
11678  FILE *f;
11679
11680  f = fopen(NFA_REGEXP_DUMP_LOG, "a");
11681  if (f == NULL) {
11682    return;
11683  }
11684
11685  fprintf(f, "\n-------------------------\n");
11686  if (retval == FAIL) {
11687    fprintf(f, ">>> NFA engine failed... \n");
11688  } else if (retval == OK) {
11689    fprintf(f, ">>> NFA engine succeeded !\n");
11690  }
11691  fprintf(f, "Regexp: \"%s\"\nPostfix notation (char): \"", expr);
11692  for (p = post_start; *p && p < post_ptr; p++) {
11693    nfa_set_code(*p);
11694    fprintf(f, "%s, ", code);
11695  }
11696  fprintf(f, "\"\nPostfix notation (int): ");
11697  for (p = post_start; *p && p < post_ptr; p++) {
11698    fprintf(f, "%d ", *p);
11699  }
11700  fprintf(f, "\n\n");
11701  fclose(f);
11702}
11703
11704// Print the NFA starting with a root node "state".
11705static void nfa_print_state(FILE *debugf, nfa_state_T *state)
11706{
11707  garray_T indent;
11708
11709  ga_init(&indent, 1, 64);
11710  ga_append(&indent, NUL);
11711  nfa_print_state2(debugf, state, &indent);
11712  ga_clear(&indent);
11713}
11714
11715static void nfa_print_state2(FILE *debugf, nfa_state_T *state, garray_T *indent)
11716{
11717  uint8_t *p;
11718
11719  if (state == NULL) {
11720    return;
11721  }
11722
11723  fprintf(debugf, "(%2d)", abs(state->id));
11724
11725  // Output indent
11726  p = (uint8_t *)indent->ga_data;
11727  if (indent->ga_len >= 3) {
11728    int last = indent->ga_len - 3;
11729    uint8_t save[2];
11730
11731    strncpy(save, &p[last], 2);  // NOLINT(runtime/printf)
11732    memcpy(&p[last], "+-", 2);
11733    fprintf(debugf, " %s", p);
11734    strncpy(&p[last], save, 2);  // NOLINT(runtime/printf)
11735  } else {
11736    fprintf(debugf, " %s", p);
11737  }
11738
11739  nfa_set_code(state->c);
11740  fprintf(debugf, "%s (%d) (id=%d) val=%d\n",
11741          code,
11742          state->c,
11743          abs(state->id),
11744          state->val);
11745  if (state->id < 0) {
11746    return;
11747  }
11748
11749  state->id = abs(state->id) * -1;
11750
11751  // grow indent for state->out
11752  indent->ga_len -= 1;
11753  if (state->out1) {
11754    GA_CONCAT_LITERAL(indent, "| ");
11755  } else {
11756    GA_CONCAT_LITERAL(indent, "  ");
11757  }
11758  ga_append(indent, NUL);
11759
11760  nfa_print_state2(debugf, state->out, indent);
11761
11762  // replace last part of indent for state->out1
11763  indent->ga_len -= 3;
11764  GA_CONCAT_LITERAL(indent, "  ");
11765  ga_append(indent, NUL);
11766
11767  nfa_print_state2(debugf, state->out1, indent);
11768
11769  // shrink indent
11770  indent->ga_len -= 3;
11771  ga_append(indent, NUL);
11772}
11773
11774// Print the NFA state machine.
11775static void nfa_dump(nfa_regprog_T *prog)
11776{
11777  FILE *debugf = fopen(NFA_REGEXP_DUMP_LOG, "a");
11778
11779  if (debugf == NULL) {
11780    return;
11781  }
11782
11783  nfa_print_state(debugf, prog->start);
11784
11785  if (prog->reganch) {
11786    fprintf(debugf, "reganch: %d\n", prog->reganch);
11787  }
11788  if (prog->regstart != NUL) {
11789    fprintf(debugf, "regstart: %c (decimal: %d)\n",
11790            prog->regstart, prog->regstart);
11791  }
11792  if (prog->match_text != NULL) {
11793    fprintf(debugf, "match_text: \"%s\"\n", prog->match_text);
11794  }
11795
11796  fclose(debugf);
11797}
11798#endif  // REGEXP_DEBUG
11799
11800// Parse r.e. @expr and convert it into postfix form.
11801// Return the postfix string on success, NULL otherwise.
11802static int *re2post(void)
11803{
11804  if (nfa_reg(REG_NOPAREN) == FAIL) {
11805    return NULL;
11806  }
11807  EMIT(NFA_MOPEN);
11808  return post_start;
11809}
11810
11811// NB. Some of the code below is inspired by Russ's.
11812
11813// Represents an NFA state plus zero or one or two arrows exiting.
11814// if c == MATCH, no arrows out; matching state.
11815// If c == SPLIT, unlabeled arrows to out and out1 (if != NULL).
11816// If c < 256, labeled arrow with character c to out.
11817
11818static nfa_state_T *state_ptr;  // points to nfa_prog->state
11819
11820// Allocate and initialize nfa_state_T.
11821static nfa_state_T *alloc_state(int c, nfa_state_T *out, nfa_state_T *out1)
11822{
11823  nfa_state_T *s;
11824
11825  if (istate >= nstate) {
11826    return NULL;
11827  }
11828
11829  s = &state_ptr[istate++];
11830
11831  s->c = c;
11832  s->out = out;
11833  s->out1 = out1;
11834  s->val = 0;
11835
11836  s->id = istate;
11837  s->lastlist[0] = 0;
11838  s->lastlist[1] = 0;
11839
11840  return s;
11841}
11842
11843// Reused across compilations by post2nfa(); freed in free_regexp_stuff().
11844static Frag_T *nfa_stack;
11845static int nfa_stack_len;
11846
11847// A partially built NFA without the matching state filled in.
11848// Frag_T.start points at the start state.
11849// Frag_T.out is a list of places that need to be set to the
11850// next state for this fragment.
11851
11852// Initialize a Frag_T struct and return it.
11853static Frag_T frag(nfa_state_T *start, Ptrlist *out)
11854{
11855  Frag_T n;
11856
11857  n.start = start;
11858  n.out = out;
11859  return n;
11860}
11861
11862// Create singleton list containing just outp.
11863static Ptrlist *list1(nfa_state_T **outp)
11864{
11865  Ptrlist *l;
11866
11867  l = (Ptrlist *)outp;
11868  l->next = NULL;
11869  return l;
11870}
11871
11872// Patch the list of states at out to point to start.
11873static void patch(Ptrlist *l, nfa_state_T *s)
11874{
11875  Ptrlist *next;
11876
11877  for (; l; l = next) {
11878    next = l->next;
11879    l->s = s;
11880  }
11881}
11882
11883// Join the two lists l1 and l2, returning the combination.
11884static Ptrlist *append(Ptrlist *l1, Ptrlist *l2)
11885{
11886  Ptrlist *oldl1;
11887
11888  oldl1 = l1;
11889  while (l1->next) {
11890    l1 = l1->next;
11891  }
11892  l1->next = l2;
11893  return oldl1;
11894}
11895
11896// Stack used for transforming postfix form into NFA.
11897static Frag_T empty;
11898
11899static void st_error(int *postfix, int *end, int *p)
11900{
11901#ifdef NFA_REGEXP_ERROR_LOG
11902  FILE *df;
11903  int *p2;
11904
11905  df = fopen(NFA_REGEXP_ERROR_LOG, "a");
11906  if (df) {
11907    fprintf(df, "Error popping the stack!\n");
11908# ifdef REGEXP_DEBUG
11909    fprintf(df, "Current regexp is \"%s\"\n", nfa_regengine.expr);
11910# endif
11911    fprintf(df, "Postfix form is: ");
11912# ifdef REGEXP_DEBUG
11913    for (p2 = postfix; p2 < end; p2++) {
11914      nfa_set_code(*p2);
11915      fprintf(df, "%s, ", code);
11916    }
11917    nfa_set_code(*p);
11918    fprintf(df, "\nCurrent position is: ");
11919    for (p2 = postfix; p2 <= p; p2++) {
11920      nfa_set_code(*p2);
11921      fprintf(df, "%s, ", code);
11922    }
11923# else
11924    for (p2 = postfix; p2 < end; p2++) {
11925      fprintf(df, "%d, ", *p2);
11926    }
11927    fprintf(df, "\nCurrent position is: ");
11928    for (p2 = postfix; p2 <= p; p2++) {
11929      fprintf(df, "%d, ", *p2);
11930    }
11931# endif
11932    fprintf(df, "\n--------------------------\n");
11933    fclose(df);
11934  }
11935#endif
11936  emsg(_("E874: (NFA) Could not pop the stack!"));
11937}
11938
11939// Push an item onto the stack.
11940static void st_push(Frag_T s, Frag_T **p, Frag_T *stack_end)
11941{
11942  Frag_T *stackp = *p;
11943
11944  if (stackp >= stack_end) {
11945    return;
11946  }
11947  *stackp = s;
11948  *p = *p + 1;
11949}
11950
11951// Pop an item from the stack.
11952static Frag_T st_pop(Frag_T **p, Frag_T *stack)
11953{
11954  Frag_T *stackp;
11955
11956  *p = *p - 1;
11957  stackp = *p;
11958  if (stackp < stack) {
11959    return empty;
11960  }
11961  return **p;
11962}
11963
11964// Estimate the maximum byte length of anything matching "state".
11965// When unknown or unlimited return -1.
11966static int nfa_max_width(nfa_state_T *startstate, int depth)
11967{
11968  int l, r;
11969  nfa_state_T *state = startstate;
11970  int len = 0;
11971
11972  // detect looping in a NFA_SPLIT
11973  if (depth > 4) {
11974    return -1;
11975  }
11976
11977  while (state != NULL) {
11978    switch (state->c) {
11979    case NFA_END_INVISIBLE:
11980    case NFA_END_INVISIBLE_NEG:
11981      // the end, return what we have
11982      return len;
11983
11984    case NFA_SPLIT:
11985      // two alternatives, use the maximum
11986      l = nfa_max_width(state->out, depth + 1);
11987      r = nfa_max_width(state->out1, depth + 1);
11988      if (l < 0 || r < 0) {
11989        return -1;
11990      }
11991      return len + (l > r ? l : r);
11992
11993    case NFA_ANY:
11994    case NFA_START_COLL:
11995    case NFA_START_NEG_COLL:
11996      // Matches some character, including composing chars.
11997      len += MB_MAXBYTES;
11998      if (state->c != NFA_ANY) {
11999        // Skip over the compiled collection.
12000        // malformed NFAs must not crash width estimation.
12001        if (state->out1 == NULL || state->out1->out == NULL) {
12002          return -1;
12003        }
12004        state = state->out1->out;
12005        continue;
12006      }
12007      break;
12008
12009    case NFA_DIGIT:
12010    case NFA_WHITE:
12011    case NFA_HEX:
12012    case NFA_OCTAL:
12013      // ascii
12014      len++;
12015      break;
12016
12017    case NFA_IDENT:
12018    case NFA_SIDENT:
12019    case NFA_KWORD:
12020    case NFA_SKWORD:
12021    case NFA_FNAME:
12022    case NFA_SFNAME:
12023    case NFA_PRINT:
12024    case NFA_SPRINT:
12025    case NFA_NWHITE:
12026    case NFA_NDIGIT:
12027    case NFA_NHEX:
12028    case NFA_NOCTAL:
12029    case NFA_WORD:
12030    case NFA_NWORD:
12031    case NFA_HEAD:
12032    case NFA_NHEAD:
12033    case NFA_ALPHA:
12034    case NFA_NALPHA:
12035    case NFA_LOWER:
12036    case NFA_NLOWER:
12037    case NFA_UPPER:
12038    case NFA_NUPPER:
12039    case NFA_LOWER_IC:
12040    case NFA_NLOWER_IC:
12041    case NFA_UPPER_IC:
12042    case NFA_NUPPER_IC:
12043    case NFA_ANY_COMPOSING:
12044      // possibly non-ascii
12045      len += 3;
12046      break;
12047
12048    case NFA_START_INVISIBLE:
12049    case NFA_START_INVISIBLE_NEG:
12050    case NFA_START_INVISIBLE_BEFORE:
12051    case NFA_START_INVISIBLE_BEFORE_NEG:
12052      // zero-width, out1 points to the END state
12053      state = state->out1->out;
12054      continue;
12055
12056    case NFA_BACKREF1:
12057    case NFA_BACKREF2:
12058    case NFA_BACKREF3:
12059    case NFA_BACKREF4:
12060    case NFA_BACKREF5:
12061    case NFA_BACKREF6:
12062    case NFA_BACKREF7:
12063    case NFA_BACKREF8:
12064    case NFA_BACKREF9:
12065    case NFA_ZREF1:
12066    case NFA_ZREF2:
12067    case NFA_ZREF3:
12068    case NFA_ZREF4:
12069    case NFA_ZREF5:
12070    case NFA_ZREF6:
12071    case NFA_ZREF7:
12072    case NFA_ZREF8:
12073    case NFA_ZREF9:
12074    case NFA_NEWL:
12075    case NFA_SKIP:
12076      // unknown width
12077      return -1;
12078
12079    case NFA_BOL:
12080    case NFA_EOL:
12081    case NFA_BOF:
12082    case NFA_EOF:
12083    case NFA_BOW:
12084    case NFA_EOW:
12085    case NFA_MOPEN:
12086    case NFA_MOPEN1:
12087    case NFA_MOPEN2:
12088    case NFA_MOPEN3:
12089    case NFA_MOPEN4:
12090    case NFA_MOPEN5:
12091    case NFA_MOPEN6:
12092    case NFA_MOPEN7:
12093    case NFA_MOPEN8:
12094    case NFA_MOPEN9:
12095    case NFA_ZOPEN:
12096    case NFA_ZOPEN1:
12097    case NFA_ZOPEN2:
12098    case NFA_ZOPEN3:
12099    case NFA_ZOPEN4:
12100    case NFA_ZOPEN5:
12101    case NFA_ZOPEN6:
12102    case NFA_ZOPEN7:
12103    case NFA_ZOPEN8:
12104    case NFA_ZOPEN9:
12105    case NFA_ZCLOSE:
12106    case NFA_ZCLOSE1:
12107    case NFA_ZCLOSE2:
12108    case NFA_ZCLOSE3:
12109    case NFA_ZCLOSE4:
12110    case NFA_ZCLOSE5:
12111    case NFA_ZCLOSE6:
12112    case NFA_ZCLOSE7:
12113    case NFA_ZCLOSE8:
12114    case NFA_ZCLOSE9:
12115    case NFA_MCLOSE:
12116    case NFA_MCLOSE1:
12117    case NFA_MCLOSE2:
12118    case NFA_MCLOSE3:
12119    case NFA_MCLOSE4:
12120    case NFA_MCLOSE5:
12121    case NFA_MCLOSE6:
12122    case NFA_MCLOSE7:
12123    case NFA_MCLOSE8:
12124    case NFA_MCLOSE9:
12125    case NFA_NOPEN:
12126    case NFA_NCLOSE:
12127
12128    case NFA_LNUM_GT:
12129    case NFA_LNUM_LT:
12130    case NFA_COL_GT:
12131    case NFA_COL_LT:
12132    case NFA_VCOL_GT:
12133    case NFA_VCOL_LT:
12134    case NFA_MARK_GT:
12135    case NFA_MARK_LT:
12136    case NFA_VISUAL:
12137    case NFA_LNUM:
12138    case NFA_CURSOR:
12139    case NFA_COL:
12140    case NFA_VCOL:
12141    case NFA_MARK:
12142
12143    case NFA_ZSTART:
12144    case NFA_ZEND:
12145    case NFA_OPT_CHARS:
12146    case NFA_EMPTY:
12147    case NFA_START_PATTERN:
12148    case NFA_END_PATTERN:
12149    case NFA_COMPOSING:
12150    case NFA_END_COMPOSING:
12151      // zero-width
12152      break;
12153
12154    default:
12155      if (state->c < 0) {
12156        // don't know what this is
12157        return -1;
12158      }
12159      // normal character
12160      len += utf_char2len(state->c);
12161      break;
12162    }
12163
12164    // normal way to continue
12165    state = state->out;
12166  }
12167
12168  // unrecognized, "cannot happen"
12169  return -1;
12170}
12171
12172// Convert a postfix form into its equivalent NFA.
12173// Return the NFA start state on success, NULL otherwise.
12174static nfa_state_T *post2nfa(int *postfix, int *end, int nfa_calc_size)
12175{
12176  int *p;
12177  int mopen;
12178  int mclose;
12179  Frag_T *stack = NULL;
12180  Frag_T *stackp = NULL;
12181  Frag_T *stack_end = NULL;
12182  Frag_T e1;
12183  Frag_T e2;
12184  Frag_T e;
12185  nfa_state_T *s;
12186  nfa_state_T *s1;
12187  nfa_state_T *matchstate;
12188  nfa_state_T *ret = NULL;
12189
12190  if (postfix == NULL) {
12191    return NULL;
12192  }
12193
12194#define PUSH(s)     st_push((s), &stackp, stack_end)
12195#define POP()       st_pop(&stackp, stack); \
12196  if (stackp < stack) { \
12197    st_error(postfix, end, p); \
12198    return NULL; \
12199  }
12200
12201  if (nfa_calc_size == false) {
12202    // Reuse the fragment stack across compilations, growing when needed;
12203    // it is freed in free_regexp_stuff().
12204    if (nfa_stack == NULL || nfa_stack_len < nstate + 1) {
12205      xfree(nfa_stack);
12206      nfa_stack = xmalloc((size_t)(nstate + 1) * sizeof(Frag_T));
12207      nfa_stack_len = nstate + 1;
12208    }
12209    stack = nfa_stack;
12210    stackp = stack;
12211    stack_end = stack + (nstate + 1);
12212  }
12213
12214  for (p = postfix; p < end; p++) {
12215    switch (*p) {
12216    case NFA_CONCAT:
12217      // Concatenation.
12218      // Pay attention: this operator does not exist in the r.e. itself
12219      // (it is implicit, really).  It is added when r.e. is translated
12220      // to postfix form in re2post().
12221      if (nfa_calc_size == true) {
12222        // nstate += 0;
12223        break;
12224      }
12225      e2 = POP();
12226      e1 = POP();
12227      patch(e1.out, e2.start);
12228      PUSH(frag(e1.start, e2.out));
12229      break;
12230
12231    case NFA_OR:
12232      // Alternation
12233      if (nfa_calc_size == true) {
12234        nstate++;
12235        break;
12236      }
12237      e2 = POP();
12238      e1 = POP();
12239      s = alloc_state(NFA_SPLIT, e1.start, e2.start);
12240      if (s == NULL) {
12241        goto theend;
12242      }
12243      PUSH(frag(s, append(e1.out, e2.out)));
12244      break;
12245
12246    case NFA_STAR:
12247      // Zero or more, prefer more
12248      if (nfa_calc_size == true) {
12249        nstate++;
12250        break;
12251      }
12252      e = POP();
12253      s = alloc_state(NFA_SPLIT, e.start, NULL);
12254      if (s == NULL) {
12255        goto theend;
12256      }
12257      patch(e.out, s);
12258      PUSH(frag(s, list1(&s->out1)));
12259      break;
12260
12261    case NFA_STAR_NONGREEDY:
12262      // Zero or more, prefer zero
12263      if (nfa_calc_size == true) {
12264        nstate++;
12265        break;
12266      }
12267      e = POP();
12268      s = alloc_state(NFA_SPLIT, NULL, e.start);
12269      if (s == NULL) {
12270        goto theend;
12271      }
12272      patch(e.out, s);
12273      PUSH(frag(s, list1(&s->out)));
12274      break;
12275
12276    case NFA_QUEST:
12277      // one or zero atoms=> greedy match
12278      if (nfa_calc_size == true) {
12279        nstate++;
12280        break;
12281      }
12282      e = POP();
12283      s = alloc_state(NFA_SPLIT, e.start, NULL);
12284      if (s == NULL) {
12285        goto theend;
12286      }
12287      PUSH(frag(s, append(e.out, list1(&s->out1))));
12288      break;
12289
12290    case NFA_QUEST_NONGREEDY:
12291      // zero or one atoms => non-greedy match
12292      if (nfa_calc_size == true) {
12293        nstate++;
12294        break;
12295      }
12296      e = POP();
12297      s = alloc_state(NFA_SPLIT, NULL, e.start);
12298      if (s == NULL) {
12299        goto theend;
12300      }
12301      PUSH(frag(s, append(e.out, list1(&s->out))));
12302      break;
12303
12304    case NFA_END_COLL:
12305    case NFA_END_NEG_COLL:
12306      // On the stack is the sequence starting with NFA_START_COLL or
12307      // NFA_START_NEG_COLL and all possible characters. Patch it to
12308      // add the output to the start.
12309      if (nfa_calc_size == true) {
12310        nstate++;
12311        break;
12312      }
12313      e = POP();
12314      s = alloc_state(NFA_END_COLL, NULL, NULL);
12315      if (s == NULL) {
12316        goto theend;
12317      }
12318      patch(e.out, s);
12319      e.start->out1 = s;
12320      PUSH(frag(e.start, list1(&s->out)));
12321      break;
12322
12323    case NFA_RANGE:
12324      // Before this are two characters, the low and high end of a
12325      // range.  Turn them into two states with MIN and MAX.
12326      if (nfa_calc_size == true) {
12327        // nstate += 0;
12328        break;
12329      }
12330      e2 = POP();
12331      e1 = POP();
12332      e2.start->val = e2.start->c;
12333      e2.start->c = NFA_RANGE_MAX;
12334      e1.start->val = e1.start->c;
12335      e1.start->c = NFA_RANGE_MIN;
12336      patch(e1.out, e2.start);
12337      PUSH(frag(e1.start, e2.out));
12338      break;
12339
12340    case NFA_EMPTY:
12341      // 0-length, used in a repetition with max/min count of 0
12342      if (nfa_calc_size == true) {
12343        nstate++;
12344        break;
12345      }
12346      s = alloc_state(NFA_EMPTY, NULL, NULL);
12347      if (s == NULL) {
12348        goto theend;
12349      }
12350      PUSH(frag(s, list1(&s->out)));
12351      break;
12352
12353    case NFA_OPT_CHARS: {
12354      int n;
12355
12356      // \%[abc] implemented as:
12357      //    NFA_SPLIT
12358      //    +-CHAR(a)
12359      //    | +-NFA_SPLIT
12360      //    |   +-CHAR(b)
12361      //    |   | +-NFA_SPLIT
12362      //    |   |   +-CHAR(c)
12363      //    |   |   | +-next
12364      //    |   |   +- next
12365      //    |   +- next
12366      //    +- next
12367      n = *++p;  // get number of characters
12368      if (nfa_calc_size == true) {
12369        nstate += n;
12370        break;
12371      }
12372      s = NULL;       // avoid compiler warning
12373      e1.out = NULL;       // stores list with out1's
12374      s1 = NULL;       // previous NFA_SPLIT to connect to
12375      while (n-- > 0) {
12376        e = POP();         // get character
12377        s = alloc_state(NFA_SPLIT, e.start, NULL);
12378        if (s == NULL) {
12379          goto theend;
12380        }
12381        if (e1.out == NULL) {
12382          e1 = e;
12383        }
12384        patch(e.out, s1);
12385        append(e1.out, list1(&s->out1));
12386        s1 = s;
12387      }
12388      PUSH(frag(s, e1.out));
12389      break;
12390    }
12391
12392    case NFA_PREV_ATOM_NO_WIDTH:
12393    case NFA_PREV_ATOM_NO_WIDTH_NEG:
12394    case NFA_PREV_ATOM_JUST_BEFORE:
12395    case NFA_PREV_ATOM_JUST_BEFORE_NEG:
12396    case NFA_PREV_ATOM_LIKE_PATTERN: {
12397      int before = (*p == NFA_PREV_ATOM_JUST_BEFORE
12398                    || *p == NFA_PREV_ATOM_JUST_BEFORE_NEG);
12399      int pattern = (*p == NFA_PREV_ATOM_LIKE_PATTERN);
12400      int start_state;
12401      int end_state;
12402      int n = 0;
12403      nfa_state_T *zend;
12404      nfa_state_T *skip;
12405
12406      switch (*p) {
12407      case NFA_PREV_ATOM_NO_WIDTH:
12408        start_state = NFA_START_INVISIBLE;
12409        end_state = NFA_END_INVISIBLE;
12410        break;
12411      case NFA_PREV_ATOM_NO_WIDTH_NEG:
12412        start_state = NFA_START_INVISIBLE_NEG;
12413        end_state = NFA_END_INVISIBLE_NEG;
12414        break;
12415      case NFA_PREV_ATOM_JUST_BEFORE:
12416        start_state = NFA_START_INVISIBLE_BEFORE;
12417        end_state = NFA_END_INVISIBLE;
12418        break;
12419      case NFA_PREV_ATOM_JUST_BEFORE_NEG:
12420        start_state = NFA_START_INVISIBLE_BEFORE_NEG;
12421        end_state = NFA_END_INVISIBLE_NEG;
12422        break;
12423      default:           // NFA_PREV_ATOM_LIKE_PATTERN:
12424        start_state = NFA_START_PATTERN;
12425        end_state = NFA_END_PATTERN;
12426        break;
12427      }
12428
12429      if (before) {
12430        n = *++p;         // get the count
12431      }
12432      // The \@= operator: match the preceding atom with zero width.
12433      // The \@! operator: no match for the preceding atom.
12434      // The \@<= operator: match for the preceding atom.
12435      // The \@<! operator: no match for the preceding atom.
12436      // Surrounds the preceding atom with START_INVISIBLE and
12437      // END_INVISIBLE, similarly to MOPEN.
12438
12439      if (nfa_calc_size == true) {
12440        nstate += pattern ? 4 : 2;
12441        break;
12442      }
12443      e = POP();
12444      s1 = alloc_state(end_state, NULL, NULL);
12445      if (s1 == NULL) {
12446        goto theend;
12447      }
12448
12449      s = alloc_state(start_state, e.start, s1);
12450      if (s == NULL) {
12451        goto theend;
12452      }
12453      if (pattern) {
12454        // NFA_ZEND -> NFA_END_PATTERN -> NFA_SKIP -> what follows.
12455        skip = alloc_state(NFA_SKIP, NULL, NULL);
12456        if (skip == NULL) {
12457          goto theend;
12458        }
12459        zend = alloc_state(NFA_ZEND, s1, NULL);
12460        if (zend == NULL) {
12461          goto theend;
12462        }
12463        s1->out = skip;
12464        patch(e.out, zend);
12465        PUSH(frag(s, list1(&skip->out)));
12466      } else {
12467        patch(e.out, s1);
12468        PUSH(frag(s, list1(&s1->out)));
12469        if (before) {
12470          if (n <= 0) {
12471            // See if we can guess the maximum width, it avoids a
12472            // lot of pointless tries.
12473            n = nfa_max_width(e.start, 0);
12474          }
12475          s->val = n;           // store the count
12476        }
12477      }
12478      break;
12479    }
12480
12481    case NFA_COMPOSING:         // char with composing char
12482      FALLTHROUGH;
12483
12484    case NFA_MOPEN:     // \( \) Submatch
12485    case NFA_MOPEN1:
12486    case NFA_MOPEN2:
12487    case NFA_MOPEN3:
12488    case NFA_MOPEN4:
12489    case NFA_MOPEN5:
12490    case NFA_MOPEN6:
12491    case NFA_MOPEN7:
12492    case NFA_MOPEN8:
12493    case NFA_MOPEN9:
12494    case NFA_ZOPEN:     // \z( \) Submatch
12495    case NFA_ZOPEN1:
12496    case NFA_ZOPEN2:
12497    case NFA_ZOPEN3:
12498    case NFA_ZOPEN4:
12499    case NFA_ZOPEN5:
12500    case NFA_ZOPEN6:
12501    case NFA_ZOPEN7:
12502    case NFA_ZOPEN8:
12503    case NFA_ZOPEN9:
12504    case NFA_NOPEN:     // \%( \) "Invisible Submatch"
12505      if (nfa_calc_size == true) {
12506        nstate += 2;
12507        break;
12508      }
12509
12510      mopen = *p;
12511      switch (*p) {
12512      case NFA_NOPEN:
12513        mclose = NFA_NCLOSE; break;
12514      case NFA_ZOPEN:
12515        mclose = NFA_ZCLOSE; break;
12516      case NFA_ZOPEN1:
12517        mclose = NFA_ZCLOSE1; break;
12518      case NFA_ZOPEN2:
12519        mclose = NFA_ZCLOSE2; break;
12520      case NFA_ZOPEN3:
12521        mclose = NFA_ZCLOSE3; break;
12522      case NFA_ZOPEN4:
12523        mclose = NFA_ZCLOSE4; break;
12524      case NFA_ZOPEN5:
12525        mclose = NFA_ZCLOSE5; break;
12526      case NFA_ZOPEN6:
12527        mclose = NFA_ZCLOSE6; break;
12528      case NFA_ZOPEN7:
12529        mclose = NFA_ZCLOSE7; break;
12530      case NFA_ZOPEN8:
12531        mclose = NFA_ZCLOSE8; break;
12532      case NFA_ZOPEN9:
12533        mclose = NFA_ZCLOSE9; break;
12534      case NFA_COMPOSING:
12535        mclose = NFA_END_COMPOSING; break;
12536      default:
12537        // NFA_MOPEN, NFA_MOPEN1 .. NFA_MOPEN9
12538        mclose = *p + NSUBEXP;
12539        break;
12540      }
12541
12542      // Allow "NFA_MOPEN" as a valid postfix representation for
12543      // the empty regexp "". In this case, the NFA will be
12544      // NFA_MOPEN -> NFA_MCLOSE. Note that this also allows
12545      // empty groups of parenthesis, and empty mbyte chars
12546      if (stackp == stack) {
12547        s = alloc_state(mopen, NULL, NULL);
12548        if (s == NULL) {
12549          goto theend;
12550        }
12551        s1 = alloc_state(mclose, NULL, NULL);
12552        if (s1 == NULL) {
12553          goto theend;
12554        }
12555        patch(list1(&s->out), s1);
12556        PUSH(frag(s, list1(&s1->out)));
12557        break;
12558      }
12559
12560      // At least one node was emitted before NFA_MOPEN, so
12561      // at least one node will be between NFA_MOPEN and NFA_MCLOSE
12562      e = POP();
12563      s = alloc_state(mopen, e.start, NULL);         // `('
12564      if (s == NULL) {
12565        goto theend;
12566      }
12567
12568      s1 = alloc_state(mclose, NULL, NULL);         // `)'
12569      if (s1 == NULL) {
12570        goto theend;
12571      }
12572      patch(e.out, s1);
12573
12574      if (mopen == NFA_COMPOSING) {
12575        // COMPOSING->out1 = END_COMPOSING
12576        patch(list1(&s->out1), s1);
12577      }
12578
12579      PUSH(frag(s, list1(&s1->out)));
12580      break;
12581
12582    case NFA_BACKREF1:
12583    case NFA_BACKREF2:
12584    case NFA_BACKREF3:
12585    case NFA_BACKREF4:
12586    case NFA_BACKREF5:
12587    case NFA_BACKREF6:
12588    case NFA_BACKREF7:
12589    case NFA_BACKREF8:
12590    case NFA_BACKREF9:
12591    case NFA_ZREF1:
12592    case NFA_ZREF2:
12593    case NFA_ZREF3:
12594    case NFA_ZREF4:
12595    case NFA_ZREF5:
12596    case NFA_ZREF6:
12597    case NFA_ZREF7:
12598    case NFA_ZREF8:
12599    case NFA_ZREF9:
12600      if (nfa_calc_size == true) {
12601        nstate += 2;
12602        break;
12603      }
12604      s = alloc_state(*p, NULL, NULL);
12605      if (s == NULL) {
12606        goto theend;
12607      }
12608      s1 = alloc_state(NFA_SKIP, NULL, NULL);
12609      if (s1 == NULL) {
12610        goto theend;
12611      }
12612      patch(list1(&s->out), s1);
12613      PUSH(frag(s, list1(&s1->out)));
12614      break;
12615
12616    case NFA_LNUM:
12617    case NFA_LNUM_GT:
12618    case NFA_LNUM_LT:
12619    case NFA_VCOL:
12620    case NFA_VCOL_GT:
12621    case NFA_VCOL_LT:
12622    case NFA_COL:
12623    case NFA_COL_GT:
12624    case NFA_COL_LT:
12625    case NFA_MARK:
12626    case NFA_MARK_GT:
12627    case NFA_MARK_LT: {
12628      int n = *++p;       // lnum, col or mark name
12629
12630      if (nfa_calc_size == true) {
12631        nstate += 1;
12632        break;
12633      }
12634      s = alloc_state(p[-1], NULL, NULL);
12635      if (s == NULL) {
12636        goto theend;
12637      }
12638      s->val = n;
12639      PUSH(frag(s, list1(&s->out)));
12640      break;
12641    }
12642
12643    case NFA_ZSTART:
12644    case NFA_ZEND:
12645    default:
12646      // Operands
12647      if (nfa_calc_size == true) {
12648        nstate++;
12649        break;
12650      }
12651      s = alloc_state(*p, NULL, NULL);
12652      if (s == NULL) {
12653        goto theend;
12654      }
12655      PUSH(frag(s, list1(&s->out)));
12656      break;
12657    }     // switch(*p)
12658  }   // for(p = postfix; *p; ++p)
12659
12660  if (nfa_calc_size == true) {
12661    nstate++;
12662    goto theend;        // Return value when counting size is ignored anyway
12663  }
12664
12665  e = POP();
12666  if (stackp != stack) {
12667    EMSG_RET_NULL(_("E875: (NFA regexp) (While converting from postfix to NFA),"
12668                    "too many states left on stack"));
12669  }
12670
12671  if (istate >= nstate) {
12672    EMSG_RET_NULL(_("E876: (NFA regexp) "
12673                    "Not enough space to store the whole NFA "));
12674  }
12675
12676  matchstate = &state_ptr[istate++];   // the match state
12677  matchstate->c = NFA_MATCH;
12678  matchstate->out = matchstate->out1 = NULL;
12679  matchstate->id = 0;
12680
12681  patch(e.out, matchstate);
12682  ret = e.start;
12683
12684theend:
12685  return ret;
12686
12687#undef POP1
12688#undef PUSH1
12689#undef POP2
12690#undef PUSH2
12691#undef POP
12692#undef PUSH
12693}
12694
12695// After building the NFA program, inspect it to add optimization hints.
12696static void nfa_postprocess(nfa_regprog_T *prog)
12697{
12698  int i;
12699  int c;
12700
12701  for (i = 0; i < prog->nstate; i++) {
12702    c = prog->state[i].c;
12703    if (c == NFA_START_INVISIBLE
12704        || c == NFA_START_INVISIBLE_NEG
12705        || c == NFA_START_INVISIBLE_BEFORE
12706        || c == NFA_START_INVISIBLE_BEFORE_NEG) {
12707      int directly;
12708
12709      // Do it directly when what follows is possibly the end of the
12710      // match.
12711      if (match_follows(prog->state[i].out1->out, 0)) {
12712        directly = true;
12713      } else {
12714        int ch_invisible = failure_chance(prog->state[i].out, 0);
12715        int ch_follows = failure_chance(prog->state[i].out1->out, 0);
12716
12717        // Postpone when the invisible match is expensive or has a
12718        // lower chance of failing.
12719        if (c == NFA_START_INVISIBLE_BEFORE
12720            || c == NFA_START_INVISIBLE_BEFORE_NEG) {
12721          // "before" matches are very expensive when
12722          // unbounded, always prefer what follows then,
12723          // unless what follows will always match.
12724          // Otherwise strongly prefer what follows.
12725          if (prog->state[i].val <= 0 && ch_follows > 0) {
12726            directly = false;
12727          } else {
12728            directly = ch_follows * 10 < ch_invisible;
12729          }
12730        } else {
12731          // normal invisible, first do the one with the
12732          // highest failure chance
12733          directly = ch_follows < ch_invisible;
12734        }
12735      }
12736      if (directly) {
12737        // switch to the _FIRST state
12738        prog->state[i].c++;
12739      }
12740    }
12741  }
12742}
12743
12744/////////////////////////////////////////////////////////////////
12745// NFA execution code.
12746/////////////////////////////////////////////////////////////////
12747
12748// Values for done in nfa_pim_T.
12749#define NFA_PIM_UNUSED   0      // pim not used
12750#define NFA_PIM_TODO     1      // pim not done yet
12751#define NFA_PIM_MATCH    2      // pim executed, matches
12752#define NFA_PIM_NOMATCH  3      // pim executed, no match
12753
12754#ifdef REGEXP_DEBUG
12755static void log_subsexpr(regsubs_T *subs)
12756{
12757  log_subexpr(&subs->norm);
12758  if (rex.nfa_has_zsubexpr) {
12759    log_subexpr(&subs->synt);
12760  }
12761}
12762
12763static void log_subexpr(regsub_T *sub)
12764{
12765  int j;
12766
12767  for (j = 0; j < sub->in_use; j++) {
12768    if (REG_MULTI) {
12769      fprintf(log_fd, "*** group %d, start: c=%d, l=%d, end: c=%d, l=%d\n",
12770              j,
12771              sub->list.multi[j].start_col,
12772              (int)sub->list.multi[j].start_lnum,
12773              sub->list.multi[j].end_col,
12774              (int)sub->list.multi[j].end_lnum);
12775    } else {
12776      char *s = (char *)sub->list.line[j].start;
12777      char *e = (char *)sub->list.line[j].end;
12778
12779      fprintf(log_fd, "*** group %d, start: \"%s\", end: \"%s\"\n",
12780              j,
12781              s == NULL ? "NULL" : s,
12782              e == NULL ? "NULL" : e);
12783    }
12784  }
12785}
12786
12787static char *pim_info(const nfa_pim_T *pim)
12788{
12789  static char buf[30];
12790
12791  if (pim == NULL || pim->result == NFA_PIM_UNUSED) {
12792    buf[0] = NUL;
12793  } else {
12794    snprintf(buf, sizeof(buf), " PIM col %d",
12795             REG_MULTI
12796             ? (int)pim->end.pos.col
12797             : (int)(pim->end.ptr - rex.input));
12798  }
12799  return buf;
12800}
12801
12802#endif
12803
12804// Used during execution: whether a match has been found.
12805static int nfa_match;
12806static proftime_T *nfa_time_limit;
12807static int *nfa_timed_out;
12808static int nfa_time_count;
12809
12810// Copy postponed invisible match info from "from" to "to".
12811static void copy_pim(nfa_pim_T *to, nfa_pim_T *from)
12812{
12813  to->result = from->result;
12814  to->state = from->state;
12815  copy_sub(&to->subs.norm, &from->subs.norm);
12816  if (rex.nfa_has_zsubexpr) {
12817    copy_sub(&to->subs.synt, &from->subs.synt);
12818  }
12819  to->end = from->end;
12820}
12821
12822static void clear_sub(regsub_T *sub)
12823{
12824  if (REG_MULTI) {
12825    // Use 0xff to set lnum to -1
12826    memset(sub->list.multi, 0xff, sizeof(struct multipos) * (size_t)rex.nfa_nsubexpr);
12827  } else {
12828    memset(sub->list.line, 0, sizeof(struct linepos) * (size_t)rex.nfa_nsubexpr);
12829  }
12830  sub->in_use = 0;
12831}
12832
12833// Copy the submatches from "from" to "to".
12834static inline void copy_sub(regsub_T *to, regsub_T *from)
12835{
12836  to->in_use = from->in_use;
12837  if (from->in_use <= 0) {
12838    return;
12839  }
12840
12841  // Copy the match start and end positions.  addstate() calls this for
12842  // every state it adds, so it is very hot.  Patterns without capturing
12843  // groups only use subexpression zero (the whole match), so special-case
12844  // "in_use == 1" with a direct assignment to avoid the mch_memmove() call.
12845  if (REG_MULTI) {
12846    if (from->in_use == 1) {
12847      to->list.multi[0] = from->list.multi[0];
12848    } else {
12849      memmove(&to->list.multi[0], &from->list.multi[0],
12850              sizeof(struct multipos) * (size_t)from->in_use);
12851    }
12852    to->orig_start_col = from->orig_start_col;
12853  } else {
12854    if (from->in_use == 1) {
12855      to->list.line[0] = from->list.line[0];
12856    } else {
12857      memmove(&to->list.line[0], &from->list.line[0],
12858              sizeof(struct linepos) * (size_t)from->in_use);
12859    }
12860  }
12861}
12862
12863// Like copy_sub() but exclude the main match.
12864static void copy_sub_off(regsub_T *to, regsub_T *from)
12865{
12866  if (to->in_use < from->in_use) {
12867    to->in_use = from->in_use;
12868  }
12869  if (from->in_use <= 1) {
12870    return;
12871  }
12872
12873  // Copy the match start and end positions.
12874  if (REG_MULTI) {
12875    memmove(&to->list.multi[1], &from->list.multi[1],
12876            sizeof(struct multipos) * (size_t)(from->in_use - 1));
12877  } else {
12878    memmove(&to->list.line[1], &from->list.line[1],
12879            sizeof(struct linepos) * (size_t)(from->in_use - 1));
12880  }
12881}
12882
12883// Like copy_sub() but only do the end of the main match if \ze is present.
12884static void copy_ze_off(regsub_T *to, regsub_T *from)
12885{
12886  if (!rex.nfa_has_zend) {
12887    return;
12888  }
12889
12890  if (REG_MULTI) {
12891    if (from->list.multi[0].end_lnum >= 0) {
12892      to->list.multi[0].end_lnum = from->list.multi[0].end_lnum;
12893      to->list.multi[0].end_col = from->list.multi[0].end_col;
12894    }
12895  } else {
12896    if (from->list.line[0].end != NULL) {
12897      to->list.line[0].end = from->list.line[0].end;
12898    }
12899  }
12900}
12901
12902// Return true if "sub1" and "sub2" have the same start positions.
12903// When using back-references also check the end position.
12904static bool sub_equal(regsub_T *sub1, regsub_T *sub2)
12905{
12906  int i;
12907  int todo;
12908  linenr_T s1;
12909  linenr_T s2;
12910  uint8_t *sp1;
12911  uint8_t *sp2;
12912
12913  todo = sub1->in_use > sub2->in_use ? sub1->in_use : sub2->in_use;
12914  if (REG_MULTI) {
12915    for (i = 0; i < todo; i++) {
12916      if (i < sub1->in_use) {
12917        s1 = sub1->list.multi[i].start_lnum;
12918      } else {
12919        s1 = -1;
12920      }
12921      if (i < sub2->in_use) {
12922        s2 = sub2->list.multi[i].start_lnum;
12923      } else {
12924        s2 = -1;
12925      }
12926      if (s1 != s2) {
12927        return false;
12928      }
12929      if (s1 != -1 && sub1->list.multi[i].start_col
12930          != sub2->list.multi[i].start_col) {
12931        return false;
12932      }
12933      if (rex.nfa_has_backref) {
12934        if (i < sub1->in_use) {
12935          s1 = sub1->list.multi[i].end_lnum;
12936        } else {
12937          s1 = -1;
12938        }
12939        if (i < sub2->in_use) {
12940          s2 = sub2->list.multi[i].end_lnum;
12941        } else {
12942          s2 = -1;
12943        }
12944        if (s1 != s2) {
12945          return false;
12946        }
12947        if (s1 != -1
12948            && sub1->list.multi[i].end_col != sub2->list.multi[i].end_col) {
12949          return false;
12950        }
12951      }
12952    }
12953  } else {
12954    for (i = 0; i < todo; i++) {
12955      if (i < sub1->in_use) {
12956        sp1 = sub1->list.line[i].start;
12957      } else {
12958        sp1 = NULL;
12959      }
12960      if (i < sub2->in_use) {
12961        sp2 = sub2->list.line[i].start;
12962      } else {
12963        sp2 = NULL;
12964      }
12965      if (sp1 != sp2) {
12966        return false;
12967      }
12968      if (rex.nfa_has_backref) {
12969        if (i < sub1->in_use) {
12970          sp1 = sub1->list.line[i].end;
12971        } else {
12972          sp1 = NULL;
12973        }
12974        if (i < sub2->in_use) {
12975          sp2 = sub2->list.line[i].end;
12976        } else {
12977          sp2 = NULL;
12978        }
12979        if (sp1 != sp2) {
12980          return false;
12981        }
12982      }
12983    }
12984  }
12985
12986  return true;
12987}
12988
12989#ifdef REGEXP_DEBUG
12990static void open_debug_log(TriState result)
12991{
12992  log_fd = fopen(NFA_REGEXP_RUN_LOG, "a");
12993  if (log_fd == NULL) {
12994    emsg(_(e_log_open_failed));
12995    log_fd = stderr;
12996  }
12997
12998  fprintf(log_fd, "****************************\n");
12999  fprintf(log_fd, "FINISHED RUNNING nfa_regmatch() recursively\n");
13000  fprintf(log_fd, "MATCH = %s\n", result == kTrue ? "OK" : result == kNone ? "MAYBE" : "FALSE");
13001  fprintf(log_fd, "****************************\n");
13002}
13003
13004static void report_state(char *action, regsub_T *sub, nfa_state_T *state, int lid, nfa_pim_T *pim)
13005{
13006  int col;
13007
13008  if (sub->in_use <= 0) {
13009    col = -1;
13010  } else if (REG_MULTI) {
13011    col = sub->list.multi[0].start_col;
13012  } else {
13013    col = (int)(sub->list.line[0].start - rex.line);
13014  }
13015  nfa_set_code(state->c);
13016  if (log_fd == NULL) {
13017    open_debug_log(kNone);
13018  }
13019  fprintf(log_fd, "> %s state %d to list %d. char %d: %s (start col %d)%s\n",
13020          action, abs(state->id), lid, state->c, code, col,
13021          pim_info(pim));
13022}
13023
13024#endif
13025
13026/// @param l      runtime state list
13027/// @param state  state to update
13028/// @param subs   pointers to subexpressions
13029/// @param pim    postponed match or NULL
13030///
13031/// @return  true if the same state is already in list "l" with the same
13032///          positions as "subs".
13033static bool has_state_with_pos(nfa_list_T *l, nfa_state_T *state, regsubs_T *subs, nfa_pim_T *pim)
13034  FUNC_ATTR_NONNULL_ARG(1, 2, 3)
13035{
13036  for (int i = 0; i < l->n; i++) {
13037    nfa_thread_T *thread = &l->t[i];
13038    if (thread->state->id == state->id
13039        && sub_equal(&thread->subs.norm, &subs->norm)
13040        && (!rex.nfa_has_zsubexpr
13041            || sub_equal(&thread->subs.synt, &subs->synt))
13042        && pim_equal(&thread->pim, pim)) {
13043      return true;
13044    }
13045  }
13046  return false;
13047}
13048
13049// Return true if "one" and "two" are equal.  That includes when both are not
13050// set.
13051static bool pim_equal(const nfa_pim_T *one, const nfa_pim_T *two)
13052{
13053  const bool one_unused = (one == NULL || one->result == NFA_PIM_UNUSED);
13054  const bool two_unused = (two == NULL || two->result == NFA_PIM_UNUSED);
13055
13056  if (one_unused) {
13057    // one is unused: equal when two is also unused
13058    return two_unused;
13059  }
13060  if (two_unused) {
13061    // one is used and two is not: not equal
13062    return false;
13063  }
13064  // compare the state id
13065  if (one->state->id != two->state->id) {
13066    return false;
13067  }
13068  // compare the position
13069  if (REG_MULTI) {
13070    return one->end.pos.lnum == two->end.pos.lnum
13071           && one->end.pos.col == two->end.pos.col;
13072  }
13073  return one->end.ptr == two->end.ptr;
13074}
13075
13076// Return true if "state" leads to a NFA_MATCH without advancing the input.
13077static bool match_follows(const nfa_state_T *startstate, int depth)
13078  FUNC_ATTR_NONNULL_ALL
13079{
13080  const nfa_state_T *state = startstate;
13081
13082  // avoid too much recursion
13083  if (depth > 10) {
13084    return false;
13085  }
13086  while (state != NULL) {
13087    switch (state->c) {
13088    case NFA_MATCH:
13089    case NFA_MCLOSE:
13090    case NFA_END_INVISIBLE:
13091    case NFA_END_INVISIBLE_NEG:
13092    case NFA_END_PATTERN:
13093      return true;
13094
13095    case NFA_SPLIT:
13096      return match_follows(state->out, depth + 1)
13097             || match_follows(state->out1, depth + 1);
13098
13099    case NFA_START_INVISIBLE:
13100    case NFA_START_INVISIBLE_FIRST:
13101    case NFA_START_INVISIBLE_BEFORE:
13102    case NFA_START_INVISIBLE_BEFORE_FIRST:
13103    case NFA_START_INVISIBLE_NEG:
13104    case NFA_START_INVISIBLE_NEG_FIRST:
13105    case NFA_START_INVISIBLE_BEFORE_NEG:
13106    case NFA_START_INVISIBLE_BEFORE_NEG_FIRST:
13107    case NFA_COMPOSING:
13108      // skip ahead to next state
13109      state = state->out1->out;
13110      continue;
13111
13112    case NFA_ANY:
13113    case NFA_ANY_COMPOSING:
13114    case NFA_IDENT:
13115    case NFA_SIDENT:
13116    case NFA_KWORD:
13117    case NFA_SKWORD:
13118    case NFA_FNAME:
13119    case NFA_SFNAME:
13120    case NFA_PRINT:
13121    case NFA_SPRINT:
13122    case NFA_WHITE:
13123    case NFA_NWHITE:
13124    case NFA_DIGIT:
13125    case NFA_NDIGIT:
13126    case NFA_HEX:
13127    case NFA_NHEX:
13128    case NFA_OCTAL:
13129    case NFA_NOCTAL:
13130    case NFA_WORD:
13131    case NFA_NWORD:
13132    case NFA_HEAD:
13133    case NFA_NHEAD:
13134    case NFA_ALPHA:
13135    case NFA_NALPHA:
13136    case NFA_LOWER:
13137    case NFA_NLOWER:
13138    case NFA_UPPER:
13139    case NFA_NUPPER:
13140    case NFA_LOWER_IC:
13141    case NFA_NLOWER_IC:
13142    case NFA_UPPER_IC:
13143    case NFA_NUPPER_IC:
13144    case NFA_START_COLL:
13145    case NFA_START_NEG_COLL:
13146    case NFA_NEWL:
13147      // state will advance input
13148      return false;
13149
13150    default:
13151      if (state->c > 0) {
13152        // state will advance input
13153        return false;
13154      }
13155      // Others: zero-width or possibly zero-width, might still find
13156      // a match at the same position, keep looking.
13157      break;
13158    }
13159    state = state->out;
13160  }
13161  return false;
13162}
13163
13164/// @param l      runtime state list
13165/// @param state  state to update
13166/// @param subs   pointers to subexpressions
13167///
13168/// @return  true if "state" is already in list "l".
13169static bool state_in_list(nfa_list_T *l, nfa_state_T *state, regsubs_T *subs)
13170  FUNC_ATTR_NONNULL_ALL
13171{
13172  if (state->lastlist[nfa_ll_index] == l->id) {
13173    if (!rex.nfa_has_backref || has_state_with_pos(l, state, subs, NULL)) {
13174      return true;
13175    }
13176  }
13177  return false;
13178}
13179
13180// Offset used for "off" by addstate_here().
13181#define ADDSTATE_HERE_OFFSET 10
13182
13183/// Add "state" and possibly what follows to state list ".".
13184///
13185/// @param l         runtime state list
13186/// @param state     state to update
13187/// @param subs_arg  pointers to subexpressions
13188/// @param pim       postponed look-behind match
13189/// @param off_arg   byte offset, when -1 go to next line
13190/// @param depth     recursion depth
13191///
13192/// @return  "subs_arg", possibly copied into temp_subs.
13193///          NULL when recursiveness is too deep.
13194static regsubs_T *addstate(nfa_list_T *l, nfa_state_T *state, regsubs_T *subs_arg, nfa_pim_T *pim,
13195                           int off_arg, int depth)
13196  FUNC_ATTR_NONNULL_ARG(1, 2) FUNC_ATTR_WARN_UNUSED_RESULT
13197{
13198  int subidx;
13199  int off = off_arg;
13200  int add_here = false;
13201  int listindex = 0;
13202  int k;
13203  int found = false;
13204  nfa_thread_T *thread;
13205  struct multipos save_multipos;
13206  int save_in_use;
13207  uint8_t *save_ptr;
13208  int i;
13209  regsub_T *sub;
13210  regsubs_T *subs = subs_arg;
13211  static regsubs_T temp_subs;
13212#ifdef REGEXP_DEBUG
13213  int did_print = false;
13214#endif
13215
13216  // This function is called recursively.  When the depth is too much we run
13217  // out of stack and crash, limit recursiveness here.
13218  if (depth >= 5000 || subs == NULL) {
13219    return NULL;
13220  }
13221
13222  if (off_arg <= -ADDSTATE_HERE_OFFSET) {
13223    add_here = true;
13224    off = 0;
13225    listindex = -(off_arg + ADDSTATE_HERE_OFFSET);
13226  }
13227
13228  switch (state->c) {
13229  case NFA_NCLOSE:
13230  case NFA_MCLOSE:
13231  case NFA_MCLOSE1:
13232  case NFA_MCLOSE2:
13233  case NFA_MCLOSE3:
13234  case NFA_MCLOSE4:
13235  case NFA_MCLOSE5:
13236  case NFA_MCLOSE6:
13237  case NFA_MCLOSE7:
13238  case NFA_MCLOSE8:
13239  case NFA_MCLOSE9:
13240  case NFA_ZCLOSE:
13241  case NFA_ZCLOSE1:
13242  case NFA_ZCLOSE2:
13243  case NFA_ZCLOSE3:
13244  case NFA_ZCLOSE4:
13245  case NFA_ZCLOSE5:
13246  case NFA_ZCLOSE6:
13247  case NFA_ZCLOSE7:
13248  case NFA_ZCLOSE8:
13249  case NFA_ZCLOSE9:
13250  case NFA_MOPEN:
13251  case NFA_ZEND:
13252  case NFA_SPLIT:
13253  case NFA_EMPTY:
13254    // These nodes are not added themselves but their "out" and/or
13255    // "out1" may be added below.
13256    break;
13257
13258  case NFA_BOL:
13259  case NFA_BOF:
13260    // "^" won't match past end-of-line, don't bother trying.
13261    // Except when at the end of the line, or when we are going to the
13262    // next line for a look-behind match.
13263    if (rex.input > rex.line
13264        && *rex.input != NUL
13265        && (nfa_endp == NULL
13266            || !REG_MULTI
13267            || rex.lnum == nfa_endp->se_u.pos.lnum)) {
13268      goto skip_add;
13269    }
13270    FALLTHROUGH;
13271
13272  case NFA_MOPEN1:
13273  case NFA_MOPEN2:
13274  case NFA_MOPEN3:
13275  case NFA_MOPEN4:
13276  case NFA_MOPEN5:
13277  case NFA_MOPEN6:
13278  case NFA_MOPEN7:
13279  case NFA_MOPEN8:
13280  case NFA_MOPEN9:
13281  case NFA_ZOPEN:
13282  case NFA_ZOPEN1:
13283  case NFA_ZOPEN2:
13284  case NFA_ZOPEN3:
13285  case NFA_ZOPEN4:
13286  case NFA_ZOPEN5:
13287  case NFA_ZOPEN6:
13288  case NFA_ZOPEN7:
13289  case NFA_ZOPEN8:
13290  case NFA_ZOPEN9:
13291  case NFA_NOPEN:
13292  case NFA_ZSTART:
13293  // These nodes need to be added so that we can bail out when it
13294  // was added to this list before at the same position to avoid an
13295  // endless loop for "\(\)*"
13296
13297  default:
13298    if (state->lastlist[nfa_ll_index] == l->id && state->c != NFA_SKIP) {
13299      // This state is already in the list, don't add it again,
13300      // unless it is an MOPEN that is used for a backreference or
13301      // when there is a PIM. For NFA_MATCH check the position,
13302      // lower position is preferred.
13303      if (!rex.nfa_has_backref && pim == NULL && !l->has_pim
13304          && state->c != NFA_MATCH) {
13305        // When called from addstate_here() do insert before
13306        // existing states.
13307        if (add_here) {
13308          for (k = 0; k < l->n && k < listindex; k++) {
13309            if (l->t[k].state->id == state->id) {
13310              found = true;
13311              break;
13312            }
13313          }
13314        }
13315
13316        if (!add_here || found) {
13317skip_add:
13318#ifdef REGEXP_DEBUG
13319          nfa_set_code(state->c);
13320          fprintf(log_fd,
13321                  "> Not adding state %d to list %d. char %d: %s pim: %s has_pim: %d found: %d\n",
13322                  abs(state->id), l->id, state->c, code,
13323                  pim == NULL ? "NULL" : "yes", l->has_pim, found);
13324#endif
13325          return subs;
13326        }
13327      }
13328
13329      // Do not add the state again when it exists with the same
13330      // positions.
13331      if (has_state_with_pos(l, state, subs, pim)) {
13332        goto skip_add;
13333      }
13334    }
13335
13336    // When there are backreferences or PIMs the number of states may
13337    // be (a lot) bigger than anticipated.
13338    if (l->n == l->len) {
13339      const int newlen = l->len * 3 / 2 + 50;
13340      const size_t newsize = (size_t)newlen * sizeof(nfa_thread_T);
13341
13342      if ((int64_t)(newsize >> 10) >= p_mmp) {
13343        emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
13344        return NULL;
13345      }
13346      if (subs != &temp_subs) {
13347        // "subs" may point into the current array, need to make a
13348        // copy before it becomes invalid.
13349        copy_sub(&temp_subs.norm, &subs->norm);
13350        if (rex.nfa_has_zsubexpr) {
13351          copy_sub(&temp_subs.synt, &subs->synt);
13352        }
13353        subs = &temp_subs;
13354      }
13355
13356      nfa_thread_T *const newt = xrealloc(l->t, newsize);
13357      l->t = newt;
13358      l->len = newlen;
13359    }
13360
13361    // add the state to the list
13362    state->lastlist[nfa_ll_index] = l->id;
13363    thread = &l->t[l->n++];
13364    thread->state = state;
13365    if (pim == NULL) {
13366      thread->pim.result = NFA_PIM_UNUSED;
13367    } else {
13368      copy_pim(&thread->pim, pim);
13369      l->has_pim = true;
13370    }
13371    copy_sub(&thread->subs.norm, &subs->norm);
13372    if (rex.nfa_has_zsubexpr) {
13373      copy_sub(&thread->subs.synt, &subs->synt);
13374    }
13375#ifdef REGEXP_DEBUG
13376    report_state("Adding", &thread->subs.norm, state, l->id, pim);
13377    did_print = true;
13378#endif
13379  }
13380
13381#ifdef REGEXP_DEBUG
13382  if (!did_print) {
13383    report_state("Processing", &subs->norm, state, l->id, pim);
13384  }
13385#endif
13386  switch (state->c) {
13387  case NFA_MATCH:
13388    break;
13389
13390  case NFA_SPLIT:
13391    // order matters here
13392    subs = addstate(l, state->out, subs, pim, off_arg, depth + 1);
13393    subs = addstate(l, state->out1, subs, pim, off_arg, depth + 1);
13394    break;
13395
13396  case NFA_EMPTY:
13397  case NFA_NOPEN:
13398  case NFA_NCLOSE:
13399    subs = addstate(l, state->out, subs, pim, off_arg, depth + 1);
13400    break;
13401
13402  case NFA_MOPEN:
13403  case NFA_MOPEN1:
13404  case NFA_MOPEN2:
13405  case NFA_MOPEN3:
13406  case NFA_MOPEN4:
13407  case NFA_MOPEN5:
13408  case NFA_MOPEN6:
13409  case NFA_MOPEN7:
13410  case NFA_MOPEN8:
13411  case NFA_MOPEN9:
13412  case NFA_ZOPEN:
13413  case NFA_ZOPEN1:
13414  case NFA_ZOPEN2:
13415  case NFA_ZOPEN3:
13416  case NFA_ZOPEN4:
13417  case NFA_ZOPEN5:
13418  case NFA_ZOPEN6:
13419  case NFA_ZOPEN7:
13420  case NFA_ZOPEN8:
13421  case NFA_ZOPEN9:
13422  case NFA_ZSTART:
13423    if (state->c == NFA_ZSTART) {
13424      subidx = 0;
13425      sub = &subs->norm;
13426    } else if (state->c >= NFA_ZOPEN && state->c <= NFA_ZOPEN9) {
13427      subidx = state->c - NFA_ZOPEN;
13428      sub = &subs->synt;
13429    } else {
13430      subidx = state->c - NFA_MOPEN;
13431      sub = &subs->norm;
13432    }
13433
13434    // avoid compiler warnings
13435    save_ptr = NULL;
13436    CLEAR_FIELD(save_multipos);
13437
13438    // Set the position (with "off" added) in the subexpression.  Save
13439    // and restore it when it was in use.  Otherwise fill any gap.
13440    if (REG_MULTI) {
13441      if (subidx < sub->in_use) {
13442        save_multipos = sub->list.multi[subidx];
13443        save_in_use = -1;
13444      } else {
13445        save_in_use = sub->in_use;
13446        for (i = sub->in_use; i < subidx; i++) {
13447          sub->list.multi[i].start_lnum = -1;
13448          sub->list.multi[i].end_lnum = -1;
13449        }
13450        sub->in_use = subidx + 1;
13451      }
13452      if (off == -1) {
13453        sub->list.multi[subidx].start_lnum = rex.lnum + 1;
13454        sub->list.multi[subidx].start_col = 0;
13455      } else {
13456        sub->list.multi[subidx].start_lnum = rex.lnum;
13457        sub->list.multi[subidx].start_col =
13458          (colnr_T)(rex.input - rex.line + off);
13459      }
13460      sub->list.multi[subidx].end_lnum = -1;
13461    } else {
13462      if (subidx < sub->in_use) {
13463        save_ptr = sub->list.line[subidx].start;
13464        save_in_use = -1;
13465      } else {
13466        save_in_use = sub->in_use;
13467        for (i = sub->in_use; i < subidx; i++) {
13468          sub->list.line[i].start = NULL;
13469          sub->list.line[i].end = NULL;
13470        }
13471        sub->in_use = subidx + 1;
13472      }
13473      sub->list.line[subidx].start = rex.input + off;
13474    }
13475
13476    subs = addstate(l, state->out, subs, pim, off_arg, depth + 1);
13477    if (subs == NULL) {
13478      break;
13479    }
13480    // "subs" may have changed, need to set "sub" again.
13481    if (state->c >= NFA_ZOPEN && state->c <= NFA_ZOPEN9) {
13482      sub = &subs->synt;
13483    } else {
13484      sub = &subs->norm;
13485    }
13486
13487    if (save_in_use == -1) {
13488      if (REG_MULTI) {
13489        sub->list.multi[subidx] = save_multipos;
13490      } else {
13491        sub->list.line[subidx].start = save_ptr;
13492      }
13493    } else {
13494      sub->in_use = save_in_use;
13495    }
13496    break;
13497
13498  case NFA_MCLOSE:
13499    if (rex.nfa_has_zend
13500        && (REG_MULTI
13501            ? subs->norm.list.multi[0].end_lnum >= 0
13502            : subs->norm.list.line[0].end != NULL)) {
13503      // Do not overwrite the position set by \ze.
13504      subs = addstate(l, state->out, subs, pim, off_arg, depth + 1);
13505      break;
13506    }
13507    FALLTHROUGH;
13508  case NFA_MCLOSE1:
13509  case NFA_MCLOSE2:
13510  case NFA_MCLOSE3:
13511  case NFA_MCLOSE4:
13512  case NFA_MCLOSE5:
13513  case NFA_MCLOSE6:
13514  case NFA_MCLOSE7:
13515  case NFA_MCLOSE8:
13516  case NFA_MCLOSE9:
13517  case NFA_ZCLOSE:
13518  case NFA_ZCLOSE1:
13519  case NFA_ZCLOSE2:
13520  case NFA_ZCLOSE3:
13521  case NFA_ZCLOSE4:
13522  case NFA_ZCLOSE5:
13523  case NFA_ZCLOSE6:
13524  case NFA_ZCLOSE7:
13525  case NFA_ZCLOSE8:
13526  case NFA_ZCLOSE9:
13527  case NFA_ZEND:
13528    if (state->c == NFA_ZEND) {
13529      subidx = 0;
13530      sub = &subs->norm;
13531    } else if (state->c >= NFA_ZCLOSE && state->c <= NFA_ZCLOSE9) {
13532      subidx = state->c - NFA_ZCLOSE;
13533      sub = &subs->synt;
13534    } else {
13535      subidx = state->c - NFA_MCLOSE;
13536      sub = &subs->norm;
13537    }
13538
13539    // We don't fill in gaps here, there must have been an MOPEN that
13540    // has done that.
13541    save_in_use = sub->in_use;
13542    if (sub->in_use <= subidx) {
13543      sub->in_use = subidx + 1;
13544    }
13545    if (REG_MULTI) {
13546      save_multipos = sub->list.multi[subidx];
13547      if (off == -1) {
13548        sub->list.multi[subidx].end_lnum = rex.lnum + 1;
13549        sub->list.multi[subidx].end_col = 0;
13550      } else {
13551        sub->list.multi[subidx].end_lnum = rex.lnum;
13552        sub->list.multi[subidx].end_col =
13553          (colnr_T)(rex.input - rex.line + off);
13554      }
13555      // avoid compiler warnings
13556      save_ptr = NULL;
13557    } else {
13558      save_ptr = sub->list.line[subidx].end;
13559      sub->list.line[subidx].end = rex.input + off;
13560      // avoid compiler warnings
13561      CLEAR_FIELD(save_multipos);
13562    }
13563
13564    subs = addstate(l, state->out, subs, pim, off_arg, depth + 1);
13565    if (subs == NULL) {
13566      break;
13567    }
13568    // "subs" may have changed, need to set "sub" again.
13569    if (state->c >= NFA_ZCLOSE && state->c <= NFA_ZCLOSE9) {
13570      sub = &subs->synt;
13571    } else {
13572      sub = &subs->norm;
13573    }
13574
13575    if (REG_MULTI) {
13576      sub->list.multi[subidx] = save_multipos;
13577    } else {
13578      sub->list.line[subidx].end = save_ptr;
13579    }
13580    sub->in_use = save_in_use;
13581    break;
13582  }
13583  return subs;
13584}
13585
13586/// Like addstate(), but the new state(s) are put at position "*ip".
13587/// Used for zero-width matches, next state to use is the added one.
13588/// This makes sure the order of states to be tried does not change, which
13589/// matters for alternatives.
13590///
13591/// @param l      runtime state list
13592/// @param state  state to update
13593/// @param subs   pointers to subexpressions
13594/// @param pim    postponed look-behind match
13595static regsubs_T *addstate_here(nfa_list_T *l, nfa_state_T *state, regsubs_T *subs, nfa_pim_T *pim,
13596                                int *ip)
13597  FUNC_ATTR_NONNULL_ARG(1, 2, 5) FUNC_ATTR_WARN_UNUSED_RESULT
13598{
13599  int tlen = l->n;
13600  int count;
13601  int listidx = *ip;
13602
13603  // First add the state(s) at the end, so that we know how many there are.
13604  // Pass the listidx as offset (avoids adding another argument to
13605  // addstate()).
13606  regsubs_T *r = addstate(l, state, subs, pim, -listidx - ADDSTATE_HERE_OFFSET, 0);
13607  if (r == NULL) {
13608    return NULL;
13609  }
13610
13611  // when "*ip" was at the end of the list, nothing to do
13612  if (listidx + 1 == tlen) {
13613    return r;
13614  }
13615
13616  // re-order to put the new state at the current position
13617  count = l->n - tlen;
13618  if (count == 0) {
13619    return r;  // no state got added
13620  }
13621  if (count == 1) {
13622    // overwrite the current state
13623    l->t[listidx] = l->t[l->n - 1];
13624  } else if (count > 1) {
13625    if (l->n + count - 1 >= l->len) {
13626      // not enough space to move the new states, reallocate the list
13627      // and move the states to the right position
13628      const int newlen = l->len * 3 / 2 + 50;
13629      const size_t newsize = (size_t)newlen * sizeof(nfa_thread_T);
13630
13631      if ((int64_t)(newsize >> 10) >= p_mmp) {
13632        emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
13633        return NULL;
13634      }
13635      nfa_thread_T *const newl = xmalloc(newsize);
13636      l->len = newlen;
13637      memmove(&(newl[0]),
13638              &(l->t[0]),
13639              sizeof(nfa_thread_T) * (size_t)listidx);
13640      memmove(&(newl[listidx]),
13641              &(l->t[l->n - count]),
13642              sizeof(nfa_thread_T) * (size_t)count);
13643      memmove(&(newl[listidx + count]),
13644              &(l->t[listidx + 1]),
13645              sizeof(nfa_thread_T) * (size_t)(l->n - count - listidx - 1));
13646      xfree(l->t);
13647      l->t = newl;
13648    } else {
13649      // make space for new states, then move them from the
13650      // end to the current position
13651      memmove(&(l->t[listidx + count]),
13652              &(l->t[listidx + 1]),
13653              sizeof(nfa_thread_T) * (size_t)(l->n - listidx - 1));
13654      memmove(&(l->t[listidx]),
13655              &(l->t[l->n - 1]),
13656              sizeof(nfa_thread_T) * (size_t)count);
13657    }
13658  }
13659  l->n--;
13660  *ip = listidx - 1;
13661
13662  return r;
13663}
13664
13665// Check character class "class" against current character c.
13666static int check_char_class(int cls, int c)
13667{
13668  switch (cls) {
13669  case NFA_CLASS_ALNUM:
13670    if (c >= 1 && c < 128 && isalnum(c)) {
13671      return OK;
13672    }
13673    break;
13674  case NFA_CLASS_ALPHA:
13675    if (c >= 1 && c < 128 && isalpha(c)) {
13676      return OK;
13677    }
13678    break;
13679  case NFA_CLASS_BLANK:
13680    if (c == ' ' || c == '\t') {
13681      return OK;
13682    }
13683    break;
13684  case NFA_CLASS_CNTRL:
13685    if (c >= 1 && c <= 127 && iscntrl(c)) {
13686      return OK;
13687    }
13688    break;
13689  case NFA_CLASS_DIGIT:
13690    if (ascii_isdigit(c)) {
13691      return OK;
13692    }
13693    break;
13694  case NFA_CLASS_GRAPH:
13695    if (c >= 1 && c <= 127 && isgraph(c)) {
13696      return OK;
13697    }
13698    break;
13699  case NFA_CLASS_LOWER:
13700    if (mb_islower(c) && c != 170 && c != 186) {
13701      return OK;
13702    }
13703    break;
13704  case NFA_CLASS_PRINT:
13705    if (vim_isprintc(c)) {
13706      return OK;
13707    }
13708    break;
13709  case NFA_CLASS_PUNCT:
13710    if (c >= 1 && c < 128 && ispunct(c)) {
13711      return OK;
13712    }
13713    break;
13714  case NFA_CLASS_SPACE:
13715    if ((c >= 9 && c <= 13) || (c == ' ')) {
13716      return OK;
13717    }
13718    break;
13719  case NFA_CLASS_UPPER:
13720    if (mb_isupper(c)) {
13721      return OK;
13722    }
13723    break;
13724  case NFA_CLASS_XDIGIT:
13725    if (ascii_isxdigit(c)) {
13726      return OK;
13727    }
13728    break;
13729  case NFA_CLASS_TAB:
13730    if (c == '\t') {
13731      return OK;
13732    }
13733    break;
13734  case NFA_CLASS_RETURN:
13735    if (c == '\r') {
13736      return OK;
13737    }
13738    break;
13739  case NFA_CLASS_BACKSPACE:
13740    if (c == '\b') {
13741      return OK;
13742    }
13743    break;
13744  case NFA_CLASS_ESCAPE:
13745    if (c == ESC) {
13746      return OK;
13747    }
13748    break;
13749  case NFA_CLASS_IDENT:
13750    if (vim_isIDc(c)) {
13751      return OK;
13752    }
13753    break;
13754  case NFA_CLASS_KEYWORD:
13755    if (reg_iswordc(c)) {
13756      return OK;
13757    }
13758    break;
13759  case NFA_CLASS_FNAME:
13760    if (vim_isfilec(c)) {
13761      return OK;
13762    }
13763    break;
13764
13765  default:
13766    // should not be here :P
13767    siemsg(_(e_ill_char_class), (int64_t)cls);
13768    return FAIL;
13769  }
13770  return FAIL;
13771}
13772
13773/// Check for a match with subexpression "subidx".
13774///
13775/// @param sub      pointers to subexpressions
13776/// @param bytelen  out: length of match in bytes
13777///
13778/// @return  true if it matches.
13779static int match_backref(regsub_T *sub, int subidx, int *bytelen)
13780{
13781  int len;
13782
13783  if (sub->in_use <= subidx) {
13784retempty:
13785    // backref was not set, match an empty string
13786    *bytelen = 0;
13787    return true;
13788  }
13789
13790  if (REG_MULTI) {
13791    if (sub->list.multi[subidx].start_lnum < 0
13792        || sub->list.multi[subidx].end_lnum < 0) {
13793      goto retempty;
13794    }
13795    if (sub->list.multi[subidx].start_lnum == rex.lnum
13796        && sub->list.multi[subidx].end_lnum == rex.lnum) {
13797      len = sub->list.multi[subidx].end_col
13798            - sub->list.multi[subidx].start_col;
13799      if (cstrncmp((char *)rex.line + sub->list.multi[subidx].start_col,
13800                   (char *)rex.input, &len) == 0) {
13801        *bytelen = len;
13802        return true;
13803      }
13804    } else {
13805      if (match_with_backref(sub->list.multi[subidx].start_lnum,
13806                             sub->list.multi[subidx].start_col,
13807                             sub->list.multi[subidx].end_lnum,
13808                             sub->list.multi[subidx].end_col,
13809                             bytelen) == RA_MATCH) {
13810        return true;
13811      }
13812    }
13813  } else {
13814    if (sub->list.line[subidx].start == NULL
13815        || sub->list.line[subidx].end == NULL) {
13816      goto retempty;
13817    }
13818    len = (int)(sub->list.line[subidx].end - sub->list.line[subidx].start);
13819    if (cstrncmp((char *)sub->list.line[subidx].start, (char *)rex.input, &len) == 0) {
13820      *bytelen = len;
13821      return true;
13822    }
13823  }
13824  return false;
13825}
13826
13827/// Check for a match with \z subexpression "subidx".
13828///
13829/// @param bytelen  out: length of match in bytes
13830///
13831/// @return  true if it matches.
13832static int match_zref(int subidx, int *bytelen)
13833{
13834  int len;
13835
13836  cleanup_zsubexpr();
13837  if (re_extmatch_in == NULL || re_extmatch_in->matches[subidx] == NULL) {
13838    // backref was not set, match an empty string
13839    *bytelen = 0;
13840    return true;
13841  }
13842
13843  len = (int)strlen((char *)re_extmatch_in->matches[subidx]);
13844  if (cstrncmp((char *)re_extmatch_in->matches[subidx], (char *)rex.input, &len) == 0) {
13845    *bytelen = len;
13846    return true;
13847  }
13848  return false;
13849}
13850
13851// Save list IDs for all NFA states of "prog" into "list".
13852// Also reset the IDs to zero.
13853// Only used for the recursive value lastlist[1].
13854static void nfa_save_listids(nfa_regprog_T *prog, int *list)
13855{
13856  int i;
13857  nfa_state_T *p;
13858
13859  // Order in the list is reverse, it's a bit faster that way.
13860  p = &prog->state[0];
13861  for (i = prog->nstate; --i >= 0;) {
13862    list[i] = p->lastlist[1];
13863    p->lastlist[1] = 0;
13864    p++;
13865  }
13866}
13867
13868// Restore list IDs from "list" to all NFA states.
13869static void nfa_restore_listids(nfa_regprog_T *prog, const int *list)
13870{
13871  int i;
13872  nfa_state_T *p;
13873
13874  p = &prog->state[0];
13875  for (i = prog->nstate; --i >= 0;) {
13876    p->lastlist[1] = list[i];
13877    p++;
13878  }
13879}
13880
13881static bool nfa_re_num_cmp(uintmax_t val, int op, uintmax_t pos)
13882{
13883  if (op == 1) {
13884    return pos > val;
13885  }
13886  if (op == 2) {
13887    return pos < val;
13888  }
13889  return val == pos;
13890}
13891
13892// Recursively call nfa_regmatch()
13893// "pim" is NULL or contains info about a Postponed Invisible Match (start
13894// position).
13895static int recursive_regmatch(nfa_state_T *state, nfa_pim_T *pim, nfa_regprog_T *prog,
13896                              regsubs_T *submatch, regsubs_T *m, int **listids, int *listids_len)
13897  FUNC_ATTR_NONNULL_ARG(1, 3, 5, 6, 7)
13898{
13899  const int save_reginput_col = (int)(rex.input - rex.line);
13900  const int save_reglnum = rex.lnum;
13901  const int save_nfa_match = nfa_match;
13902  const int save_nfa_listid = rex.nfa_listid;
13903  save_se_T *const save_nfa_endp = nfa_endp;
13904  save_se_T endpos;
13905  save_se_T *endposp = NULL;
13906  int need_restore = false;
13907
13908  if (pim != NULL) {
13909    // start at the position where the postponed match was
13910    if (REG_MULTI) {
13911      rex.input = rex.line + pim->end.pos.col;
13912    } else {
13913      rex.input = pim->end.ptr;
13914    }
13915  }
13916
13917  if (state->c == NFA_START_INVISIBLE_BEFORE
13918      || state->c == NFA_START_INVISIBLE_BEFORE_FIRST
13919      || state->c == NFA_START_INVISIBLE_BEFORE_NEG
13920      || state->c == NFA_START_INVISIBLE_BEFORE_NEG_FIRST) {
13921    // The recursive match must end at the current position. When "pim" is
13922    // not NULL it specifies the current position.
13923    endposp = &endpos;
13924    if (REG_MULTI) {
13925      if (pim == NULL) {
13926        endpos.se_u.pos.col = (int)(rex.input - rex.line);
13927        endpos.se_u.pos.lnum = rex.lnum;
13928      } else {
13929        endpos.se_u.pos = pim->end.pos;
13930      }
13931    } else {
13932      if (pim == NULL) {
13933        endpos.se_u.ptr = rex.input;
13934      } else {
13935        endpos.se_u.ptr = pim->end.ptr;
13936      }
13937    }
13938
13939    // Go back the specified number of bytes, or as far as the
13940    // start of the previous line, to try matching "\@<=" or
13941    // not matching "\@<!". This is very inefficient, limit the number of
13942    // bytes if possible.
13943    if (state->val <= 0) {
13944      if (REG_MULTI) {
13945        rex.line = (uint8_t *)reg_getline(--rex.lnum);
13946        if (rex.line == NULL) {
13947          // can't go before the first line
13948          rex.line = (uint8_t *)reg_getline(++rex.lnum);
13949        }
13950      }
13951      rex.input = rex.line;
13952    } else {
13953      if (REG_MULTI && (int)(rex.input - rex.line) < state->val) {
13954        // Not enough bytes in this line, go to end of
13955        // previous line.
13956        rex.line = (uint8_t *)reg_getline(--rex.lnum);
13957        if (rex.line == NULL) {
13958          // can't go before the first line
13959          rex.line = (uint8_t *)reg_getline(++rex.lnum);
13960          rex.input = rex.line;
13961        } else {
13962          rex.input = rex.line + reg_getline_len(rex.lnum);
13963        }
13964      }
13965      if ((int)(rex.input - rex.line) >= state->val) {
13966        rex.input -= state->val;
13967        rex.input -= utf_head_off((char *)rex.line, (char *)rex.input);
13968      } else {
13969        rex.input = rex.line;
13970      }
13971    }
13972  }
13973
13974#ifdef REGEXP_DEBUG
13975  if (log_fd != stderr) {
13976    fclose(log_fd);
13977  }
13978  log_fd = NULL;
13979#endif
13980  // Have to clear the lastlist field of the NFA nodes, so that
13981  // nfa_regmatch() and addstate() can run properly after recursion.
13982  if (nfa_ll_index == 1) {
13983    // Already calling nfa_regmatch() recursively.  Save the lastlist[1]
13984    // values and clear them.
13985    if (*listids == NULL || *listids_len < prog->nstate) {
13986      xfree(*listids);
13987      *listids = xmalloc(sizeof(**listids) * (size_t)prog->nstate);
13988      *listids_len = prog->nstate;
13989    }
13990    nfa_save_listids(prog, *listids);
13991    need_restore = true;
13992    // any value of rex.nfa_listid will do
13993  } else {
13994    // First recursive nfa_regmatch() call, switch to the second lastlist
13995    // entry.  Make sure rex.nfa_listid is different from a previous
13996    // recursive call, because some states may still have this ID.
13997    nfa_ll_index++;
13998    if (rex.nfa_listid <= rex.nfa_alt_listid) {
13999      rex.nfa_listid = rex.nfa_alt_listid;
14000    }
14001  }
14002
14003  // Call nfa_regmatch() to check if the current concat matches at this
14004  // position. The concat ends with the node NFA_END_INVISIBLE
14005  nfa_endp = endposp;
14006  const int result = nfa_regmatch(prog, state->out, submatch, m);
14007
14008  if (need_restore) {
14009    nfa_restore_listids(prog, *listids);
14010  } else {
14011    nfa_ll_index--;
14012    rex.nfa_alt_listid = rex.nfa_listid;
14013  }
14014
14015  // restore position in input text
14016  rex.lnum = save_reglnum;
14017  if (REG_MULTI) {
14018    rex.line = (uint8_t *)reg_getline(rex.lnum);
14019  }
14020  rex.input = rex.line + save_reginput_col;
14021  if (result != NFA_TOO_EXPENSIVE) {
14022    nfa_match = save_nfa_match;
14023    rex.nfa_listid = save_nfa_listid;
14024  }
14025  nfa_endp = save_nfa_endp;
14026
14027#ifdef REGEXP_DEBUG
14028  open_debug_log(result);
14029#endif
14030
14031  return result;
14032}
14033
14034// Estimate the chance of a match with "state" failing.
14035// empty match: 0
14036// NFA_ANY: 1
14037// specific character: 99
14038static int failure_chance(nfa_state_T *state, int depth)
14039{
14040  int c = state->c;
14041  int l, r;
14042
14043  // detect looping
14044  if (depth > 4) {
14045    return 1;
14046  }
14047
14048  switch (c) {
14049  case NFA_SPLIT:
14050    if (state->out->c == NFA_SPLIT || state->out1->c == NFA_SPLIT) {
14051      // avoid recursive stuff
14052      return 1;
14053    }
14054    // two alternatives, use the lowest failure chance
14055    l = failure_chance(state->out, depth + 1);
14056    r = failure_chance(state->out1, depth + 1);
14057    return l < r ? l : r;
14058
14059  case NFA_ANY:
14060    // matches anything, unlikely to fail
14061    return 1;
14062
14063  case NFA_MATCH:
14064  case NFA_MCLOSE:
14065  case NFA_ANY_COMPOSING:
14066    // empty match works always
14067    return 0;
14068
14069  case NFA_START_INVISIBLE:
14070  case NFA_START_INVISIBLE_FIRST:
14071  case NFA_START_INVISIBLE_NEG:
14072  case NFA_START_INVISIBLE_NEG_FIRST:
14073  case NFA_START_INVISIBLE_BEFORE:
14074  case NFA_START_INVISIBLE_BEFORE_FIRST:
14075  case NFA_START_INVISIBLE_BEFORE_NEG:
14076  case NFA_START_INVISIBLE_BEFORE_NEG_FIRST:
14077  case NFA_START_PATTERN:
14078    // recursive regmatch is expensive, use low failure chance
14079    return 5;
14080
14081  case NFA_BOL:
14082  case NFA_EOL:
14083  case NFA_BOF:
14084  case NFA_EOF:
14085  case NFA_NEWL:
14086    return 99;
14087
14088  case NFA_BOW:
14089  case NFA_EOW:
14090    return 90;
14091
14092  case NFA_MOPEN:
14093  case NFA_MOPEN1:
14094  case NFA_MOPEN2:
14095  case NFA_MOPEN3:
14096  case NFA_MOPEN4:
14097  case NFA_MOPEN5:
14098  case NFA_MOPEN6:
14099  case NFA_MOPEN7:
14100  case NFA_MOPEN8:
14101  case NFA_MOPEN9:
14102  case NFA_ZOPEN:
14103  case NFA_ZOPEN1:
14104  case NFA_ZOPEN2:
14105  case NFA_ZOPEN3:
14106  case NFA_ZOPEN4:
14107  case NFA_ZOPEN5:
14108  case NFA_ZOPEN6:
14109  case NFA_ZOPEN7:
14110  case NFA_ZOPEN8:
14111  case NFA_ZOPEN9:
14112  case NFA_ZCLOSE:
14113  case NFA_ZCLOSE1:
14114  case NFA_ZCLOSE2:
14115  case NFA_ZCLOSE3:
14116  case NFA_ZCLOSE4:
14117  case NFA_ZCLOSE5:
14118  case NFA_ZCLOSE6:
14119  case NFA_ZCLOSE7:
14120  case NFA_ZCLOSE8:
14121  case NFA_ZCLOSE9:
14122  case NFA_NOPEN:
14123  case NFA_MCLOSE1:
14124  case NFA_MCLOSE2:
14125  case NFA_MCLOSE3:
14126  case NFA_MCLOSE4:
14127  case NFA_MCLOSE5:
14128  case NFA_MCLOSE6:
14129  case NFA_MCLOSE7:
14130  case NFA_MCLOSE8:
14131  case NFA_MCLOSE9:
14132  case NFA_NCLOSE:
14133    return failure_chance(state->out, depth + 1);
14134
14135  case NFA_BACKREF1:
14136  case NFA_BACKREF2:
14137  case NFA_BACKREF3:
14138  case NFA_BACKREF4:
14139  case NFA_BACKREF5:
14140  case NFA_BACKREF6:
14141  case NFA_BACKREF7:
14142  case NFA_BACKREF8:
14143  case NFA_BACKREF9:
14144  case NFA_ZREF1:
14145  case NFA_ZREF2:
14146  case NFA_ZREF3:
14147  case NFA_ZREF4:
14148  case NFA_ZREF5:
14149  case NFA_ZREF6:
14150  case NFA_ZREF7:
14151  case NFA_ZREF8:
14152  case NFA_ZREF9:
14153    // backreferences don't match in many places
14154    return 94;
14155
14156  case NFA_LNUM_GT:
14157  case NFA_LNUM_LT:
14158  case NFA_COL_GT:
14159  case NFA_COL_LT:
14160  case NFA_VCOL_GT:
14161  case NFA_VCOL_LT:
14162  case NFA_MARK_GT:
14163  case NFA_MARK_LT:
14164  case NFA_VISUAL:
14165    // before/after positions don't match very often
14166    return 85;
14167
14168  case NFA_LNUM:
14169    return 90;
14170
14171  case NFA_CURSOR:
14172  case NFA_COL:
14173  case NFA_VCOL:
14174  case NFA_MARK:
14175    // specific positions rarely match
14176    return 98;
14177
14178  case NFA_COMPOSING:
14179    return 95;
14180
14181  default:
14182    if (c > 0) {
14183      // character match fails often
14184      return 95;
14185    }
14186  }
14187
14188  // something else, includes character classes
14189  return 50;
14190}
14191
14192// Skip until the char "c" we know a match must start with.
14193static int skip_to_start(int c, colnr_T *colp)
14194{
14195  const uint8_t *const s = (uint8_t *)cstrchr((char *)rex.line + *colp, c);
14196  if (s == NULL) {
14197    return FAIL;
14198  }
14199  *colp = (int)(s - rex.line);
14200  return OK;
14201}
14202
14203// Check for a match with match_text.
14204// Called after skip_to_start() has found regstart.
14205// Returns zero for no match, 1 for a match.
14206static int find_match_text(colnr_T *startcol, int regstart, uint8_t *match_text)
14207{
14208  colnr_T col = *startcol;
14209  const int regstart_len = utf_char2len(regstart);
14210
14211  while (true) {
14212    bool match = true;
14213    uint8_t *s1 = match_text;
14214    // skip regstart
14215    int regstart_len2 = regstart_len;
14216    if (regstart_len2 > 1 && utf_ptr2len((char *)rex.line + col) != regstart_len2) {
14217      // because of case-folding of the previously matched text, we may need
14218      // to skip fewer bytes than utf_char2len(regstart)
14219      regstart_len2 = utf_char2len(utf_fold(regstart));
14220    }
14221    uint8_t *s2 = rex.line + col + regstart_len2;
14222    while (*s1) {
14223      int c1_len = utf_ptr2len((char *)s1);
14224      int c1 = utf_ptr2char((char *)s1);
14225      int c2_len = utf_ptr2len((char *)s2);
14226      int c2 = utf_ptr2char((char *)s2);
14227      if (c1 != c2 && (!rex.reg_ic || utf_fold(c1) != utf_fold(c2))) {
14228        match = false;
14229        break;
14230      }
14231      s1 += c1_len;
14232      s2 += c2_len;
14233    }
14234    if (match
14235        // check that no composing char follows
14236        && !utf_iscomposing_legacy(utf_ptr2char((char *)s2))) {
14237      cleanup_subexpr();
14238      if (REG_MULTI) {
14239        rex.reg_startpos[0].lnum = rex.lnum;
14240        rex.reg_startpos[0].col = col;
14241        rex.reg_endpos[0].lnum = rex.lnum;
14242        rex.reg_endpos[0].col = (colnr_T)(s2 - rex.line);
14243      } else {
14244        rex.reg_startp[0] = rex.line + col;
14245        rex.reg_endp[0] = s2;
14246      }
14247      *startcol = col;
14248      return 1L;
14249    }
14250
14251    // Try finding regstart after the current match.
14252    col += regstart_len;  // skip regstart
14253    if (skip_to_start(regstart, &col) == FAIL) {
14254      break;
14255    }
14256  }
14257
14258  *startcol = col;
14259  return 0L;
14260}
14261
14262/// Check whether the composing characters at the current input position match
14263/// the NFA composing sub-expression that starts at "sta" (the first state
14264/// after NFA_COMPOSING).  "curc" is the base character and "clen" its byte
14265/// length.
14266/// Returns OK when it matches, FAIL otherwise.
14267static int match_composing(nfa_state_T *sta, int curc, int clen)
14268{
14269  int mc = curc;
14270  int len = 0;
14271  int cchars[MAX_MCO];
14272  int ccount = 0;
14273  int j;
14274
14275  len = 0;
14276  if (utf_iscomposing_legacy(sta->c)) {
14277    // Only match composing character(s), ignore base
14278    // character.  Used for ".{composing}" and "{composing}"
14279    // (no preceding character).
14280    len += utf_char2len(mc);
14281  }
14282
14283  if (rex.reg_icombine && len == 0) {
14284    // If \Z was present, then ignore composing characters.
14285    // When ignoring the base character this always matches.
14286    return sta->c == curc ? OK : FAIL;
14287  }
14288
14289  // Check base character matches first, unless ignored.
14290  if (len == 0 && mc != sta->c) {
14291    return FAIL;
14292  }
14293
14294  if (len == 0) {
14295    len += utf_char2len(mc);
14296    sta = sta->out;
14297  }
14298
14299  // We don't care about the order of composing characters.
14300  // Get them into cchars[] first.
14301  while (len < clen) {
14302    mc = utf_ptr2char((char *)rex.input + len);
14303    cchars[ccount++] = mc;
14304    len += utf_char2len(mc);
14305    if (ccount == MAX_MCO) {
14306      break;
14307    }
14308  }
14309
14310  // Check that each composing char in the pattern matches a
14311  // composing char in the text.  We do not check if all
14312  // composing chars are matched.
14313  while (sta->c != NFA_END_COMPOSING) {
14314    for (j = 0; j < ccount; j++) {
14315      if (cchars[j] == sta->c) {
14316        break;
14317      }
14318    }
14319    if (j == ccount) {
14320      return FAIL;
14321    }
14322    sta = sta->out;
14323  }
14324
14325  return OK;
14326}
14327
14328static int nfa_did_time_out(void)
14329{
14330  if (nfa_time_limit != NULL && profile_passed_limit(*nfa_time_limit)) {
14331    if (nfa_timed_out != NULL) {
14332      *nfa_timed_out = true;
14333    }
14334    return true;
14335  }
14336  return false;
14337}
14338
14339/// Main matching routine.
14340///
14341/// Run NFA to determine whether it matches rex.input.
14342///
14343/// When "nfa_endp" is not NULL it is a required end-of-match position.
14344///
14345/// Return true if there is a match, false if there is no match,
14346/// NFA_TOO_EXPENSIVE if we end up with too many states.
14347/// When there is a match "submatch" contains the positions.
14348///
14349/// Note: Caller must ensure that: start != NULL.
14350static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start, regsubs_T *submatch, regsubs_T *m)
14351  FUNC_ATTR_NONNULL_ARG(1, 2, 4)
14352{
14353  int result = false;
14354  int flag = 0;
14355  bool go_to_nextline = false;
14356  nfa_thread_T *t;
14357  nfa_list_T list[2];
14358  int listidx;
14359  nfa_list_T *thislist;
14360  nfa_list_T *nextlist;
14361  int *listids = NULL;
14362  int listids_len = 0;
14363  nfa_state_T *add_state;
14364  bool add_here;
14365  int add_count;
14366  int add_off = 0;
14367  int toplevel = start->c == NFA_MOPEN;
14368  regsubs_T *r;
14369  // Some patterns may take a long time to match, especially when using
14370  // recursive_regmatch(). Allow interrupting them with CTRL-C.
14371  reg_breakcheck();
14372  if (got_int) {
14373    return false;
14374  }
14375  if (nfa_did_time_out()) {
14376    return false;
14377  }
14378
14379#ifdef NFA_REGEXP_DEBUG_LOG
14380  FILE *debug = fopen(NFA_REGEXP_DEBUG_LOG, "a");
14381
14382  if (debug == NULL) {
14383    semsg("(NFA) COULD NOT OPEN %s!", NFA_REGEXP_DEBUG_LOG);
14384    return false;
14385  }
14386#endif
14387  nfa_match = false;
14388
14389  // Allocate memory for the lists of nodes.
14390  size_t size = (size_t)(prog->nstate + 1) * sizeof(nfa_thread_T);
14391  // Reuse cached list buffers from prog when available (top-level call).
14392  // Recursive calls must allocate their own buffers.
14393  if (toplevel && prog->listbuf[0] != NULL) {
14394    list[0].t = (nfa_thread_T *)prog->listbuf[0];
14395    list[1].t = (nfa_thread_T *)prog->listbuf[1];
14396    prog->listbuf[0] = NULL;
14397    prog->listbuf[1] = NULL;
14398  } else {
14399    list[0].t = xmalloc(size);
14400    list[1].t = xmalloc(size);
14401  }
14402  list[0].len = prog->nstate + 1;
14403  list[1].len = prog->nstate + 1;
14404
14405#ifdef REGEXP_DEBUG
14406  log_fd = fopen(NFA_REGEXP_RUN_LOG, "a");
14407  if (log_fd == NULL) {
14408    emsg(_(e_log_open_failed));
14409    log_fd = stderr;
14410  }
14411  fprintf(log_fd, "**********************************\n");
14412  nfa_set_code(start->c);
14413  fprintf(log_fd, " RUNNING nfa_regmatch() starting with state %d, code %s\n",
14414          abs(start->id), code);
14415  fprintf(log_fd, "**********************************\n");
14416#endif
14417
14418  thislist = &list[0];
14419  thislist->n = 0;
14420  thislist->has_pim = false;
14421  nextlist = &list[1];
14422  nextlist->n = 0;
14423  nextlist->has_pim = false;
14424#ifdef REGEXP_DEBUG
14425  fprintf(log_fd, "(---) STARTSTATE first\n");
14426#endif
14427  thislist->id = rex.nfa_listid + 1;
14428
14429  // Inline optimized code for addstate(thislist, start, m, 0) if we know
14430  // it's the first MOPEN.
14431  if (toplevel) {
14432    if (REG_MULTI) {
14433      m->norm.list.multi[0].start_lnum = rex.lnum;
14434      m->norm.list.multi[0].start_col = (colnr_T)(rex.input - rex.line);
14435      m->norm.orig_start_col = m->norm.list.multi[0].start_col;
14436    } else {
14437      m->norm.list.line[0].start = rex.input;
14438    }
14439    m->norm.in_use = 1;
14440    r = addstate(thislist, start->out, m, NULL, 0, 0);
14441  } else {
14442    r = addstate(thislist, start, m, NULL, 0, 0);
14443  }
14444  if (r == NULL) {
14445    nfa_match = NFA_TOO_EXPENSIVE;
14446    goto theend;
14447  }
14448
14449#define ADD_STATE_IF_MATCH(state) \
14450  if (result) { \
14451    add_state = (state)->out; \
14452    add_off = clen; \
14453  }
14454
14455  // Run for each character.
14456  while (true) {
14457    int curc, clen;
14458    // Fast path for an ASCII byte not followed by a composing
14459    // character, matching the check in utfc_ptr2len().  Avoids two
14460    // indirect calls for the common case.
14461    if (rex.input[0] != NUL && rex.input[0] < 0x80 && rex.input[1] < 0x80) {
14462      curc = rex.input[0];
14463      clen = 1;
14464    } else {
14465      curc = utf_ptr2char((char *)rex.input);
14466      clen = utfc_ptr2len((char *)rex.input);
14467    }
14468    if (curc == NUL) {
14469      clen = 0;
14470      go_to_nextline = false;
14471    }
14472
14473    // swap lists
14474    thislist = &list[flag];
14475    nextlist = &list[flag ^= 1];
14476    nextlist->n = 0;                // clear nextlist
14477    nextlist->has_pim = false;
14478    rex.nfa_listid++;
14479    if (prog->re_engine == AUTOMATIC_ENGINE
14480        && (rex.nfa_listid >= NFA_MAX_STATES)) {
14481      // Too many states, retry with old engine.
14482      nfa_match = NFA_TOO_EXPENSIVE;
14483      goto theend;
14484    }
14485
14486    thislist->id = rex.nfa_listid;
14487    nextlist->id = rex.nfa_listid + 1;
14488
14489#ifdef REGEXP_DEBUG
14490    fprintf(log_fd, "------------------------------------------\n");
14491    fprintf(log_fd, ">>> Reginput is \"%s\"\n", rex.input);
14492    fprintf(log_fd,
14493            ">>> Advanced one character... Current char is %c (code %d) \n",
14494            curc,
14495            (int)curc);
14496    fprintf(log_fd, ">>> Thislist has %d states available: ", thislist->n);
14497    {
14498      int i;
14499
14500      for (i = 0; i < thislist->n; i++) {
14501        fprintf(log_fd, "%d  ", abs(thislist->t[i].state->id));
14502      }
14503    }
14504    fprintf(log_fd, "\n");
14505#endif
14506
14507#ifdef NFA_REGEXP_DEBUG_LOG
14508    fprintf(debug, "\n-------------------\n");
14509#endif
14510    // If the state lists are empty we can stop.
14511    if (thislist->n == 0) {
14512      break;
14513    }
14514
14515    // compute nextlist
14516    for (listidx = 0; listidx < thislist->n; listidx++) {
14517      // If the list gets very long there probably is something wrong.
14518      // At least allow interrupting with CTRL-C.
14519      reg_breakcheck();
14520      if (got_int) {
14521        break;
14522      }
14523      if (nfa_time_limit != NULL && ++nfa_time_count == 20) {
14524        nfa_time_count = 0;
14525        if (nfa_did_time_out()) {
14526          break;
14527        }
14528      }
14529      t = &thislist->t[listidx];
14530
14531#ifdef NFA_REGEXP_DEBUG_LOG
14532      nfa_set_code(t->state->c);
14533      fprintf(debug, "%s, ", code);
14534#endif
14535#ifdef REGEXP_DEBUG
14536      {
14537        int col;
14538
14539        if (t->subs.norm.in_use <= 0) {
14540          col = -1;
14541        } else if (REG_MULTI) {
14542          col = t->subs.norm.list.multi[0].start_col;
14543        } else {
14544          col = (int)(t->subs.norm.list.line[0].start - rex.line);
14545        }
14546        nfa_set_code(t->state->c);
14547        fprintf(log_fd, "(%d) char %d %s (start col %d)%s... \n",
14548                abs(t->state->id), (int)t->state->c, code, col,
14549                pim_info(&t->pim));
14550      }
14551#endif
14552
14553      // Handle the possible codes of the current state.
14554      // The most important is NFA_MATCH.
14555      add_state = NULL;
14556      add_here = false;
14557      add_count = 0;
14558      switch (t->state->c) {
14559      case NFA_MATCH:
14560        // If the match is not at the start of the line, ends before a
14561        // composing characters and rex.reg_icombine is not set, that
14562        // is not really a match.
14563        if (!rex.reg_icombine
14564            && rex.input != rex.line
14565            && utf_iscomposing_legacy(curc)) {
14566          break;
14567        }
14568        nfa_match = true;
14569        copy_sub(&submatch->norm, &t->subs.norm);
14570        if (rex.nfa_has_zsubexpr) {
14571          copy_sub(&submatch->synt, &t->subs.synt);
14572        }
14573#ifdef REGEXP_DEBUG
14574        log_subsexpr(&t->subs);
14575#endif
14576        // Found the left-most longest match, do not look at any other
14577        // states at this position.  When the list of states is going
14578        // to be empty quit without advancing, so that "rex.input" is
14579        // correct.
14580        if (nextlist->n == 0) {
14581          clen = 0;
14582        }
14583        goto nextchar;
14584
14585      case NFA_END_INVISIBLE:
14586      case NFA_END_INVISIBLE_NEG:
14587      case NFA_END_PATTERN:
14588        // This is only encountered after a NFA_START_INVISIBLE or
14589        // NFA_START_INVISIBLE_BEFORE node.
14590        // They surround a zero-width group, used with "\@=", "\&",
14591        // "\@!", "\@<=" and "\@<!".
14592        // If we got here, it means that the current "invisible" group
14593        // finished successfully, so return control to the parent
14594        // nfa_regmatch().  For a look-behind match only when it ends
14595        // in the position in "nfa_endp".
14596        // Submatches are stored in *m, and used in the parent call.
14597#ifdef REGEXP_DEBUG
14598        if (nfa_endp != NULL) {
14599          if (REG_MULTI) {
14600            fprintf(log_fd,
14601                    "Current lnum: %d, endp lnum: %d;"
14602                    " current col: %d, endp col: %d\n",
14603                    (int)rex.lnum,
14604                    (int)nfa_endp->se_u.pos.lnum,
14605                    (int)(rex.input - rex.line),
14606                    nfa_endp->se_u.pos.col);
14607          } else {
14608            fprintf(log_fd, "Current col: %d, endp col: %d\n",
14609                    (int)(rex.input - rex.line),
14610                    (int)(nfa_endp->se_u.ptr - rex.input));
14611          }
14612        }
14613#endif
14614        // If "nfa_endp" is set it's only a match if it ends at
14615        // "nfa_endp"
14616        if (nfa_endp != NULL
14617            && (REG_MULTI
14618                ? (rex.lnum != nfa_endp->se_u.pos.lnum
14619                   || (int)(rex.input - rex.line) != nfa_endp->se_u.pos.col)
14620                : rex.input != nfa_endp->se_u.ptr)) {
14621          break;
14622        }
14623        // do not set submatches for \@!
14624        if (t->state->c != NFA_END_INVISIBLE_NEG) {
14625          copy_sub(&m->norm, &t->subs.norm);
14626          if (rex.nfa_has_zsubexpr) {
14627            copy_sub(&m->synt, &t->subs.synt);
14628          }
14629        }
14630#ifdef REGEXP_DEBUG
14631        fprintf(log_fd, "Match found:\n");
14632        log_subsexpr(m);
14633#endif
14634        nfa_match = true;
14635        // See comment above at "goto nextchar".
14636        if (nextlist->n == 0) {
14637          clen = 0;
14638        }
14639        goto nextchar;
14640
14641      case NFA_START_INVISIBLE:
14642      case NFA_START_INVISIBLE_FIRST:
14643      case NFA_START_INVISIBLE_NEG:
14644      case NFA_START_INVISIBLE_NEG_FIRST:
14645      case NFA_START_INVISIBLE_BEFORE:
14646      case NFA_START_INVISIBLE_BEFORE_FIRST:
14647      case NFA_START_INVISIBLE_BEFORE_NEG:
14648      case NFA_START_INVISIBLE_BEFORE_NEG_FIRST:
14649#ifdef REGEXP_DEBUG
14650        fprintf(log_fd, "Failure chance invisible: %d, what follows: %d\n",
14651                failure_chance(t->state->out, 0),
14652                failure_chance(t->state->out1->out, 0));
14653#endif
14654        // Do it directly if there already is a PIM or when
14655        // nfa_postprocess() detected it will work better.
14656        if (t->pim.result != NFA_PIM_UNUSED
14657            || t->state->c == NFA_START_INVISIBLE_FIRST
14658            || t->state->c == NFA_START_INVISIBLE_NEG_FIRST
14659            || t->state->c == NFA_START_INVISIBLE_BEFORE_FIRST
14660            || t->state->c == NFA_START_INVISIBLE_BEFORE_NEG_FIRST) {
14661          int in_use = m->norm.in_use;
14662
14663          // Copy submatch info for the recursive call, opposite
14664          // of what happens on success below.
14665          copy_sub_off(&m->norm, &t->subs.norm);
14666          if (rex.nfa_has_zsubexpr) {
14667            copy_sub_off(&m->synt, &t->subs.synt);
14668          }
14669          // First try matching the invisible match, then what
14670          // follows.
14671          result = recursive_regmatch(t->state, NULL, prog, submatch, m,
14672                                      &listids, &listids_len);
14673          if (result == NFA_TOO_EXPENSIVE) {
14674            nfa_match = result;
14675            goto theend;
14676          }
14677
14678          // for \@! and \@<! it is a match when the result is
14679          // false
14680          if (result != (t->state->c == NFA_START_INVISIBLE_NEG
14681                         || t->state->c == NFA_START_INVISIBLE_NEG_FIRST
14682                         || t->state->c
14683                         == NFA_START_INVISIBLE_BEFORE_NEG
14684                         || t->state->c
14685                         == NFA_START_INVISIBLE_BEFORE_NEG_FIRST)) {
14686            // Copy submatch info from the recursive call
14687            copy_sub_off(&t->subs.norm, &m->norm);
14688            if (rex.nfa_has_zsubexpr) {
14689              copy_sub_off(&t->subs.synt, &m->synt);
14690            }
14691            // If the pattern has \ze and it matched in the
14692            // sub pattern, use it.
14693            copy_ze_off(&t->subs.norm, &m->norm);
14694
14695            // t->state->out1 is the corresponding
14696            // END_INVISIBLE node; Add its out to the current
14697            // list (zero-width match).
14698            add_here = true;
14699            add_state = t->state->out1->out;
14700          }
14701          m->norm.in_use = in_use;
14702        } else {
14703          nfa_pim_T pim;
14704
14705          // First try matching what follows.  Only if a match
14706          // is found verify the invisible match matches.  Add a
14707          // nfa_pim_T to the following states, it contains info
14708          // about the invisible match.
14709          pim.state = t->state;
14710          pim.result = NFA_PIM_TODO;
14711          pim.subs.norm.in_use = 0;
14712          pim.subs.synt.in_use = 0;
14713          if (REG_MULTI) {
14714            pim.end.pos.col = (int)(rex.input - rex.line);
14715            pim.end.pos.lnum = rex.lnum;
14716          } else {
14717            pim.end.ptr = rex.input;
14718          }
14719          // t->state->out1 is the corresponding END_INVISIBLE
14720          // node; Add its out to the current list (zero-width
14721          // match).
14722          if (addstate_here(thislist, t->state->out1->out, &t->subs,
14723                            &pim, &listidx) == NULL) {
14724            nfa_match = NFA_TOO_EXPENSIVE;
14725            goto theend;
14726          }
14727        }
14728        break;
14729
14730      case NFA_START_PATTERN: {
14731        nfa_state_T *skip = NULL;
14732#ifdef REGEXP_DEBUG
14733        int skip_lid = 0;
14734#endif
14735
14736        // There is no point in trying to match the pattern if the
14737        // output state is not going to be added to the list.
14738        if (state_in_list(nextlist, t->state->out1->out, &t->subs)) {
14739          skip = t->state->out1->out;
14740#ifdef REGEXP_DEBUG
14741          skip_lid = nextlist->id;
14742#endif
14743        } else if (state_in_list(nextlist,
14744                                 t->state->out1->out->out, &t->subs)) {
14745          skip = t->state->out1->out->out;
14746#ifdef REGEXP_DEBUG
14747          skip_lid = nextlist->id;
14748#endif
14749        } else if (state_in_list(thislist,
14750                                 t->state->out1->out->out, &t->subs)) {
14751          skip = t->state->out1->out->out;
14752#ifdef REGEXP_DEBUG
14753          skip_lid = thislist->id;
14754#endif
14755        }
14756        if (skip != NULL) {
14757#ifdef REGEXP_DEBUG
14758          nfa_set_code(skip->c);
14759          fprintf(log_fd,
14760                  "> Not trying to match pattern, output state %d is already in list %d. char %d: %s\n",
14761                  abs(skip->id), skip_lid, skip->c, code);
14762#endif
14763          break;
14764        }
14765        // Copy submatch info to the recursive call, opposite of what
14766        // happens afterwards.
14767        copy_sub_off(&m->norm, &t->subs.norm);
14768        if (rex.nfa_has_zsubexpr) {
14769          copy_sub_off(&m->synt, &t->subs.synt);
14770        }
14771
14772        // First try matching the pattern.
14773        result = recursive_regmatch(t->state, NULL, prog, submatch, m,
14774                                    &listids, &listids_len);
14775        if (result == NFA_TOO_EXPENSIVE) {
14776          nfa_match = result;
14777          goto theend;
14778        }
14779        if (result) {
14780          int bytelen;
14781
14782#ifdef REGEXP_DEBUG
14783          fprintf(log_fd, "NFA_START_PATTERN matches:\n");
14784          log_subsexpr(m);
14785#endif
14786          // Copy submatch info from the recursive call
14787          copy_sub_off(&t->subs.norm, &m->norm);
14788          if (rex.nfa_has_zsubexpr) {
14789            copy_sub_off(&t->subs.synt, &m->synt);
14790          }
14791          // Now we need to skip over the matched text and then
14792          // continue with what follows.
14793          if (REG_MULTI) {
14794            // TODO(RE): multi-line match
14795            bytelen = m->norm.list.multi[0].end_col
14796                      - (int)(rex.input - rex.line);
14797          } else {
14798            bytelen = (int)(m->norm.list.line[0].end - rex.input);
14799          }
14800
14801#ifdef REGEXP_DEBUG
14802          fprintf(log_fd, "NFA_START_PATTERN length: %d\n", bytelen);
14803#endif
14804          if (bytelen == 0) {
14805            // empty match, output of corresponding
14806            // NFA_END_PATTERN/NFA_SKIP to be used at current
14807            // position
14808            add_here = true;
14809            add_state = t->state->out1->out->out;
14810          } else if (bytelen <= clen) {
14811            // match current character, output of corresponding
14812            // NFA_END_PATTERN to be used at next position.
14813            add_state = t->state->out1->out->out;
14814            add_off = clen;
14815          } else {
14816            // skip over the matched characters, set character
14817            // count in NFA_SKIP
14818            add_state = t->state->out1->out;
14819            add_off = bytelen;
14820            add_count = bytelen - clen;
14821          }
14822        }
14823        break;
14824      }
14825
14826      case NFA_BOL:
14827        if (rex.input == rex.line) {
14828          add_here = true;
14829          add_state = t->state->out;
14830        }
14831        break;
14832
14833      case NFA_EOL:
14834        if (curc == NUL) {
14835          add_here = true;
14836          add_state = t->state->out;
14837        }
14838        break;
14839
14840      case NFA_BOW:
14841        result = true;
14842
14843        if (curc == NUL) {
14844          result = false;
14845        } else {
14846          int this_class;
14847
14848          // Get class of current and previous char (if it exists).
14849          this_class = mb_get_class_tab((char *)rex.input, rex.reg_buf->b_chartab);
14850          if (this_class <= 1) {
14851            result = false;
14852          } else if (reg_prev_class() == this_class) {
14853            result = false;
14854          }
14855        }
14856        if (result) {
14857          add_here = true;
14858          add_state = t->state->out;
14859        }
14860        break;
14861
14862      case NFA_EOW:
14863        result = true;
14864        if (rex.input == rex.line) {
14865          result = false;
14866        } else {
14867          int this_class, prev_class;
14868
14869          // Get class of current and previous char (if it exists).
14870          this_class = mb_get_class_tab((char *)rex.input, rex.reg_buf->b_chartab);
14871          prev_class = reg_prev_class();
14872          if (this_class == prev_class
14873              || prev_class == 0 || prev_class == 1) {
14874            result = false;
14875          }
14876        }
14877        if (result) {
14878          add_here = true;
14879          add_state = t->state->out;
14880        }
14881        break;
14882
14883      case NFA_BOF:
14884        if (rex.lnum == 0 && rex.input == rex.line
14885            && (!REG_MULTI || rex.reg_firstlnum == 1)) {
14886          add_here = true;
14887          add_state = t->state->out;
14888        }
14889        break;
14890
14891      case NFA_EOF:
14892        if (rex.lnum == rex.reg_maxline && curc == NUL) {
14893          add_here = true;
14894          add_state = t->state->out;
14895        }
14896        break;
14897
14898      case NFA_COMPOSING: {
14899        nfa_state_T *end;
14900        result = match_composing(t->state->out, curc, clen);
14901        end = t->state->out1;               // NFA_END_COMPOSING
14902        ADD_STATE_IF_MATCH(end);
14903        break;
14904      }
14905
14906      case NFA_NEWL:
14907        if (curc == NUL && !rex.reg_line_lbr && REG_MULTI
14908            && rex.lnum <= rex.reg_maxline) {
14909          go_to_nextline = true;
14910          // Pass -1 for the offset, which means taking the position
14911          // at the start of the next line.
14912          add_state = t->state->out;
14913          add_off = -1;
14914        } else if (curc == '\n' && rex.reg_line_lbr) {
14915          // match \n as if it is an ordinary character
14916          add_state = t->state->out;
14917          add_off = 1;
14918        }
14919        break;
14920
14921      case NFA_START_COLL:
14922      case NFA_START_NEG_COLL: {
14923        // What follows is a list of characters, until NFA_END_COLL.
14924        // One of them must match or none of them must match.
14925        nfa_state_T *state;
14926        int result_if_matched;
14927        int c1, c2;
14928
14929        // Never match EOL. If it's part of the collection it is added
14930        // as a separate state with an OR.
14931        if (curc == NUL) {
14932          break;
14933        }
14934
14935        state = t->state->out;
14936        result_if_matched = (t->state->c == NFA_START_COLL);
14937        while (true) {
14938          if (state->c == NFA_COMPOSING) {
14939            nfa_state_T *end;
14940            result = match_composing(t->state->out->out, curc, clen);
14941            if (t->state->out->out1 != NULL
14942                && t->state->out->out1->c == NFA_END_COMPOSING) {
14943              end = t->state->out->out1;
14944              ADD_STATE_IF_MATCH(end);
14945            }
14946            break;
14947          }
14948          if (state->c == NFA_END_COLL) {
14949            result = !result_if_matched;
14950            break;
14951          }
14952          if (state->c == NFA_RANGE_MIN) {
14953            c1 = state->val;
14954            state = state->out;             // advance to NFA_RANGE_MAX
14955            c2 = state->val;
14956#ifdef REGEXP_DEBUG
14957            fprintf(log_fd, "NFA_RANGE_MIN curc=%d c1=%d c2=%d\n",
14958                    curc, c1, c2);
14959#endif
14960            if (curc >= c1 && curc <= c2) {
14961              result = result_if_matched;
14962              break;
14963            }
14964            if (rex.reg_ic) {
14965              int curc_low = utf_fold(curc);
14966              int done = false;
14967
14968              for (; c1 <= c2; c1++) {
14969                if (utf_fold(c1) == curc_low) {
14970                  result = result_if_matched;
14971                  done = true;
14972                  break;
14973                }
14974              }
14975              if (done) {
14976                break;
14977              }
14978            }
14979          } else if (state->c < 0 ? check_char_class(state->c, curc)
14980                                  : (curc == state->c
14981                                     || (rex.reg_ic
14982                                         && utf_fold(curc) == utf_fold(state->c)))) {
14983            result = result_if_matched;
14984            break;
14985          }
14986          state = state->out;
14987        }
14988        if (result) {
14989          // next state is in out of the NFA_END_COLL, out1 of
14990          // START points to the END state
14991          add_state = t->state->out1->out;
14992          add_off = clen;
14993        }
14994        break;
14995      }
14996
14997      case NFA_ANY:
14998        // Any char except NUL, (end of input) does not match.
14999        if (curc > 0) {
15000          add_state = t->state->out;
15001          add_off = clen;
15002        }
15003        break;
15004
15005      case NFA_ANY_COMPOSING:
15006        // On a composing character skip over it.  Otherwise do
15007        // nothing.  Always matches.
15008        if (utf_iscomposing_legacy(curc)) {
15009          add_off = clen;
15010        } else {
15011          add_here = true;
15012          add_off = 0;
15013        }
15014        add_state = t->state->out;
15015        break;
15016
15017      // Character classes like \a for alpha, \d for digit etc.
15018      case NFA_IDENT:           //  \i
15019        result = vim_isIDc(curc);
15020        ADD_STATE_IF_MATCH(t->state);
15021        break;
15022
15023      case NFA_SIDENT:          //  \I
15024        result = !ascii_isdigit(curc) && vim_isIDc(curc);
15025        ADD_STATE_IF_MATCH(t->state);
15026        break;
15027
15028      case NFA_KWORD:           //  \k
15029        result = vim_iswordp_buf((char *)rex.input, rex.reg_buf);
15030        ADD_STATE_IF_MATCH(t->state);
15031        break;
15032
15033      case NFA_SKWORD:          //  \K
15034        result = !ascii_isdigit(curc)
15035                 && vim_iswordp_buf((char *)rex.input, rex.reg_buf);
15036        ADD_STATE_IF_MATCH(t->state);
15037        break;
15038
15039      case NFA_FNAME:           //  \f
15040        result = vim_isfilec(curc);
15041        ADD_STATE_IF_MATCH(t->state);
15042        break;
15043
15044      case NFA_SFNAME:          //  \F
15045        result = !ascii_isdigit(curc) && vim_isfilec(curc);
15046        ADD_STATE_IF_MATCH(t->state);
15047        break;
15048
15049      case NFA_PRINT:           //  \p
15050        result = vim_isprintc(utf_ptr2char((char *)rex.input));
15051        ADD_STATE_IF_MATCH(t->state);
15052        break;
15053
15054      case NFA_SPRINT:          //  \P
15055        result = !ascii_isdigit(curc) && vim_isprintc(utf_ptr2char((char *)rex.input));
15056        ADD_STATE_IF_MATCH(t->state);
15057        break;
15058
15059      case NFA_WHITE:           //  \s
15060        result = ascii_iswhite(curc);
15061        ADD_STATE_IF_MATCH(t->state);
15062        break;
15063
15064      case NFA_NWHITE:          //  \S
15065        result = curc != NUL && !ascii_iswhite(curc);
15066        ADD_STATE_IF_MATCH(t->state);
15067        break;
15068
15069      case NFA_DIGIT:           //  \d
15070        result = ri_digit(curc);
15071        ADD_STATE_IF_MATCH(t->state);
15072        break;
15073
15074      case NFA_NDIGIT:          //  \D
15075        result = curc != NUL && !ri_digit(curc);
15076        ADD_STATE_IF_MATCH(t->state);
15077        break;
15078
15079      case NFA_HEX:             //  \x
15080        result = ri_hex(curc);
15081        ADD_STATE_IF_MATCH(t->state);
15082        break;
15083
15084      case NFA_NHEX:            //  \X
15085        result = curc != NUL && !ri_hex(curc);
15086        ADD_STATE_IF_MATCH(t->state);
15087        break;
15088
15089      case NFA_OCTAL:           //  \o
15090        result = ri_octal(curc);
15091        ADD_STATE_IF_MATCH(t->state);
15092        break;
15093
15094      case NFA_NOCTAL:          //  \O
15095        result = curc != NUL && !ri_octal(curc);
15096        ADD_STATE_IF_MATCH(t->state);
15097        break;
15098
15099      case NFA_WORD:            //  \w
15100        result = ri_word(curc);
15101        ADD_STATE_IF_MATCH(t->state);
15102        break;
15103
15104      case NFA_NWORD:           //  \W
15105        result = curc != NUL && !ri_word(curc);
15106        ADD_STATE_IF_MATCH(t->state);
15107        break;
15108
15109      case NFA_HEAD:            //  \h
15110        result = ri_head(curc);
15111        ADD_STATE_IF_MATCH(t->state);
15112        break;
15113
15114      case NFA_NHEAD:           //  \H
15115        result = curc != NUL && !ri_head(curc);
15116        ADD_STATE_IF_MATCH(t->state);
15117        break;
15118
15119      case NFA_ALPHA:           //  \a
15120        result = ri_alpha(curc);
15121        ADD_STATE_IF_MATCH(t->state);
15122        break;
15123
15124      case NFA_NALPHA:          //  \A
15125        result = curc != NUL && !ri_alpha(curc);
15126        ADD_STATE_IF_MATCH(t->state);
15127        break;
15128
15129      case NFA_LOWER:           //  \l
15130        result = ri_lower(curc);
15131        ADD_STATE_IF_MATCH(t->state);
15132        break;
15133
15134      case NFA_NLOWER:          //  \L
15135        result = curc != NUL && !ri_lower(curc);
15136        ADD_STATE_IF_MATCH(t->state);
15137        break;
15138
15139      case NFA_UPPER:           //  \u
15140        result = ri_upper(curc);
15141        ADD_STATE_IF_MATCH(t->state);
15142        break;
15143
15144      case NFA_NUPPER:          // \U
15145        result = curc != NUL && !ri_upper(curc);
15146        ADD_STATE_IF_MATCH(t->state);
15147        break;
15148
15149      case NFA_LOWER_IC:        // [a-z]
15150        result = ri_lower(curc) || (rex.reg_ic && ri_upper(curc));
15151        ADD_STATE_IF_MATCH(t->state);
15152        break;
15153
15154      case NFA_NLOWER_IC:       // [^a-z]
15155        result = curc != NUL
15156                 && !(ri_lower(curc) || (rex.reg_ic && ri_upper(curc)));
15157        ADD_STATE_IF_MATCH(t->state);
15158        break;
15159
15160      case NFA_UPPER_IC:        // [A-Z]
15161        result = ri_upper(curc) || (rex.reg_ic && ri_lower(curc));
15162        ADD_STATE_IF_MATCH(t->state);
15163        break;
15164
15165      case NFA_NUPPER_IC:       // [^A-Z]
15166        result = curc != NUL
15167                 && !(ri_upper(curc) || (rex.reg_ic && ri_lower(curc)));
15168        ADD_STATE_IF_MATCH(t->state);
15169        break;
15170
15171      case NFA_BACKREF1:
15172      case NFA_BACKREF2:
15173      case NFA_BACKREF3:
15174      case NFA_BACKREF4:
15175      case NFA_BACKREF5:
15176      case NFA_BACKREF6:
15177      case NFA_BACKREF7:
15178      case NFA_BACKREF8:
15179      case NFA_BACKREF9:
15180      case NFA_ZREF1:
15181      case NFA_ZREF2:
15182      case NFA_ZREF3:
15183      case NFA_ZREF4:
15184      case NFA_ZREF5:
15185      case NFA_ZREF6:
15186      case NFA_ZREF7:
15187      case NFA_ZREF8:
15188      case NFA_ZREF9:
15189        // \1 .. \9  \z1 .. \z9
15190      {
15191        int subidx;
15192        int bytelen;
15193
15194        if (t->state->c >= NFA_BACKREF1 && t->state->c <= NFA_BACKREF9) {
15195          subidx = t->state->c - NFA_BACKREF1 + 1;
15196          result = match_backref(&t->subs.norm, subidx, &bytelen);
15197        } else {
15198          subidx = t->state->c - NFA_ZREF1 + 1;
15199          result = match_zref(subidx, &bytelen);
15200        }
15201
15202        if (result) {
15203          if (bytelen == 0) {
15204            // empty match always works, output of NFA_SKIP to be
15205            // used next
15206            add_here = true;
15207            add_state = t->state->out->out;
15208          } else if (bytelen <= clen) {
15209            // match current character, jump ahead to out of
15210            // NFA_SKIP
15211            add_state = t->state->out->out;
15212            add_off = clen;
15213          } else {
15214            // skip over the matched characters, set character
15215            // count in NFA_SKIP
15216            add_state = t->state->out;
15217            add_off = bytelen;
15218            add_count = bytelen - clen;
15219          }
15220        }
15221        break;
15222      }
15223      case NFA_SKIP:
15224        // character of previous matching \1 .. \9  or \@>
15225        if (t->count - clen <= 0) {
15226          // end of match, go to what follows
15227          add_state = t->state->out;
15228          add_off = clen;
15229        } else {
15230          // add state again with decremented count
15231          add_state = t->state;
15232          add_off = 0;
15233          add_count = t->count - clen;
15234        }
15235        break;
15236
15237      case NFA_LNUM:
15238      case NFA_LNUM_GT:
15239      case NFA_LNUM_LT:
15240        assert(t->state->val >= 0
15241               && !((rex.reg_firstlnum > 0
15242                     && rex.lnum > LONG_MAX - rex.reg_firstlnum)
15243                    || (rex.reg_firstlnum < 0
15244                        && rex.lnum < LONG_MIN + rex.reg_firstlnum))
15245               && rex.lnum + rex.reg_firstlnum >= 0);
15246        result = (REG_MULTI
15247                  && nfa_re_num_cmp((uintmax_t)t->state->val,
15248                                    t->state->c - NFA_LNUM,
15249                                    (uintmax_t)rex.lnum + (uintmax_t)rex.reg_firstlnum));
15250        if (result) {
15251          add_here = true;
15252          add_state = t->state->out;
15253        }
15254        break;
15255
15256      case NFA_COL:
15257      case NFA_COL_GT:
15258      case NFA_COL_LT:
15259        assert(t->state->val >= 0
15260               && rex.input >= rex.line
15261               && (uintmax_t)(rex.input - rex.line) <= UINTMAX_MAX - 1);
15262        result = nfa_re_num_cmp((uintmax_t)t->state->val,
15263                                t->state->c - NFA_COL,
15264                                (uintmax_t)(rex.input - rex.line + 1));
15265        if (result) {
15266          add_here = true;
15267          add_state = t->state->out;
15268        }
15269        break;
15270
15271      case NFA_VCOL:
15272      case NFA_VCOL_GT:
15273      case NFA_VCOL_LT: {
15274        int op = t->state->c - NFA_VCOL;
15275        colnr_T col = (colnr_T)(rex.input - rex.line);
15276
15277        // Bail out quickly when there can't be a match, avoid the overhead of
15278        // win_linetabsize() on long lines.
15279        if (op != 1 && col > t->state->val * MB_MAXBYTES) {
15280          break;
15281        }
15282
15283        result = false;
15284        win_T *wp = rex.reg_win == NULL ? curwin : rex.reg_win;
15285        if (op == 1 && col - 1 > t->state->val && col > 100) {
15286          int64_t ts = (int64_t)wp->w_buffer->b_p_ts;
15287
15288          // Guess that a character won't use more columns than 'tabstop',
15289          // with a minimum of 4.
15290          if (ts < 4) {
15291            ts = 4;
15292          }
15293          result = col > t->state->val * ts;
15294        }
15295        if (!result) {
15296          linenr_T lnum = REG_MULTI ? rex.reg_firstlnum + rex.lnum : 1;
15297          if (REG_MULTI && (lnum <= 0 || lnum > wp->w_buffer->b_ml.ml_line_count)) {
15298            lnum = 1;
15299          }
15300          int vcol = win_linetabsize(wp, lnum, (char *)rex.line, col);
15301          assert(t->state->val >= 0);
15302          result = nfa_re_num_cmp((uintmax_t)t->state->val, op, (uintmax_t)vcol + 1);
15303        }
15304        if (result) {
15305          add_here = true;
15306          add_state = t->state->out;
15307        }
15308      }
15309      break;
15310
15311      case NFA_MARK:
15312      case NFA_MARK_GT:
15313      case NFA_MARK_LT: {
15314        size_t col = REG_MULTI ? (size_t)(rex.input - rex.line) : 0;
15315        fmark_T *fm = mark_get(rex.reg_buf, curwin, NULL, kMarkBufLocal, t->state->val);
15316
15317        // Line may have been freed, get it again.
15318        if (REG_MULTI) {
15319          rex.line = (uint8_t *)reg_getline(rex.lnum);
15320          rex.input = rex.line + col;
15321        }
15322
15323        // Compare the mark position to the match position, if the mark
15324        // exists and mark is set in reg_buf.
15325        if (fm != NULL && fm->mark.lnum > 0) {
15326          pos_T *pos = &fm->mark;
15327          const colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum
15328                                  && pos->col == MAXCOL
15329                                  ? reg_getline_len(pos->lnum - rex.reg_firstlnum)
15330                                  : pos->col;
15331
15332          result = pos->lnum == rex.lnum + rex.reg_firstlnum
15333                   ? (pos_col == (colnr_T)(rex.input - rex.line)
15334                      ? t->state->c == NFA_MARK
15335                      : (pos_col < (colnr_T)(rex.input - rex.line)
15336                         ? t->state->c == NFA_MARK_GT
15337                         : t->state->c == NFA_MARK_LT))
15338                   : (pos->lnum < rex.lnum + rex.reg_firstlnum
15339                      ? t->state->c == NFA_MARK_GT
15340                      : t->state->c == NFA_MARK_LT);
15341          if (result) {
15342            add_here = true;
15343            add_state = t->state->out;
15344          }
15345        }
15346        break;
15347      }
15348
15349      case NFA_CURSOR:
15350        result = rex.reg_win != NULL
15351                 && (rex.lnum + rex.reg_firstlnum == rex.reg_win->w_cursor.lnum)
15352                 && ((colnr_T)(rex.input - rex.line) == rex.reg_win->w_cursor.col);
15353        if (result) {
15354          add_here = true;
15355          add_state = t->state->out;
15356        }
15357        break;
15358
15359      case NFA_VISUAL:
15360        result = reg_match_visual();
15361        if (result) {
15362          add_here = true;
15363          add_state = t->state->out;
15364        }
15365        break;
15366
15367      case NFA_MOPEN1:
15368      case NFA_MOPEN2:
15369      case NFA_MOPEN3:
15370      case NFA_MOPEN4:
15371      case NFA_MOPEN5:
15372      case NFA_MOPEN6:
15373      case NFA_MOPEN7:
15374      case NFA_MOPEN8:
15375      case NFA_MOPEN9:
15376      case NFA_ZOPEN:
15377      case NFA_ZOPEN1:
15378      case NFA_ZOPEN2:
15379      case NFA_ZOPEN3:
15380      case NFA_ZOPEN4:
15381      case NFA_ZOPEN5:
15382      case NFA_ZOPEN6:
15383      case NFA_ZOPEN7:
15384      case NFA_ZOPEN8:
15385      case NFA_ZOPEN9:
15386      case NFA_NOPEN:
15387      case NFA_ZSTART:
15388        // These states are only added to be able to bail out when
15389        // they are added again, nothing is to be done.
15390        break;
15391
15392      default:          // regular character
15393      {
15394        int c = t->state->c;
15395
15396#ifdef REGEXP_DEBUG
15397        if (c < 0) {
15398          siemsg("INTERNAL: Negative state char: %" PRId64, (int64_t)c);
15399        }
15400#endif
15401        result = (c == curc);
15402
15403        if (!result && rex.reg_ic) {
15404          result = utf_fold(c) == utf_fold(curc);
15405        }
15406
15407        // If rex.reg_icombine is not set only skip over the character
15408        // itself.  When it is set skip over composing characters.
15409        if (result && !rex.reg_icombine) {
15410          clen = utf_ptr2len((char *)rex.input);
15411        }
15412
15413        ADD_STATE_IF_MATCH(t->state);
15414        break;
15415      }
15416      }       // switch (t->state->c)
15417
15418      if (add_state != NULL) {
15419        nfa_pim_T *pim;
15420        nfa_pim_T pim_copy;
15421
15422        if (t->pim.result == NFA_PIM_UNUSED) {
15423          pim = NULL;
15424        } else {
15425          pim = &t->pim;
15426        }
15427
15428        // Handle the postponed invisible match if the match might end
15429        // without advancing and before the end of the line.
15430        if (pim != NULL && (clen == 0 || match_follows(add_state, 0))) {
15431          if (pim->result == NFA_PIM_TODO) {
15432#ifdef REGEXP_DEBUG
15433            fprintf(log_fd, "\n");
15434            fprintf(log_fd, "==================================\n");
15435            fprintf(log_fd, "Postponed recursive nfa_regmatch()\n");
15436            fprintf(log_fd, "\n");
15437#endif
15438            result = recursive_regmatch(pim->state, pim, prog, submatch, m,
15439                                        &listids, &listids_len);
15440            pim->result = result ? NFA_PIM_MATCH : NFA_PIM_NOMATCH;
15441            // for \@! and \@<! it is a match when the result is
15442            // false
15443            if (result != (pim->state->c == NFA_START_INVISIBLE_NEG
15444                           || pim->state->c == NFA_START_INVISIBLE_NEG_FIRST
15445                           || pim->state->c
15446                           == NFA_START_INVISIBLE_BEFORE_NEG
15447                           || pim->state->c
15448                           == NFA_START_INVISIBLE_BEFORE_NEG_FIRST)) {
15449              // Copy submatch info from the recursive call
15450              copy_sub_off(&pim->subs.norm, &m->norm);
15451              if (rex.nfa_has_zsubexpr) {
15452                copy_sub_off(&pim->subs.synt, &m->synt);
15453              }
15454            }
15455          } else {
15456            result = (pim->result == NFA_PIM_MATCH);
15457#ifdef REGEXP_DEBUG
15458            fprintf(log_fd, "\n");
15459            fprintf(log_fd,
15460                    "Using previous recursive nfa_regmatch() result, result == %d\n",
15461                    pim->result);
15462            fprintf(log_fd, "MATCH = %s\n", result ? "OK" : "false");
15463            fprintf(log_fd, "\n");
15464#endif
15465          }
15466
15467          // for \@! and \@<! it is a match when result is false
15468          if (result != (pim->state->c == NFA_START_INVISIBLE_NEG
15469                         || pim->state->c == NFA_START_INVISIBLE_NEG_FIRST
15470                         || pim->state->c
15471                         == NFA_START_INVISIBLE_BEFORE_NEG
15472                         || pim->state->c
15473                         == NFA_START_INVISIBLE_BEFORE_NEG_FIRST)) {
15474            // Copy submatch info from the recursive call
15475            copy_sub_off(&t->subs.norm, &pim->subs.norm);
15476            if (rex.nfa_has_zsubexpr) {
15477              copy_sub_off(&t->subs.synt, &pim->subs.synt);
15478            }
15479          } else {
15480            // look-behind match failed, don't add the state
15481            continue;
15482          }
15483
15484          // Postponed invisible match was handled, don't add it to
15485          // following states.
15486          pim = NULL;
15487        }
15488
15489        // If "pim" points into l->t it will become invalid when
15490        // adding the state causes the list to be reallocated.  Make a
15491        // local copy to avoid that.
15492        if (pim == &t->pim) {
15493          copy_pim(&pim_copy, pim);
15494          pim = &pim_copy;
15495        }
15496
15497        if (add_here) {
15498          r = addstate_here(thislist, add_state, &t->subs, pim, &listidx);
15499        } else {
15500          r = addstate(nextlist, add_state, &t->subs, pim, add_off, 0);
15501          if (add_count > 0) {
15502            nextlist->t[nextlist->n - 1].count = add_count;
15503          }
15504        }
15505        if (r == NULL) {
15506          nfa_match = NFA_TOO_EXPENSIVE;
15507          goto theend;
15508        }
15509      }
15510    }     // for (thislist = thislist; thislist->state; thislist++)
15511
15512    // Look for the start of a match in the current position by adding the
15513    // start state to the list of states.
15514    // The first found match is the leftmost one, thus the order of states
15515    // matters!
15516    // Do not add the start state in recursive calls of nfa_regmatch(),
15517    // because recursive calls should only start in the first position.
15518    // Unless "nfa_endp" is not NULL, then we match the end position.
15519    // Also don't start a match past the first line.
15520    if (!nfa_match
15521        && ((toplevel
15522             && rex.lnum == 0
15523             && clen != 0
15524             && (rex.reg_maxcol == 0
15525                 || (colnr_T)(rex.input - rex.line) < rex.reg_maxcol))
15526            || (nfa_endp != NULL
15527                && (REG_MULTI
15528                    ? (rex.lnum < nfa_endp->se_u.pos.lnum
15529                       || (rex.lnum == nfa_endp->se_u.pos.lnum
15530                           && (int)(rex.input - rex.line)
15531                           < nfa_endp->se_u.pos.col))
15532                    : rex.input < nfa_endp->se_u.ptr)))) {
15533#ifdef REGEXP_DEBUG
15534      fprintf(log_fd, "(---) STARTSTATE\n");
15535#endif
15536      // Inline optimized code for addstate() if we know the state is
15537      // the first MOPEN.
15538      if (toplevel) {
15539        int add = true;
15540
15541        if (prog->regstart != NUL && clen != 0) {
15542          if (nextlist->n == 0) {
15543            colnr_T col = (colnr_T)(rex.input - rex.line) + clen;
15544
15545            // Nextlist is empty, we can skip ahead to the
15546            // character that must appear at the start.
15547            if (skip_to_start(prog->regstart, &col) == FAIL) {
15548              break;
15549            }
15550#ifdef REGEXP_DEBUG
15551            fprintf(log_fd, "  Skipping ahead %d bytes to regstart\n",
15552                    col - ((colnr_T)(rex.input - rex.line) + clen));
15553#endif
15554            rex.input = rex.line + col - clen;
15555          } else {
15556            // Checking if the required start character matches is
15557            // cheaper than adding a state that won't match.
15558            const int c = utf_ptr2char((char *)rex.input + clen);
15559            if (c != prog->regstart
15560                && (!rex.reg_ic
15561                    || utf_fold(c) != utf_fold(prog->regstart))) {
15562#ifdef REGEXP_DEBUG
15563              fprintf(log_fd,
15564                      "  Skipping start state, regstart does not match\n");
15565#endif
15566              add = false;
15567            }
15568          }
15569        }
15570
15571        if (add) {
15572          if (REG_MULTI) {
15573            m->norm.list.multi[0].start_col =
15574              (colnr_T)(rex.input - rex.line) + clen;
15575            m->norm.orig_start_col =
15576              m->norm.list.multi[0].start_col;
15577          } else {
15578            m->norm.list.line[0].start = rex.input + clen;
15579          }
15580          if (addstate(nextlist, start->out, m, NULL, clen, 0) == NULL) {
15581            nfa_match = NFA_TOO_EXPENSIVE;
15582            goto theend;
15583          }
15584        }
15585      } else {
15586        uint8_t *save_line = rex.line;
15587        uint8_t *save_input = rex.input;
15588        linenr_T save_lnum = rex.lnum;
15589
15590        // At the end of a line the match can only start on the next
15591        // line, use that position instead of the line break.
15592        if (REG_MULTI && clen == 0 && nfa_endp != NULL
15593            && rex.lnum < nfa_endp->se_u.pos.lnum) {
15594          char *next_line = reg_getline(rex.lnum + 1);
15595
15596          if (next_line != NULL) {
15597            rex.line = (uint8_t *)next_line;
15598            rex.input = rex.line;
15599            rex.lnum++;
15600          }
15601        }
15602
15603        r = addstate(nextlist, start, m, NULL, clen, 0);
15604
15605        rex.line = save_line;
15606        rex.input = save_input;
15607        rex.lnum = save_lnum;
15608
15609        if (r == NULL) {
15610          nfa_match = NFA_TOO_EXPENSIVE;
15611          goto theend;
15612        }
15613      }
15614    }
15615
15616#ifdef REGEXP_DEBUG
15617    fprintf(log_fd, ">>> Thislist had %d states available: ", thislist->n);
15618    {
15619      int i;
15620
15621      for (i = 0; i < thislist->n; i++) {
15622        fprintf(log_fd, "%d  ", abs(thislist->t[i].state->id));
15623      }
15624    }
15625    fprintf(log_fd, "\n");
15626#endif
15627
15628nextchar:
15629    // Advance to the next character, or advance to the next line, or
15630    // finish.
15631    if (clen != 0) {
15632      rex.input += clen;
15633    } else if (go_to_nextline || (nfa_endp != NULL && REG_MULTI
15634                                  && rex.lnum < nfa_endp->se_u.pos.lnum)) {
15635      reg_nextline();
15636    } else {
15637      break;
15638    }
15639
15640    // Allow interrupting with CTRL-C.
15641    reg_breakcheck();
15642    if (got_int) {
15643      break;
15644    }
15645    // Check for timeout once every twenty times to avoid overhead.
15646    if (nfa_time_limit != NULL && ++nfa_time_count == 20) {
15647      nfa_time_count = 0;
15648      if (nfa_did_time_out()) {
15649        break;
15650      }
15651    }
15652  }
15653
15654#ifdef REGEXP_DEBUG
15655  if (log_fd != stderr) {
15656    fclose(log_fd);
15657  }
15658  log_fd = NULL;
15659#endif
15660
15661theend:
15662  // Free memory
15663  // Cache list buffers in prog for reuse, or free if prog already has
15664  // cached buffers (recursive call case).
15665  if (prog->listbuf[0] == NULL && list[0].t != NULL && list[1].t != NULL) {
15666    prog->listbuf[0] = list[0].t;
15667    prog->listbuf[1] = list[1].t;
15668  } else {
15669    xfree(list[0].t);
15670    xfree(list[1].t);
15671  }
15672  xfree(listids);
15673#undef ADD_STATE_IF_MATCH
15674#ifdef NFA_REGEXP_DEBUG_LOG
15675  fclose(debug);
15676#endif
15677
15678  return nfa_match;
15679}
15680
15681/// Try match of "prog" with at rex.line["col"].
15682///
15683/// @param tm         timeout limit or NULL
15684/// @param timed_out  flag set on timeout or NULL
15685///
15686/// @return  <= 0 for failure, number of lines contained in the match otherwise.
15687static int nfa_regtry(nfa_regprog_T *prog, colnr_T col, proftime_T *tm, int *timed_out)
15688{
15689  int i;
15690  regsubs_T subs, m;
15691  nfa_state_T *start = prog->start;
15692#ifdef REGEXP_DEBUG
15693  FILE *f;
15694#endif
15695
15696  rex.input = rex.line + col;
15697  nfa_time_limit = tm;
15698  nfa_timed_out = timed_out;
15699  nfa_time_count = 0;
15700
15701#ifdef REGEXP_DEBUG
15702  f = fopen(NFA_REGEXP_RUN_LOG, "a");
15703  if (f != NULL) {
15704    fprintf(f,
15705            "\n\n\t=======================================================\n");
15706# ifdef REGEXP_DEBUG
15707    fprintf(f, "\tRegexp is \"%s\"\n", nfa_regengine.expr);
15708# endif
15709    fprintf(f, "\tInput text is \"%s\" \n", rex.input);
15710    fprintf(f, "\t=======================================================\n\n");
15711    nfa_print_state(f, start);
15712    fprintf(f, "\n\n");
15713    fclose(f);
15714  } else {
15715    emsg("Could not open temporary log file for writing");
15716  }
15717#endif
15718
15719  clear_sub(&subs.norm);
15720  clear_sub(&m.norm);
15721  clear_sub(&subs.synt);
15722  clear_sub(&m.synt);
15723
15724  int result = nfa_regmatch(prog, start, &subs, &m);
15725  if (!result) {
15726    return 0;
15727  } else if (result == NFA_TOO_EXPENSIVE) {
15728    return result;
15729  }
15730
15731  cleanup_subexpr();
15732  if (REG_MULTI) {
15733    for (i = 0; i < subs.norm.in_use; i++) {
15734      rex.reg_startpos[i].lnum = subs.norm.list.multi[i].start_lnum;
15735      rex.reg_startpos[i].col = subs.norm.list.multi[i].start_col;
15736
15737      rex.reg_endpos[i].lnum = subs.norm.list.multi[i].end_lnum;
15738      rex.reg_endpos[i].col = subs.norm.list.multi[i].end_col;
15739    }
15740    if (rex.reg_mmatch != NULL) {
15741      rex.reg_mmatch->rmm_matchcol = subs.norm.orig_start_col;
15742    }
15743
15744    if (rex.reg_startpos[0].lnum < 0) {
15745      rex.reg_startpos[0].lnum = 0;
15746      rex.reg_startpos[0].col = col;
15747    }
15748    if (rex.reg_endpos[0].lnum < 0) {
15749      // pattern has a \ze but it didn't match, use current end
15750      rex.reg_endpos[0].lnum = rex.lnum;
15751      rex.reg_endpos[0].col = (int)(rex.input - rex.line);
15752    } else {
15753      // Use line number of "\ze".
15754      rex.lnum = rex.reg_endpos[0].lnum;
15755    }
15756  } else {
15757    for (i = 0; i < subs.norm.in_use; i++) {
15758      rex.reg_startp[i] = subs.norm.list.line[i].start;
15759      rex.reg_endp[i] = subs.norm.list.line[i].end;
15760    }
15761
15762    if (rex.reg_startp[0] == NULL) {
15763      rex.reg_startp[0] = rex.line + col;
15764    }
15765    if (rex.reg_endp[0] == NULL) {
15766      rex.reg_endp[0] = rex.input;
15767    }
15768  }
15769
15770  // Package any found \z(...\) matches for export. Default is none.
15771  unref_extmatch(re_extmatch_out);
15772  re_extmatch_out = NULL;
15773
15774  if (prog->reghasz == REX_SET) {
15775    cleanup_zsubexpr();
15776    re_extmatch_out = make_extmatch();
15777    // Loop over \z1, \z2, etc.  There is no \z0.
15778    for (i = 1; i < subs.synt.in_use; i++) {
15779      if (REG_MULTI) {
15780        struct multipos *mpos = &subs.synt.list.multi[i];
15781
15782        // Only accept single line matches that are valid.
15783        if (mpos->start_lnum >= 0
15784            && mpos->start_lnum == mpos->end_lnum
15785            && mpos->end_col >= mpos->start_col) {
15786          re_extmatch_out->matches[i] =
15787            (uint8_t *)xstrnsave(reg_getline(mpos->start_lnum) + mpos->start_col,
15788                                 (size_t)(mpos->end_col - mpos->start_col));
15789        }
15790      } else {
15791        struct linepos *lpos = &subs.synt.list.line[i];
15792
15793        if (lpos->start != NULL && lpos->end != NULL) {
15794          re_extmatch_out->matches[i] =
15795            (uint8_t *)xstrnsave((char *)lpos->start, (size_t)(lpos->end - lpos->start));
15796        }
15797      }
15798    }
15799  }
15800
15801  return 1 + rex.lnum;
15802}
15803
15804/// Match a regexp against a string ("line" points to the string) or multiple
15805/// lines (if "line" is NULL, use reg_getline()).
15806///
15807/// @param line String in which to search or NULL
15808/// @param startcol Column to start looking for match
15809/// @param tm Timeout limit or NULL
15810/// @param timed_out Flag set on timeout or NULL
15811///
15812/// @return <= 0 if there is no match and number of lines contained in the
15813/// match otherwise.
15814static int nfa_regexec_both(uint8_t *line, colnr_T startcol, proftime_T *tm, int *timed_out)
15815{
15816  nfa_regprog_T *prog;
15817  int retval = 0;
15818  colnr_T col = startcol;
15819
15820  if (REG_MULTI) {
15821    prog = (nfa_regprog_T *)rex.reg_mmatch->regprog;
15822    line = (uint8_t *)reg_getline(0);  // relative to the cursor
15823    rex.reg_startpos = rex.reg_mmatch->startpos;
15824    rex.reg_endpos = rex.reg_mmatch->endpos;
15825  } else {
15826    prog = (nfa_regprog_T *)rex.reg_match->regprog;
15827    rex.reg_startp = (uint8_t **)rex.reg_match->startp;
15828    rex.reg_endp = (uint8_t **)rex.reg_match->endp;
15829  }
15830
15831  // Be paranoid...
15832  if (prog == NULL || line == NULL) {
15833    iemsg(_(e_null));
15834    goto theend;
15835  }
15836
15837  // If pattern contains "\c" or "\C": overrule value of rex.reg_ic
15838  if (prog->regflags & RF_ICASE) {
15839    rex.reg_ic = true;
15840  } else if (prog->regflags & RF_NOICASE) {
15841    rex.reg_ic = false;
15842  }
15843
15844  // If pattern contains "\Z" overrule value of rex.reg_icombine
15845  if (prog->regflags & RF_ICOMBINE) {
15846    rex.reg_icombine = true;
15847  }
15848
15849  rex.line = line;
15850  rex.lnum = 0;  // relative to line
15851
15852  rex.nfa_has_zend = prog->has_zend;
15853  rex.nfa_has_backref = prog->has_backref;
15854  rex.nfa_nsubexpr = prog->nsubexp;
15855  rex.nfa_listid = 1;
15856  rex.nfa_alt_listid = 2;
15857#ifdef REGEXP_DEBUG
15858  nfa_regengine.expr = prog->pattern;
15859#endif
15860
15861  if (prog->reganch && col > 0) {
15862    return 0L;
15863  }
15864
15865  rex.need_clear_subexpr = true;
15866  // Clear the external match subpointers if necessary.
15867  if (prog->reghasz == REX_SET) {
15868    rex.nfa_has_zsubexpr = true;
15869    rex.need_clear_zsubexpr = true;
15870  } else {
15871    rex.nfa_has_zsubexpr = false;
15872    rex.need_clear_zsubexpr = false;
15873  }
15874
15875  if (prog->regstart != NUL) {
15876    // Skip ahead until a character we know the match must start with.
15877    // When there is none there is no match.
15878    if (skip_to_start(prog->regstart, &col) == FAIL) {
15879      return 0L;
15880    }
15881
15882    // If match_text is set it contains the full text that must match.
15883    // Nothing else to try. Doesn't handle combining chars well.
15884    if (prog->match_text != NULL && *prog->match_text != NUL && !rex.reg_icombine) {
15885      retval = find_match_text(&col, prog->regstart, prog->match_text);
15886      if (REG_MULTI) {
15887        rex.reg_mmatch->rmm_matchcol = col;
15888      } else {
15889        rex.reg_match->rm_matchcol = col;
15890      }
15891      return retval;
15892    }
15893  }
15894
15895  // If the start column is past the maximum column: no need to try.
15896  if (rex.reg_maxcol > 0 && col >= rex.reg_maxcol) {
15897    goto theend;
15898  }
15899
15900  // Set the "nstate" used by nfa_regcomp() to zero to trigger an error when
15901  // it's accidentally used during execution.
15902  nstate = 0;
15903  for (int i = 0; i < prog->nstate; i++) {
15904    prog->state[i].id = i;
15905    prog->state[i].lastlist[0] = 0;
15906    prog->state[i].lastlist[1] = 0;
15907  }
15908
15909  retval = nfa_regtry(prog, col, tm, timed_out);
15910
15911#ifdef REGEXP_DEBUG
15912  nfa_regengine.expr = NULL;
15913#endif
15914
15915theend:
15916  if (retval > 0) {
15917    // Make sure the end is never before the start.  Can happen when \zs and
15918    // \ze are used.
15919    if (REG_MULTI) {
15920      const lpos_T *const start = &rex.reg_mmatch->startpos[0];
15921      const lpos_T *const end = &rex.reg_mmatch->endpos[0];
15922
15923      if (end->lnum < start->lnum
15924          || (end->lnum == start->lnum && end->col < start->col)) {
15925        rex.reg_mmatch->endpos[0] = rex.reg_mmatch->startpos[0];
15926      }
15927    } else {
15928      if (rex.reg_match->endp[0] < rex.reg_match->startp[0]) {
15929        rex.reg_match->endp[0] = rex.reg_match->startp[0];
15930      }
15931
15932      // startpos[0] may be set by "\zs", also return the column where
15933      // the whole pattern matched.
15934      rex.reg_match->rm_matchcol = col;
15935    }
15936  }
15937
15938  return retval;
15939}
15940
15941// Compile a regular expression into internal code for the NFA matcher.
15942// Returns the program in allocated space.  Returns NULL for an error.
15943static regprog_T *nfa_regcomp(uint8_t *expr, int re_flags)
15944{
15945  nfa_regprog_T *prog = NULL;
15946  int *postfix;
15947
15948  if (expr == NULL) {
15949    return NULL;
15950  }
15951
15952#ifdef REGEXP_DEBUG
15953  nfa_regengine.expr = expr;
15954#endif
15955  nfa_re_flags = re_flags;
15956
15957  init_class_tab();
15958
15959  nfa_regcomp_start(expr, re_flags);
15960
15961  // Build postfix form of the regexp. Needed to build the NFA
15962  // (and count its size).
15963  postfix = re2post();
15964  if (postfix == NULL) {
15965    goto fail;              // Cascaded (syntax?) error
15966  }
15967
15968  // In order to build the NFA, we parse the input regexp twice:
15969  // 1. first pass to count size (so we can allocate space)
15970  // 2. second to emit code
15971#ifdef REGEXP_DEBUG
15972  {
15973    FILE *f = fopen(NFA_REGEXP_RUN_LOG, "a");
15974
15975    if (f != NULL) {
15976      fprintf(f,
15977              "\n*****************************\n\n\n\n\t"
15978              "Compiling regexp \"%s\"... hold on !\n",
15979              expr);
15980      fclose(f);
15981    }
15982  }
15983#endif
15984
15985  // PASS 1
15986  // Count number of NFA states in "nstate". Do not build the NFA.
15987  post2nfa(postfix, post_ptr, true);
15988
15989  // allocate the regprog with space for the compiled regexp
15990  size_t prog_size = offsetof(nfa_regprog_T, state) + sizeof(nfa_state_T) * (size_t)nstate;
15991  prog = xmalloc(prog_size);
15992  state_ptr = prog->state;
15993  prog->re_in_use = false;
15994  prog->listbuf[0] = NULL;
15995  prog->listbuf[1] = NULL;
15996
15997  // PASS 2
15998  // Build the NFA
15999  prog->start = post2nfa(postfix, post_ptr, false);
16000  if (prog->start == NULL) {
16001    goto fail;
16002  }
16003  prog->regflags = regflags;
16004  prog->engine = &nfa_regengine;
16005  prog->nstate = nstate;
16006  prog->has_zend = rex.nfa_has_zend;
16007  prog->has_backref = rex.nfa_has_backref;
16008  prog->nsubexp = regnpar;
16009
16010  nfa_postprocess(prog);
16011
16012  prog->reganch = nfa_get_reganch(prog->start, 0);
16013  prog->regstart = nfa_get_regstart(prog->start, 0);
16014  prog->match_text = nfa_get_match_text(prog->start);
16015
16016#ifdef REGEXP_DEBUG
16017  nfa_postfix_dump(expr, OK);
16018  nfa_dump(prog);
16019#endif
16020  // Remember whether this pattern has any \z specials in it.
16021  prog->reghasz = re_has_z;
16022  prog->pattern = xstrdup((char *)expr);
16023#ifdef REGEXP_DEBUG
16024  nfa_regengine.expr = NULL;
16025#endif
16026
16027out:
16028  // The postfix list and fragment stack are reused by the next compilation
16029  // (and freed in free_regexp_stuff()), but drop ones that grew large for a
16030  // big pattern to avoid holding much memory.
16031  if (post_start_len > NFA_POSTFIX_KEEP) {
16032    XFREE_CLEAR(post_start);
16033    post_start_len = 0;
16034  }
16035  post_ptr = post_end = NULL;
16036  if (nfa_stack_len > NFA_STACK_KEEP) {
16037    XFREE_CLEAR(nfa_stack);
16038    nfa_stack_len = 0;
16039  }
16040  state_ptr = NULL;
16041  return (regprog_T *)prog;
16042
16043fail:
16044  XFREE_CLEAR(prog);
16045#ifdef REGEXP_DEBUG
16046  nfa_postfix_dump(expr, FAIL);
16047  nfa_regengine.expr = NULL;
16048#endif
16049  goto out;
16050}
16051
16052// Free a compiled regexp program, returned by nfa_regcomp().
16053static void nfa_regfree(regprog_T *prog)
16054{
16055  if (prog == NULL) {
16056    return;
16057  }
16058
16059  xfree(((nfa_regprog_T *)prog)->match_text);
16060  xfree(((nfa_regprog_T *)prog)->pattern);
16061  xfree(((nfa_regprog_T *)prog)->listbuf[0]);
16062  xfree(((nfa_regprog_T *)prog)->listbuf[1]);
16063  xfree(prog);
16064}
16065
16066/// Match a regexp against a string.
16067/// "rmp->regprog" is a compiled regexp as returned by nfa_regcomp().
16068/// Uses curbuf for line count and 'iskeyword'.
16069/// If "line_lbr" is true, consider a "\n" in "line" to be a line break.
16070///
16071/// @param line  string to match against
16072/// @param col   column to start looking for match
16073///
16074/// @return  <= 0 for failure, number of lines contained in the match otherwise.
16075static int nfa_regexec_nl(regmatch_T *rmp, uint8_t *line, colnr_T col, bool line_lbr)
16076{
16077  rex.reg_match = rmp;
16078  rex.reg_mmatch = NULL;
16079  rex.reg_maxline = 0;
16080  rex.reg_line_lbr = line_lbr;
16081  rex.reg_buf = curbuf;
16082  rex.reg_win = NULL;
16083  rex.reg_ic = rmp->rm_ic;
16084  rex.reg_icombine = false;
16085  rex.reg_nobreak = rmp->regprog->re_flags & RE_NOBREAK;
16086  rex.reg_maxcol = 0;
16087  return nfa_regexec_both(line, col, NULL, NULL);
16088}
16089
16090/// Matches a regexp against multiple lines.
16091/// "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
16092/// Uses curbuf for line count and 'iskeyword'.
16093///
16094/// @param win Window in which to search or NULL
16095/// @param buf Buffer in which to search
16096/// @param lnum Number of line to start looking for match
16097/// @param col Column to start looking for match
16098/// @param tm Timeout limit or NULL
16099/// @param timed_out Flag set on timeout or NULL
16100///
16101/// @return <= 0 if there is no match and number of lines contained in the match
16102/// otherwise.
16103///
16104/// @note The body is the same as bt_regexec() except for nfa_regexec_both()
16105///
16106/// @warning
16107/// Match may actually be in another line. e.g.:
16108/// when r.e. is \nc, cursor is at 'a' and the text buffer looks like
16109///
16110/// @par
16111///
16112///     +-------------------------+
16113///     |a                        |
16114///     |b                        |
16115///     |c                        |
16116///     |                         |
16117///     +-------------------------+
16118///
16119/// @par
16120/// then nfa_regexec_multi() returns 3. while the original vim_regexec_multi()
16121/// returns 0 and a second call at line 2 will return 2.
16122///
16123/// @par
16124/// FIXME if this behavior is not compatible.
16125static int nfa_regexec_multi(regmmatch_T *rmp, win_T *win, buf_T *buf, linenr_T lnum, colnr_T col,
16126                             proftime_T *tm, int *timed_out)
16127{
16128  init_regexec_multi(rmp, win, buf, lnum);
16129  return nfa_regexec_both(NULL, col, tm, timed_out);
16130}
16131// }}}1
16132
16133static regengine_T bt_regengine = {
16134  bt_regcomp,
16135  bt_regfree,
16136  bt_regexec_nl,
16137  bt_regexec_multi,
16138#ifdef REGEXP_DEBUG
16139  "",
16140#endif
16141};
16142
16143static regengine_T nfa_regengine = {
16144  nfa_regcomp,
16145  nfa_regfree,
16146  nfa_regexec_nl,
16147  nfa_regexec_multi,
16148#ifdef REGEXP_DEBUG
16149  "",
16150#endif
16151};
16152
16153// Which regexp engine to use? Needed for vim_regcomp().
16154// Must match with 'regexpengine'.
16155static int regexp_engine = 0;
16156
16157#ifdef REGEXP_DEBUG
16158static const uint8_t regname[][30] = {
16159  "AUTOMATIC Regexp Engine",
16160  "BACKTRACKING Regexp Engine",
16161  "NFA Regexp Engine"
16162};
16163#endif
16164
16165// Compile a regular expression into internal code.
16166// Returns the program in allocated memory.
16167// Use vim_regfree() to free the memory.
16168// Returns NULL for an error.
16169regprog_T *vim_regcomp(const char *expr_arg, int re_flags)
16170{
16171  regprog_T *prog = NULL;
16172  const char *expr = expr_arg;
16173
16174  regexp_engine = (int)p_re;
16175
16176  // Check for prefix "\%#=", that sets the regexp engine
16177  if (strncmp(expr, "\\%#=", 4) == 0) {
16178    int newengine = expr[4] - '0';
16179
16180    if (newengine == AUTOMATIC_ENGINE
16181        || newengine == BACKTRACKING_ENGINE
16182        || newengine == NFA_ENGINE) {
16183      regexp_engine = expr[4] - '0';
16184      expr += 5;
16185#ifdef REGEXP_DEBUG
16186      smsg(0, "New regexp mode selected (%d): %s",
16187           regexp_engine,
16188           regname[newengine]);
16189#endif
16190    } else {
16191      emsg(_("E864: \\%#= can only be followed by 0, 1, or 2. The automatic engine will be used "));
16192      regexp_engine = AUTOMATIC_ENGINE;
16193    }
16194  }
16195#ifdef REGEXP_DEBUG
16196  bt_regengine.expr = expr;
16197  nfa_regengine.expr = expr;
16198#endif
16199  // reg_iswordc() uses rex.reg_buf
16200  rex.reg_buf = curbuf;
16201
16202  //
16203  // First try the NFA engine, unless backtracking was requested.
16204  //
16205  const int called_emsg_before = called_emsg;
16206  if (regexp_engine != BACKTRACKING_ENGINE) {
16207    prog = nfa_regengine.regcomp((uint8_t *)expr,
16208                                 re_flags + (regexp_engine == AUTOMATIC_ENGINE ? RE_AUTO : 0));
16209  } else {
16210    prog = bt_regengine.regcomp((uint8_t *)expr, re_flags);
16211  }
16212
16213  // Check for error compiling regexp with initial engine.
16214  if (prog == NULL) {
16215#ifdef BT_REGEXP_DEBUG_LOG
16216    // Debugging log for BT engine.
16217    if (regexp_engine != BACKTRACKING_ENGINE) {
16218      FILE *f = fopen(BT_REGEXP_DEBUG_LOG_NAME, "a");
16219      if (f) {
16220        fprintf(f, "Syntax error in \"%s\"\n", expr);
16221        fclose(f);
16222      } else {
16223        semsg("(NFA) Could not open \"%s\" to write !!!",
16224              BT_REGEXP_DEBUG_LOG_NAME);
16225      }
16226    }
16227#endif
16228    // If the NFA engine failed, try the backtracking engine. The NFA engine
16229    // also fails for patterns that it can't handle well but are still valid
16230    // patterns, thus a retry should work.
16231    // But don't try if an error message was given.
16232    if (regexp_engine == AUTOMATIC_ENGINE && called_emsg == called_emsg_before) {
16233      regexp_engine = BACKTRACKING_ENGINE;
16234      report_re_switch(expr);
16235      prog = bt_regengine.regcomp((uint8_t *)expr, re_flags);
16236    }
16237  }
16238
16239  if (prog != NULL) {
16240    // Store the info needed to call regcomp() again when the engine turns out
16241    // to be very slow when executing it.
16242    prog->re_engine = (unsigned)regexp_engine;
16243    prog->re_flags = (unsigned)re_flags;
16244  }
16245
16246  return prog;
16247}
16248
16249// Free a compiled regexp program, returned by vim_regcomp().
16250void vim_regfree(regprog_T *prog)
16251{
16252  if (prog != NULL) {
16253    prog->engine->regfree(prog);
16254  }
16255}
16256
16257#ifdef EXITFREE
16258void free_regexp_stuff(void)
16259{
16260  ga_clear(&regstack);
16261  ga_clear(&backpos);
16262  xfree(reg_tofree);
16263  xfree(reg_prev_sub);
16264  xfree(post_start);   // NFA postfix buffer, reused across compilations
16265  post_start = NULL;
16266  post_start_len = 0;
16267  xfree(nfa_stack);    // NFA fragment stack, reused across compilations
16268  nfa_stack = NULL;
16269  nfa_stack_len = 0;
16270}
16271
16272#endif
16273
16274static void report_re_switch(const char *pat)
16275{
16276  if (p_verbose > 0) {
16277    verbose_enter();
16278    msg_puts(_("Switching to backtracking RE engine for pattern: "));
16279    msg_puts(pat);
16280    verbose_leave();
16281  }
16282}
16283
16284/// Match a regexp against a string.
16285/// "rmp->regprog" must be a compiled regexp as returned by vim_regcomp().
16286/// Note: "rmp->regprog" may be freed and changed.
16287/// Uses curbuf for line count and 'iskeyword'.
16288/// When "nl" is true consider a "\n" in "line" to be a line break.
16289///
16290/// @param rmp
16291/// @param line the string to match against
16292/// @param col  the column to start looking for match
16293/// @param nl
16294///
16295/// @return true if there is a match, false if not.
16296static bool vim_regexec_string(regmatch_T *rmp, const char *line, colnr_T col, bool nl)
16297{
16298  regexec_T rex_save;
16299  bool rex_in_use_save = rex_in_use;
16300
16301  // Cannot use the same prog recursively, it contains state.
16302  if (rmp->regprog->re_in_use) {
16303    emsg(_(e_recursive));
16304    return false;
16305  }
16306  rmp->regprog->re_in_use = true;
16307
16308  if (rex_in_use) {
16309    // Being called recursively, save the state.
16310    rex_save = rex;
16311  }
16312  rex_in_use = true;
16313
16314  rex.reg_startp = NULL;
16315  rex.reg_endp = NULL;
16316  rex.reg_startpos = NULL;
16317  rex.reg_endpos = NULL;
16318
16319  int result = rmp->regprog->engine->regexec_nl(rmp, (uint8_t *)line, col, nl);
16320  rmp->regprog->re_in_use = false;
16321
16322  // NFA engine aborted because it's very slow, use backtracking engine instead.
16323  if (rmp->regprog->re_engine == AUTOMATIC_ENGINE
16324      && result == NFA_TOO_EXPENSIVE) {
16325    int save_p_re = (int)p_re;
16326    int re_flags = (int)rmp->regprog->re_flags;
16327    char *pat = xstrdup(((nfa_regprog_T *)rmp->regprog)->pattern);
16328
16329    p_re = BACKTRACKING_ENGINE;
16330    regprog_T *prev_prog = rmp->regprog;
16331    report_re_switch(pat);
16332    rmp->regprog = vim_regcomp(pat, re_flags);
16333    if (rmp->regprog == NULL) {
16334      // Somehow compiling the pattern failed now, put back the
16335      // previous one to avoid "regprog" becoming NULL.
16336      rmp->regprog = prev_prog;
16337    } else {
16338      vim_regfree(prev_prog);
16339      rmp->regprog->re_in_use = true;
16340      result = rmp->regprog->engine->regexec_nl(rmp, (uint8_t *)line, col, nl);
16341      rmp->regprog->re_in_use = false;
16342    }
16343
16344    xfree(pat);
16345    p_re = save_p_re;
16346  }
16347
16348  rex_in_use = rex_in_use_save;
16349  if (rex_in_use) {
16350    rex = rex_save;
16351  }
16352
16353  return result > 0;
16354}
16355
16356// Note: "*prog" may be freed and changed.
16357// Return true if there is a match, false if not.
16358bool vim_regexec_prog(regprog_T **prog, bool ignore_case, const char *line, colnr_T col)
16359{
16360  regmatch_T regmatch = { .regprog = *prog, .rm_ic = ignore_case };
16361  bool r = vim_regexec_string(&regmatch, line, col, false);
16362  *prog = regmatch.regprog;
16363  return r;
16364}
16365
16366// Note: "rmp->regprog" may be freed and changed.
16367// Return true if there is a match, false if not.
16368bool vim_regexec(regmatch_T *rmp, const char *line, colnr_T col)
16369{
16370  return vim_regexec_string(rmp, line, col, false);
16371}
16372
16373// Like vim_regexec(), but consider a "\n" in "line" to be a line break.
16374// Note: "rmp->regprog" may be freed and changed.
16375// Return true if there is a match, false if not.
16376bool vim_regexec_nl(regmatch_T *rmp, const char *line, colnr_T col)
16377{
16378  return vim_regexec_string(rmp, line, col, true);
16379}
16380
16381/// Match a regexp against multiple lines.
16382/// "rmp->regprog" must be a compiled regexp as returned by vim_regcomp().
16383/// Note: "rmp->regprog" may be freed and changed, even set to NULL.
16384/// Uses curbuf for line count and 'iskeyword'.
16385///
16386/// @param win        window in which to search or NULL
16387/// @param buf        buffer in which to search
16388/// @param lnum       nr of line to start looking for match
16389/// @param col        column to start looking for match
16390/// @param tm         timeout limit or NULL
16391/// @param timed_out  flag is set when timeout limit reached
16392///
16393/// @return  zero if there is no match.  Return number of lines contained in the
16394///          match otherwise.
16395int vim_regexec_multi(regmmatch_T *rmp, win_T *win, buf_T *buf, linenr_T lnum, colnr_T col,
16396                      proftime_T *tm, int *timed_out)
16397  FUNC_ATTR_NONNULL_ARG(1)
16398{
16399  regexec_T rex_save;
16400  bool rex_in_use_save = rex_in_use;
16401
16402  // Cannot use the same prog recursively, it contains state.
16403  if (rmp->regprog->re_in_use) {
16404    emsg(_(e_recursive));
16405    return false;
16406  }
16407  rmp->regprog->re_in_use = true;
16408
16409  if (rex_in_use) {
16410    // Being called recursively, save the state.
16411    rex_save = rex;
16412  }
16413  rex_in_use = true;
16414
16415  int result = rmp->regprog->engine->regexec_multi(rmp, win, buf, lnum, col, tm, timed_out);
16416  rmp->regprog->re_in_use = false;
16417
16418  // NFA engine aborted because it's very slow, use backtracking engine instead.
16419  if (rmp->regprog->re_engine == AUTOMATIC_ENGINE
16420      && result == NFA_TOO_EXPENSIVE) {
16421    int save_p_re = (int)p_re;
16422    int re_flags = (int)rmp->regprog->re_flags;
16423    char *pat = xstrdup(((nfa_regprog_T *)rmp->regprog)->pattern);
16424
16425    p_re = BACKTRACKING_ENGINE;
16426    regprog_T *prev_prog = rmp->regprog;
16427
16428    report_re_switch(pat);
16429    // checking for \z misuse was already done when compiling for NFA,
16430    // allow all here
16431    reg_do_extmatch = REX_ALL;
16432    rmp->regprog = vim_regcomp(pat, re_flags);
16433    reg_do_extmatch = 0;
16434
16435    if (rmp->regprog == NULL) {
16436      // Somehow compiling the pattern failed now, put back the
16437      // previous one to avoid "regprog" becoming NULL.
16438      rmp->regprog = prev_prog;
16439    } else {
16440      vim_regfree(prev_prog);
16441
16442      rmp->regprog->re_in_use = true;
16443      result = rmp->regprog->engine->regexec_multi(rmp, win, buf, lnum, col, tm, timed_out);
16444      rmp->regprog->re_in_use = false;
16445    }
16446
16447    xfree(pat);
16448    p_re = save_p_re;
16449  }
16450
16451  rex_in_use = rex_in_use_save;
16452  if (rex_in_use) {
16453    rex = rex_save;
16454  }
16455
16456  return result <= 0 ? 0 : result;
16457}