blob: 157d3ebad5134f2b61381cdb9ce9f6c45b3010ca [file] [log] [blame]
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * NFA regular expression implementation.
4 *
5 * This file is included in "regexp.c".
6 */
7
8#ifdef DEBUG
9/* Comment this out to disable log files. They can get pretty big */
10# define ENABLE_LOG
11# define LOG_NAME "log_nfarun.log"
Bram Moolenaar7fcff1f2013-05-20 21:49:13 +020012# define NFA_REGEXP_DEBUG_LOG
13# define NFA_REGEXP_DEBUG_LOG_NAME "nfa_regexp_debug.log"
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +020014#endif
15
16/* Upper limit allowed for {m,n} repetitions handled by NFA */
17#define NFA_BRACES_MAXLIMIT 10
18/* For allocating space for the postfix representation */
19#define NFA_POSTFIX_MULTIPLIER (NFA_BRACES_MAXLIMIT + 2)*2
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +020020
21enum
22{
23 NFA_SPLIT = -1024,
24 NFA_MATCH,
25 NFA_SKIP_CHAR, /* matches a 0-length char */
26 NFA_END_NEG_RANGE, /* Used when expanding [^ab] */
27
28 NFA_CONCAT,
29 NFA_OR,
30 NFA_STAR,
31 NFA_PLUS,
32 NFA_QUEST,
33 NFA_QUEST_NONGREEDY, /* Non-greedy version of \? */
34 NFA_NOT, /* used for [^ab] negated char ranges */
35
36 NFA_BOL, /* ^ Begin line */
37 NFA_EOL, /* $ End line */
38 NFA_BOW, /* \< Begin word */
39 NFA_EOW, /* \> End word */
40 NFA_BOF, /* \%^ Begin file */
41 NFA_EOF, /* \%$ End file */
42 NFA_NEWL,
43 NFA_ZSTART, /* Used for \zs */
44 NFA_ZEND, /* Used for \ze */
45 NFA_NOPEN, /* Start of subexpression marked with \%( */
46 NFA_NCLOSE, /* End of subexpr. marked with \%( ... \) */
47 NFA_START_INVISIBLE,
48 NFA_END_INVISIBLE,
49 NFA_MULTIBYTE, /* Next nodes in NFA are part of the same
50 multibyte char */
51 NFA_END_MULTIBYTE, /* End of multibyte char in the NFA */
52 NFA_COMPOSING, /* Next nodes in NFA are part of the
53 composing multibyte char */
54 NFA_END_COMPOSING, /* End of a composing char in the NFA */
55
56 /* The following are used only in the postfix form, not in the NFA */
57 NFA_PREV_ATOM_NO_WIDTH, /* Used for \@= */
58 NFA_PREV_ATOM_NO_WIDTH_NEG, /* Used for \@! */
59 NFA_PREV_ATOM_JUST_BEFORE, /* Used for \@<= */
60 NFA_PREV_ATOM_JUST_BEFORE_NEG, /* Used for \@<! */
61 NFA_PREV_ATOM_LIKE_PATTERN, /* Used for \@> */
62
63 NFA_MOPEN,
64 NFA_MCLOSE = NFA_MOPEN + NSUBEXP,
65
66 /* NFA_FIRST_NL */
67 NFA_ANY = NFA_MCLOSE + NSUBEXP, /* Match any one character. */
68 NFA_ANYOF, /* Match any character in this string. */
69 NFA_ANYBUT, /* Match any character not in this string. */
70 NFA_IDENT, /* Match identifier char */
71 NFA_SIDENT, /* Match identifier char but no digit */
72 NFA_KWORD, /* Match keyword char */
73 NFA_SKWORD, /* Match word char but no digit */
74 NFA_FNAME, /* Match file name char */
75 NFA_SFNAME, /* Match file name char but no digit */
76 NFA_PRINT, /* Match printable char */
77 NFA_SPRINT, /* Match printable char but no digit */
78 NFA_WHITE, /* Match whitespace char */
79 NFA_NWHITE, /* Match non-whitespace char */
80 NFA_DIGIT, /* Match digit char */
81 NFA_NDIGIT, /* Match non-digit char */
82 NFA_HEX, /* Match hex char */
83 NFA_NHEX, /* Match non-hex char */
84 NFA_OCTAL, /* Match octal char */
85 NFA_NOCTAL, /* Match non-octal char */
86 NFA_WORD, /* Match word char */
87 NFA_NWORD, /* Match non-word char */
88 NFA_HEAD, /* Match head char */
89 NFA_NHEAD, /* Match non-head char */
90 NFA_ALPHA, /* Match alpha char */
91 NFA_NALPHA, /* Match non-alpha char */
92 NFA_LOWER, /* Match lowercase char */
93 NFA_NLOWER, /* Match non-lowercase char */
94 NFA_UPPER, /* Match uppercase char */
95 NFA_NUPPER, /* Match non-uppercase char */
96 NFA_FIRST_NL = NFA_ANY + ADD_NL,
97 NFA_LAST_NL = NFA_NUPPER + ADD_NL,
98
99 /* Character classes [:alnum:] etc */
100 NFA_CLASS_ALNUM,
101 NFA_CLASS_ALPHA,
102 NFA_CLASS_BLANK,
103 NFA_CLASS_CNTRL,
104 NFA_CLASS_DIGIT,
105 NFA_CLASS_GRAPH,
106 NFA_CLASS_LOWER,
107 NFA_CLASS_PRINT,
108 NFA_CLASS_PUNCT,
109 NFA_CLASS_SPACE,
110 NFA_CLASS_UPPER,
111 NFA_CLASS_XDIGIT,
112 NFA_CLASS_TAB,
113 NFA_CLASS_RETURN,
114 NFA_CLASS_BACKSPACE,
115 NFA_CLASS_ESCAPE
116};
117
118/* Keep in sync with classchars. */
119static int nfa_classcodes[] = {
120 NFA_ANY, NFA_IDENT, NFA_SIDENT, NFA_KWORD,NFA_SKWORD,
121 NFA_FNAME, NFA_SFNAME, NFA_PRINT, NFA_SPRINT,
122 NFA_WHITE, NFA_NWHITE, NFA_DIGIT, NFA_NDIGIT,
123 NFA_HEX, NFA_NHEX, NFA_OCTAL, NFA_NOCTAL,
124 NFA_WORD, NFA_NWORD, NFA_HEAD, NFA_NHEAD,
125 NFA_ALPHA, NFA_NALPHA, NFA_LOWER, NFA_NLOWER,
126 NFA_UPPER, NFA_NUPPER
127};
128
129static char_u e_misplaced[] = N_("E866: (NFA regexp) Misplaced %c");
130
131/*
132 * NFA errors can be of 3 types:
133 * *** NFA runtime errors, when something unknown goes wrong. The NFA fails
134 * silently and revert the to backtracking engine.
135 * syntax_error = FALSE;
136 * *** Regexp syntax errors, when the input regexp is not syntactically correct.
137 * The NFA engine displays an error message, and nothing else happens.
138 * syntax_error = TRUE
139 * *** Unsupported features, when the input regexp uses an operator that is not
140 * implemented in the NFA. The NFA engine fails silently, and reverts to the
141 * old backtracking engine.
142 * syntax_error = FALSE
143 * "The NFA fails" means that "compiling the regexp with the NFA fails":
144 * nfa_regcomp() returns FAIL.
145 */
146static int syntax_error = FALSE;
147
148/* NFA regexp \ze operator encountered. */
149static int nfa_has_zend = FALSE;
150
151static int *post_start; /* holds the postfix form of r.e. */
152static int *post_end;
153static int *post_ptr;
154
155static int nstate; /* Number of states in the NFA. */
156static int istate; /* Index in the state vector, used in new_state() */
157static int nstate_max; /* Upper bound of estimated number of states. */
158
159
160static int nfa_regcomp_start __ARGS((char_u*expr, int re_flags));
161static int nfa_recognize_char_class __ARGS((char_u *start, char_u *end, int extra_newl));
162static int nfa_emit_equi_class __ARGS((int c, int neg));
163static void nfa_inc __ARGS((char_u **p));
164static void nfa_dec __ARGS((char_u **p));
165static int nfa_regatom __ARGS((void));
166static int nfa_regpiece __ARGS((void));
167static int nfa_regconcat __ARGS((void));
168static int nfa_regbranch __ARGS((void));
169static int nfa_reg __ARGS((int paren));
170#ifdef DEBUG
171static void nfa_set_code __ARGS((int c));
172static void nfa_postfix_dump __ARGS((char_u *expr, int retval));
173static void nfa_print_state __ARGS((FILE *debugf, nfa_state_T *state, int ident));
174static void nfa_dump __ARGS((nfa_regprog_T *prog));
175#endif
176static int *re2post __ARGS((void));
177static nfa_state_T *new_state __ARGS((int c, nfa_state_T *out, nfa_state_T *out1));
178static nfa_state_T *post2nfa __ARGS((int *postfix, int *end, int nfa_calc_size));
179static int check_char_class __ARGS((int class, int c));
180static void st_error __ARGS((int *postfix, int *end, int *p));
181static void nfa_save_listids __ARGS((nfa_state_T *start, int *list));
182static void nfa_restore_listids __ARGS((nfa_state_T *start, int *list));
183static void nfa_set_null_listids __ARGS((nfa_state_T *start));
184static void nfa_set_neg_listids __ARGS((nfa_state_T *start));
185static long nfa_regtry __ARGS((nfa_state_T *start, colnr_T col));
186static long nfa_regexec_both __ARGS((char_u *line, colnr_T col));
187static regprog_T *nfa_regcomp __ARGS((char_u *expr, int re_flags));
188static int nfa_regexec __ARGS((regmatch_T *rmp, char_u *line, colnr_T col));
189static long nfa_regexec_multi __ARGS((regmmatch_T *rmp, win_T *win, buf_T *buf, linenr_T lnum, colnr_T col, proftime_T *tm));
190
191/* helper functions used when doing re2post() ... regatom() parsing */
192#define EMIT(c) do { \
193 if (post_ptr >= post_end) \
194 return FAIL; \
195 *post_ptr++ = c; \
196 } while (0)
197
198#define EMIT_MBYTE(c) \
199 len = (*mb_char2bytes)(c, buf); \
200 EMIT(buf[0]); \
201 for (i = 1; i < len; i++) \
202 { \
203 EMIT(buf[i]); \
204 EMIT(NFA_CONCAT); \
205 } \
206 EMIT(NFA_MULTIBYTE);
207
208#define EMIT_COMPOSING_UTF(input) \
209 len = utfc_ptr2len(input); \
210 EMIT(input[0]); \
211 for (i = 1; i < len; i++) \
212 { \
213 EMIT(input[i]); \
214 EMIT(NFA_CONCAT); \
215 } \
216 EMIT(NFA_COMPOSING);
217
218/*
219 * Initialize internal variables before NFA compilation.
220 * Return OK on success, FAIL otherwise.
221 */
222 static int
223nfa_regcomp_start(expr, re_flags)
224 char_u *expr;
225 int re_flags; /* see vim_regcomp() */
226{
Bram Moolenaarca12d7c2013-05-20 21:26:33 +0200227 size_t postfix_size;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200228
229 nstate = 0;
230 istate = 0;
231 /* A reasonable estimation for size */
Bram Moolenaarca12d7c2013-05-20 21:26:33 +0200232 nstate_max = (int)(STRLEN(expr) + 1) * NFA_POSTFIX_MULTIPLIER;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200233
Bram Moolenaarbc0ea8f2013-05-20 13:44:29 +0200234 /* Some items blow up in size, such as [A-z]. Add more space for that.
235 * TODO: some patterns may still fail. */
Bram Moolenaarca12d7c2013-05-20 21:26:33 +0200236 nstate_max += 1000;
Bram Moolenaarbc0ea8f2013-05-20 13:44:29 +0200237
238 /* Size for postfix representation of expr. */
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200239 postfix_size = sizeof(*post_start) * nstate_max;
Bram Moolenaarbc0ea8f2013-05-20 13:44:29 +0200240
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200241 post_start = (int *)lalloc(postfix_size, TRUE);
242 if (post_start == NULL)
243 return FAIL;
244 vim_memset(post_start, 0, postfix_size);
245 post_ptr = post_start;
Bram Moolenaarbc0ea8f2013-05-20 13:44:29 +0200246 post_end = post_start + nstate_max;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200247 nfa_has_zend = FALSE;
248
249 regcomp_start(expr, re_flags);
250
251 return OK;
252}
253
254/*
255 * Search between "start" and "end" and try to recognize a
256 * character class in expanded form. For example [0-9].
257 * On success, return the id the character class to be emitted.
258 * On failure, return 0 (=FAIL)
259 * Start points to the first char of the range, while end should point
260 * to the closing brace.
261 */
262 static int
263nfa_recognize_char_class(start, end, extra_newl)
264 char_u *start;
265 char_u *end;
266 int extra_newl;
267{
268 int i;
269 /* Each of these variables takes up a char in "config[]",
270 * in the order they are here. */
271 int not = FALSE, af = FALSE, AF = FALSE, az = FALSE, AZ = FALSE,
272 o7 = FALSE, o9 = FALSE, underscore = FALSE, newl = FALSE;
273 char_u *p;
274#define NCONFIGS 16
275 int classid[NCONFIGS] = {
276 NFA_DIGIT, NFA_NDIGIT, NFA_HEX, NFA_NHEX,
277 NFA_OCTAL, NFA_NOCTAL, NFA_WORD, NFA_NWORD,
278 NFA_HEAD, NFA_NHEAD, NFA_ALPHA, NFA_NALPHA,
279 NFA_LOWER, NFA_NLOWER, NFA_UPPER, NFA_NUPPER
280 };
Bram Moolenaarba404472013-05-19 22:31:18 +0200281 char_u myconfig[10];
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200282 char_u config[NCONFIGS][9] = {
283 "000000100", /* digit */
284 "100000100", /* non digit */
285 "011000100", /* hex-digit */
286 "111000100", /* non hex-digit */
287 "000001000", /* octal-digit */
288 "100001000", /* [^0-7] */
289 "000110110", /* [0-9A-Za-z_] */
290 "100110110", /* [^0-9A-Za-z_] */
291 "000110010", /* head of word */
292 "100110010", /* not head of word */
293 "000110000", /* alphabetic char a-z */
294 "100110000", /* non alphabetic char */
295 "000100000", /* lowercase letter */
296 "100100000", /* non lowercase */
297 "000010000", /* uppercase */
298 "100010000" /* non uppercase */
299 };
300
301 if (extra_newl == TRUE)
302 newl = TRUE;
303
304 if (*end != ']')
305 return FAIL;
306 p = start;
307 if (*p == '^')
308 {
309 not = TRUE;
310 p ++;
311 }
312
313 while (p < end)
314 {
315 if (p + 2 < end && *(p + 1) == '-')
316 {
317 switch (*p)
318 {
319 case '0':
320 if (*(p + 2) == '9')
321 {
322 o9 = TRUE;
323 break;
324 }
325 else
326 if (*(p + 2) == '7')
327 {
328 o7 = TRUE;
329 break;
330 }
331 case 'a':
332 if (*(p + 2) == 'z')
333 {
334 az = TRUE;
335 break;
336 }
337 else
338 if (*(p + 2) == 'f')
339 {
340 af = TRUE;
341 break;
342 }
343 case 'A':
344 if (*(p + 2) == 'Z')
345 {
346 AZ = TRUE;
347 break;
348 }
349 else
350 if (*(p + 2) == 'F')
351 {
352 AF = TRUE;
353 break;
354 }
355 /* FALLTHROUGH */
356 default:
357 return FAIL;
358 }
359 p += 3;
360 }
361 else if (p + 1 < end && *p == '\\' && *(p + 1) == 'n')
362 {
363 newl = TRUE;
364 p += 2;
365 }
366 else if (*p == '_')
367 {
368 underscore = TRUE;
369 p ++;
370 }
371 else if (*p == '\n')
372 {
373 newl = TRUE;
374 p ++;
375 }
376 else
377 return FAIL;
378 } /* while (p < end) */
379
380 if (p != end)
381 return FAIL;
382
383 /* build the config that represents the ranges we gathered */
384 STRCPY(myconfig, "000000000");
385 if (not == TRUE)
386 myconfig[0] = '1';
387 if (af == TRUE)
388 myconfig[1] = '1';
389 if (AF == TRUE)
390 myconfig[2] = '1';
391 if (az == TRUE)
392 myconfig[3] = '1';
393 if (AZ == TRUE)
394 myconfig[4] = '1';
395 if (o7 == TRUE)
396 myconfig[5] = '1';
397 if (o9 == TRUE)
398 myconfig[6] = '1';
399 if (underscore == TRUE)
400 myconfig[7] = '1';
401 if (newl == TRUE)
402 {
403 myconfig[8] = '1';
404 extra_newl = ADD_NL;
405 }
406 /* try to recognize character classes */
407 for (i = 0; i < NCONFIGS; i++)
Bram Moolenaarba404472013-05-19 22:31:18 +0200408 if (STRNCMP(myconfig, config[i], 8) == 0)
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200409 return classid[i] + extra_newl;
410
411 /* fallthrough => no success so far */
412 return FAIL;
413
414#undef NCONFIGS
415}
416
417/*
418 * Produce the bytes for equivalence class "c".
419 * Currently only handles latin1, latin9 and utf-8.
420 * Emits bytes in postfix notation: 'a,b,NFA_OR,c,NFA_OR' is
421 * equivalent to 'a OR b OR c'
422 *
423 * NOTE! When changing this function, also update reg_equi_class()
424 */
425 static int
426nfa_emit_equi_class(c, neg)
427 int c;
428 int neg;
429{
430 int first = TRUE;
431 int glue = neg == TRUE ? NFA_CONCAT : NFA_OR;
432#define EMIT2(c) \
433 EMIT(c); \
434 if (neg == TRUE) { \
435 EMIT(NFA_NOT); \
436 } \
437 if (first == FALSE) \
438 EMIT(glue); \
439 else \
440 first = FALSE; \
441
442#ifdef FEAT_MBYTE
443 if (enc_utf8 || STRCMP(p_enc, "latin1") == 0
444 || STRCMP(p_enc, "iso-8859-15") == 0)
445#endif
446 {
447 switch (c)
448 {
449 case 'A': case '\300': case '\301': case '\302':
450 case '\303': case '\304': case '\305':
451 EMIT2('A'); EMIT2('\300'); EMIT2('\301');
452 EMIT2('\302'); EMIT2('\303'); EMIT2('\304');
453 EMIT2('\305');
454 return OK;
455
456 case 'C': case '\307':
457 EMIT2('C'); EMIT2('\307');
458 return OK;
459
460 case 'E': case '\310': case '\311': case '\312': case '\313':
461 EMIT2('E'); EMIT2('\310'); EMIT2('\311');
462 EMIT2('\312'); EMIT2('\313');
463 return OK;
464
465 case 'I': case '\314': case '\315': case '\316': case '\317':
466 EMIT2('I'); EMIT2('\314'); EMIT2('\315');
467 EMIT2('\316'); EMIT2('\317');
468 return OK;
469
470 case 'N': case '\321':
471 EMIT2('N'); EMIT2('\321');
472 return OK;
473
474 case 'O': case '\322': case '\323': case '\324': case '\325':
475 case '\326':
476 EMIT2('O'); EMIT2('\322'); EMIT2('\323');
477 EMIT2('\324'); EMIT2('\325'); EMIT2('\326');
478 return OK;
479
480 case 'U': case '\331': case '\332': case '\333': case '\334':
481 EMIT2('U'); EMIT2('\331'); EMIT2('\332');
482 EMIT2('\333'); EMIT2('\334');
483 return OK;
484
485 case 'Y': case '\335':
486 EMIT2('Y'); EMIT2('\335');
487 return OK;
488
489 case 'a': case '\340': case '\341': case '\342':
490 case '\343': case '\344': case '\345':
491 EMIT2('a'); EMIT2('\340'); EMIT2('\341');
492 EMIT2('\342'); EMIT2('\343'); EMIT2('\344');
493 EMIT2('\345');
494 return OK;
495
496 case 'c': case '\347':
497 EMIT2('c'); EMIT2('\347');
498 return OK;
499
500 case 'e': case '\350': case '\351': case '\352': case '\353':
501 EMIT2('e'); EMIT2('\350'); EMIT2('\351');
502 EMIT2('\352'); EMIT2('\353');
503 return OK;
504
505 case 'i': case '\354': case '\355': case '\356': case '\357':
506 EMIT2('i'); EMIT2('\354'); EMIT2('\355');
507 EMIT2('\356'); EMIT2('\357');
508 return OK;
509
510 case 'n': case '\361':
511 EMIT2('n'); EMIT2('\361');
512 return OK;
513
514 case 'o': case '\362': case '\363': case '\364': case '\365':
515 case '\366':
516 EMIT2('o'); EMIT2('\362'); EMIT2('\363');
517 EMIT2('\364'); EMIT2('\365'); EMIT2('\366');
518 return OK;
519
520 case 'u': case '\371': case '\372': case '\373': case '\374':
521 EMIT2('u'); EMIT2('\371'); EMIT2('\372');
522 EMIT2('\373'); EMIT2('\374');
523 return OK;
524
525 case 'y': case '\375': case '\377':
526 EMIT2('y'); EMIT2('\375'); EMIT2('\377');
527 return OK;
528
529 default:
530 return FAIL;
531 }
532 }
533
534 EMIT(c);
535 return OK;
536#undef EMIT2
537}
538
539/*
540 * Code to parse regular expression.
541 *
542 * We try to reuse parsing functions in regexp.c to
543 * minimize surprise and keep the syntax consistent.
544 */
545
546/*
547 * Increments the pointer "p" by one (multi-byte) character.
548 */
549 static void
550nfa_inc(p)
551 char_u **p;
552{
553#ifdef FEAT_MBYTE
554 if (has_mbyte)
555 mb_ptr2char_adv(p);
556 else
557#endif
558 *p = *p + 1;
559}
560
561/*
562 * Decrements the pointer "p" by one (multi-byte) character.
563 */
564 static void
565nfa_dec(p)
566 char_u **p;
567{
568#ifdef FEAT_MBYTE
569 char_u *p2, *oldp;
570
571 if (has_mbyte)
572 {
573 oldp = *p;
574 /* Try to find the multibyte char that advances to the current
575 * position. */
576 do
577 {
578 *p = *p - 1;
579 p2 = *p;
580 mb_ptr2char_adv(&p2);
581 } while (p2 != oldp);
582 }
583#else
584 *p = *p - 1;
585#endif
586}
587
588/*
589 * Parse the lowest level.
590 *
591 * An atom can be one of a long list of items. Many atoms match one character
592 * in the text. It is often an ordinary character or a character class.
593 * Braces can be used to make a pattern into an atom. The "\z(\)" construct
594 * is only for syntax highlighting.
595 *
596 * atom ::= ordinary-atom
597 * or \( pattern \)
598 * or \%( pattern \)
599 * or \z( pattern \)
600 */
601 static int
602nfa_regatom()
603{
604 int c;
605 int charclass;
606 int equiclass;
607 int collclass;
608 int got_coll_char;
609 char_u *p;
610 char_u *endp;
611#ifdef FEAT_MBYTE
612 char_u *old_regparse = regparse;
613 int clen;
614 int len;
615 static char_u buf[30];
616 int i;
617#endif
618 int extra = 0;
619 int first;
620 int emit_range;
621 int negated;
622 int result;
623 int startc = -1;
624 int endc = -1;
625 int oldstartc = -1;
626 int cpo_lit; /* 'cpoptions' contains 'l' flag */
627 int cpo_bsl; /* 'cpoptions' contains '\' flag */
628 int glue; /* ID that will "glue" nodes together */
629
630 cpo_lit = vim_strchr(p_cpo, CPO_LITERAL) != NULL;
631 cpo_bsl = vim_strchr(p_cpo, CPO_BACKSL) != NULL;
632
633 c = getchr();
634
635#ifdef FEAT_MBYTE
636 /* clen has the length of the current char, without composing chars */
637 clen = (*mb_char2len)(c);
638 if (has_mbyte && clen > 1)
639 goto nfa_do_multibyte;
640#endif
641 switch (c)
642 {
643 case Magic('^'):
644 EMIT(NFA_BOL);
645 break;
646
647 case Magic('$'):
648 EMIT(NFA_EOL);
649#if defined(FEAT_SYN_HL) || defined(PROTO)
650 had_eol = TRUE;
651#endif
652 break;
653
654 case Magic('<'):
655 EMIT(NFA_BOW);
656 break;
657
658 case Magic('>'):
659 EMIT(NFA_EOW);
660 break;
661
662 case Magic('_'):
663 c = no_Magic(getchr());
664 if (c == '^') /* "\_^" is start-of-line */
665 {
666 EMIT(NFA_BOL);
667 break;
668 }
669 if (c == '$') /* "\_$" is end-of-line */
670 {
671 EMIT(NFA_EOL);
672#if defined(FEAT_SYN_HL) || defined(PROTO)
673 had_eol = TRUE;
674#endif
675 break;
676 }
677
678 extra = ADD_NL;
679
680 /* "\_[" is collection plus newline */
681 if (c == '[')
Bram Moolenaar307d10a2013-05-23 22:25:15 +0200682 goto collection;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200683
684 /* "\_x" is character class plus newline */
685 /*FALLTHROUGH*/
686
687 /*
688 * Character classes.
689 */
690 case Magic('.'):
691 case Magic('i'):
692 case Magic('I'):
693 case Magic('k'):
694 case Magic('K'):
695 case Magic('f'):
696 case Magic('F'):
697 case Magic('p'):
698 case Magic('P'):
699 case Magic('s'):
700 case Magic('S'):
701 case Magic('d'):
702 case Magic('D'):
703 case Magic('x'):
704 case Magic('X'):
705 case Magic('o'):
706 case Magic('O'):
707 case Magic('w'):
708 case Magic('W'):
709 case Magic('h'):
710 case Magic('H'):
711 case Magic('a'):
712 case Magic('A'):
713 case Magic('l'):
714 case Magic('L'):
715 case Magic('u'):
716 case Magic('U'):
717 p = vim_strchr(classchars, no_Magic(c));
718 if (p == NULL)
719 {
720 return FAIL; /* runtime error */
721 }
722#ifdef FEAT_MBYTE
723 /* When '.' is followed by a composing char ignore the dot, so that
724 * the composing char is matched here. */
725 if (enc_utf8 && c == Magic('.') && utf_iscomposing(peekchr()))
726 {
727 c = getchr();
728 goto nfa_do_multibyte;
729 }
730#endif
731 EMIT(nfa_classcodes[p - classchars]);
732 if (extra == ADD_NL)
733 {
734 EMIT(NFA_NEWL);
735 EMIT(NFA_OR);
736 regflags |= RF_HASNL;
737 }
738 break;
739
740 case Magic('n'):
741 if (reg_string)
742 /* In a string "\n" matches a newline character. */
743 EMIT(NL);
744 else
745 {
746 /* In buffer text "\n" matches the end of a line. */
747 EMIT(NFA_NEWL);
748 regflags |= RF_HASNL;
749 }
750 break;
751
752 case Magic('('):
753 if (nfa_reg(REG_PAREN) == FAIL)
754 return FAIL; /* cascaded error */
755 break;
756
757 case NUL:
758 syntax_error = TRUE;
759 EMSG_RET_FAIL(_("E865: (NFA) Regexp end encountered prematurely"));
760
761 case Magic('|'):
762 case Magic('&'):
763 case Magic(')'):
764 syntax_error = TRUE;
Bram Moolenaarba404472013-05-19 22:31:18 +0200765 EMSGN(_(e_misplaced), no_Magic(c));
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200766 return FAIL;
767
768 case Magic('='):
769 case Magic('?'):
770 case Magic('+'):
771 case Magic('@'):
772 case Magic('*'):
773 case Magic('{'):
774 /* these should follow an atom, not form an atom */
775 syntax_error = TRUE;
Bram Moolenaarba404472013-05-19 22:31:18 +0200776 EMSGN(_(e_misplaced), no_Magic(c));
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200777 return FAIL;
778
779 case Magic('~'): /* previous substitute pattern */
780 /* Not supported yet */
781 return FAIL;
782
783 case Magic('1'):
784 case Magic('2'):
785 case Magic('3'):
786 case Magic('4'):
787 case Magic('5'):
788 case Magic('6'):
789 case Magic('7'):
790 case Magic('8'):
791 case Magic('9'):
792 /* not supported yet */
793 return FAIL;
794
795 case Magic('z'):
796 c = no_Magic(getchr());
797 switch (c)
798 {
799 case 's':
800 EMIT(NFA_ZSTART);
801 break;
802 case 'e':
803 EMIT(NFA_ZEND);
804 nfa_has_zend = TRUE;
805 /* TODO: Currently \ze does not work properly. */
806 return FAIL;
807 /* break; */
808 case '1':
809 case '2':
810 case '3':
811 case '4':
812 case '5':
813 case '6':
814 case '7':
815 case '8':
816 case '9':
817 case '(':
818 /* \z1...\z9 and \z( not yet supported */
819 return FAIL;
820 default:
821 syntax_error = TRUE;
Bram Moolenaarba404472013-05-19 22:31:18 +0200822 EMSGN(_("E867: (NFA) Unknown operator '\\z%c'"),
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200823 no_Magic(c));
824 return FAIL;
825 }
826 break;
827
828 case Magic('%'):
829 c = no_Magic(getchr());
830 switch (c)
831 {
832 /* () without a back reference */
833 case '(':
834 if (nfa_reg(REG_NPAREN) == FAIL)
835 return FAIL;
836 EMIT(NFA_NOPEN);
837 break;
838
839 case 'd': /* %d123 decimal */
840 case 'o': /* %o123 octal */
841 case 'x': /* %xab hex 2 */
842 case 'u': /* %uabcd hex 4 */
843 case 'U': /* %U1234abcd hex 8 */
844 /* Not yet supported */
845 return FAIL;
846
847 c = coll_get_char();
848#ifdef FEAT_MBYTE
849 if ((*mb_char2len)(c) > 1)
850 {
851 EMIT_MBYTE(c);
852 }
853 else
854#endif
855 EMIT(c);
856 break;
857
858 /* Catch \%^ and \%$ regardless of where they appear in the
859 * pattern -- regardless of whether or not it makes sense. */
860 case '^':
861 EMIT(NFA_BOF);
862 /* Not yet supported */
863 return FAIL;
864 break;
865
866 case '$':
867 EMIT(NFA_EOF);
868 /* Not yet supported */
869 return FAIL;
870 break;
871
872 case '#':
873 /* not supported yet */
874 return FAIL;
875 break;
876
877 case 'V':
878 /* not supported yet */
879 return FAIL;
880 break;
881
882 case '[':
883 /* \%[abc] not supported yet */
884 return FAIL;
885
886 default:
887 /* not supported yet */
888 return FAIL;
889 }
890 break;
891
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200892 case Magic('['):
Bram Moolenaar307d10a2013-05-23 22:25:15 +0200893collection:
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +0200894 /*
895 * Glue is emitted between several atoms from the [].
896 * It is either NFA_OR, or NFA_CONCAT.
897 *
898 * [abc] expands to 'a b NFA_OR c NFA_OR' (in postfix notation)
899 * [^abc] expands to 'a NFA_NOT b NFA_NOT NFA_CONCAT c NFA_NOT
900 * NFA_CONCAT NFA_END_NEG_RANGE NFA_CONCAT' (in postfix
901 * notation)
902 *
903 */
904
905
906/* Emit negation atoms, if needed.
907 * The CONCAT below merges the NOT with the previous node. */
908#define TRY_NEG() \
909 if (negated == TRUE) \
910 { \
911 EMIT(NFA_NOT); \
912 }
913
914/* Emit glue between important nodes : CONCAT or OR. */
915#define EMIT_GLUE() \
916 if (first == FALSE) \
917 EMIT(glue); \
918 else \
919 first = FALSE;
920
921 p = regparse;
922 endp = skip_anyof(p);
923 if (*endp == ']')
924 {
925 /*
926 * Try to reverse engineer character classes. For example,
927 * recognize that [0-9] stands for \d and [A-Za-z_] with \h,
928 * and perform the necessary substitutions in the NFA.
929 */
930 result = nfa_recognize_char_class(regparse, endp,
931 extra == ADD_NL);
932 if (result != FAIL)
933 {
934 if (result >= NFA_DIGIT && result <= NFA_NUPPER)
935 EMIT(result);
936 else /* must be char class + newline */
937 {
938 EMIT(result - ADD_NL);
939 EMIT(NFA_NEWL);
940 EMIT(NFA_OR);
941 }
942 regparse = endp;
943 nfa_inc(&regparse);
944 return OK;
945 }
946 /*
947 * Failed to recognize a character class. Use the simple
948 * version that turns [abc] into 'a' OR 'b' OR 'c'
949 */
950 startc = endc = oldstartc = -1;
951 first = TRUE; /* Emitting first atom in this sequence? */
952 negated = FALSE;
953 glue = NFA_OR;
954 if (*regparse == '^') /* negated range */
955 {
956 negated = TRUE;
957 glue = NFA_CONCAT;
958 nfa_inc(&regparse);
959 }
960 if (*regparse == '-')
961 {
962 startc = '-';
963 EMIT(startc);
964 TRY_NEG();
965 EMIT_GLUE();
966 nfa_inc(&regparse);
967 }
968 /* Emit the OR branches for each character in the [] */
969 emit_range = FALSE;
970 while (regparse < endp)
971 {
972 oldstartc = startc;
973 startc = -1;
974 got_coll_char = FALSE;
975 if (*regparse == '[')
976 {
977 /* Check for [: :], [= =], [. .] */
978 equiclass = collclass = 0;
979 charclass = get_char_class(&regparse);
980 if (charclass == CLASS_NONE)
981 {
982 equiclass = get_equi_class(&regparse);
983 if (equiclass == 0)
984 collclass = get_coll_element(&regparse);
985 }
986
987 /* Character class like [:alpha:] */
988 if (charclass != CLASS_NONE)
989 {
990 switch (charclass)
991 {
992 case CLASS_ALNUM:
993 EMIT(NFA_CLASS_ALNUM);
994 break;
995 case CLASS_ALPHA:
996 EMIT(NFA_CLASS_ALPHA);
997 break;
998 case CLASS_BLANK:
999 EMIT(NFA_CLASS_BLANK);
1000 break;
1001 case CLASS_CNTRL:
1002 EMIT(NFA_CLASS_CNTRL);
1003 break;
1004 case CLASS_DIGIT:
1005 EMIT(NFA_CLASS_DIGIT);
1006 break;
1007 case CLASS_GRAPH:
1008 EMIT(NFA_CLASS_GRAPH);
1009 break;
1010 case CLASS_LOWER:
1011 EMIT(NFA_CLASS_LOWER);
1012 break;
1013 case CLASS_PRINT:
1014 EMIT(NFA_CLASS_PRINT);
1015 break;
1016 case CLASS_PUNCT:
1017 EMIT(NFA_CLASS_PUNCT);
1018 break;
1019 case CLASS_SPACE:
1020 EMIT(NFA_CLASS_SPACE);
1021 break;
1022 case CLASS_UPPER:
1023 EMIT(NFA_CLASS_UPPER);
1024 break;
1025 case CLASS_XDIGIT:
1026 EMIT(NFA_CLASS_XDIGIT);
1027 break;
1028 case CLASS_TAB:
1029 EMIT(NFA_CLASS_TAB);
1030 break;
1031 case CLASS_RETURN:
1032 EMIT(NFA_CLASS_RETURN);
1033 break;
1034 case CLASS_BACKSPACE:
1035 EMIT(NFA_CLASS_BACKSPACE);
1036 break;
1037 case CLASS_ESCAPE:
1038 EMIT(NFA_CLASS_ESCAPE);
1039 break;
1040 }
1041 TRY_NEG();
1042 EMIT_GLUE();
1043 continue;
1044 }
1045 /* Try equivalence class [=a=] and the like */
1046 if (equiclass != 0)
1047 {
1048 result = nfa_emit_equi_class(equiclass, negated);
1049 if (result == FAIL)
1050 {
1051 /* should never happen */
1052 EMSG_RET_FAIL(_("E868: Error building NFA with equivalence class!"));
1053 }
1054 EMIT_GLUE();
1055 continue;
1056 }
1057 /* Try collating class like [. .] */
1058 if (collclass != 0)
1059 {
1060 startc = collclass; /* allow [.a.]-x as a range */
1061 /* Will emit the proper atom at the end of the
1062 * while loop. */
1063 }
1064 }
1065 /* Try a range like 'a-x' or '\t-z' */
1066 if (*regparse == '-')
1067 {
1068 emit_range = TRUE;
1069 startc = oldstartc;
1070 nfa_inc(&regparse);
1071 continue; /* reading the end of the range */
1072 }
1073
1074 /* Now handle simple and escaped characters.
1075 * Only "\]", "\^", "\]" and "\\" are special in Vi. Vim
1076 * accepts "\t", "\e", etc., but only when the 'l' flag in
1077 * 'cpoptions' is not included.
1078 * Posix doesn't recognize backslash at all.
1079 */
1080 if (*regparse == '\\'
1081 && !cpo_bsl
1082 && regparse + 1 <= endp
1083 && (vim_strchr(REGEXP_INRANGE, regparse[1]) != NULL
1084 || (!cpo_lit
1085 && vim_strchr(REGEXP_ABBR, regparse[1])
1086 != NULL)
1087 )
1088 )
1089 {
1090 nfa_inc(&regparse);
1091
Bram Moolenaar673af4d2013-05-21 22:00:51 +02001092 if (*regparse == 'n')
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02001093 startc = reg_string ? NL : NFA_NEWL;
1094 else
1095 if (*regparse == 'd'
1096 || *regparse == 'o'
1097 || *regparse == 'x'
1098 || *regparse == 'u'
1099 || *regparse == 'U'
1100 )
1101 {
1102 /* TODO(RE) This needs more testing */
1103 startc = coll_get_char();
1104 got_coll_char = TRUE;
1105 nfa_dec(&regparse);
1106 }
1107 else
1108 {
1109 /* \r,\t,\e,\b */
1110 startc = backslash_trans(*regparse);
1111 }
1112 }
1113
1114 /* Normal printable char */
1115 if (startc == -1)
1116#ifdef FEAT_MBYTE
1117 startc = (*mb_ptr2char)(regparse);
1118#else
1119 startc = *regparse;
1120#endif
1121
1122 /* Previous char was '-', so this char is end of range. */
1123 if (emit_range)
1124 {
1125 endc = startc; startc = oldstartc;
1126 if (startc > endc)
1127 EMSG_RET_FAIL(_(e_invrange));
1128#ifdef FEAT_MBYTE
1129 if (has_mbyte && ((*mb_char2len)(startc) > 1
1130 || (*mb_char2len)(endc) > 1))
1131 {
1132 if (endc > startc + 256)
1133 EMSG_RET_FAIL(_(e_invrange));
1134 /* Emit the range. "startc" was already emitted, so
1135 * skip it. */
1136 for (c = startc + 1; c <= endc; c++)
1137 {
1138 if ((*mb_char2len)(c) > 1)
1139 {
1140 EMIT_MBYTE(c);
1141 }
1142 else
1143 EMIT(c);
1144 TRY_NEG();
1145 EMIT_GLUE();
1146 }
1147 emit_range = FALSE;
1148 }
1149 else
1150#endif
1151 {
1152#ifdef EBCDIC
1153 int alpha_only = FALSE;
1154
1155 /* for alphabetical range skip the gaps
1156 * 'i'-'j', 'r'-'s', 'I'-'J' and 'R'-'S'. */
1157 if (isalpha(startc) && isalpha(endc))
1158 alpha_only = TRUE;
1159#endif
1160 /* Emit the range. "startc" was already emitted, so
1161 * skip it. */
1162 for (c = startc + 1; c <= endc; c++)
1163#ifdef EBCDIC
1164 if (!alpha_only || isalpha(startc))
1165#endif
1166 {
1167 EMIT(c);
1168 TRY_NEG();
1169 EMIT_GLUE();
1170 }
1171 emit_range = FALSE;
1172 }
1173 }
1174 else
1175 {
1176 /*
1177 * This char (startc) is not part of a range. Just
1178 * emit it.
1179 *
1180 * Normally, simply emit startc. But if we get char
1181 * code=0 from a collating char, then replace it with
1182 * 0x0a.
1183 *
1184 * This is needed to completely mimic the behaviour of
1185 * the backtracking engine.
1186 */
1187 if (got_coll_char == TRUE && startc == 0)
1188 EMIT(0x0a);
1189 else
1190#ifdef FEAT_MBYTE
1191 if ((*mb_char2len)(startc) > 1)
1192 {
1193 EMIT_MBYTE(startc);
1194 }
1195 else
1196#endif
1197 EMIT(startc);
1198 TRY_NEG();
1199 EMIT_GLUE();
1200 }
1201
1202 nfa_inc(&regparse);
1203 } /* while (p < endp) */
1204
1205 nfa_dec(&regparse);
1206 if (*regparse == '-') /* if last, '-' is just a char */
1207 {
1208 EMIT('-');
1209 TRY_NEG();
1210 EMIT_GLUE();
1211 }
1212 nfa_inc(&regparse);
1213
1214 if (extra == ADD_NL) /* \_[] also matches \n */
1215 {
1216 EMIT(reg_string ? NL : NFA_NEWL);
1217 TRY_NEG();
1218 EMIT_GLUE();
1219 }
1220
1221 /* skip the trailing ] */
1222 regparse = endp;
1223 nfa_inc(&regparse);
1224 if (negated == TRUE)
1225 {
1226 /* Mark end of negated char range */
1227 EMIT(NFA_END_NEG_RANGE);
1228 EMIT(NFA_CONCAT);
1229 }
1230 return OK;
1231 } /* if exists closing ] */
1232 else if (reg_strict)
1233 {
1234 syntax_error = TRUE;
1235 EMSG_RET_FAIL(_(e_missingbracket));
1236 }
1237
1238 /* FALLTHROUGH */
1239 default:
1240 {
1241#ifdef FEAT_MBYTE
1242 int plen;
1243
1244nfa_do_multibyte:
1245 /* length of current char, with composing chars,
1246 * from pointer */
1247 plen = (*mb_ptr2len)(old_regparse);
1248 if (enc_utf8 && clen != plen)
1249 {
1250 /* A composing character is always handled as a
1251 * separate atom, surrounded by NFA_COMPOSING and
1252 * NFA_END_COMPOSING. Note that right now we are
1253 * building the postfix form, not the NFA itself;
1254 * a composing char could be: a, b, c, NFA_COMPOSING
1255 * where 'a', 'b', 'c' are chars with codes > 256.
1256 */
1257 EMIT_COMPOSING_UTF(old_regparse);
1258 regparse = old_regparse + plen;
1259 }
1260 else
1261 /* A multi-byte character is always handled as a
1262 * separate atom, surrounded by NFA_MULTIBYTE and
1263 * NFA_END_MULTIBYTE */
1264 if (plen > 1)
1265 {
1266 EMIT_MBYTE(c);
1267 }
1268 else
1269#endif
1270 {
1271 c = no_Magic(c);
1272 EMIT(c);
1273 }
1274 return OK;
1275 }
1276 }
1277
1278#undef TRY_NEG
1279#undef EMIT_GLUE
1280
1281 return OK;
1282}
1283
1284/*
1285 * Parse something followed by possible [*+=].
1286 *
1287 * A piece is an atom, possibly followed by a multi, an indication of how many
1288 * times the atom can be matched. Example: "a*" matches any sequence of "a"
1289 * characters: "", "a", "aa", etc.
1290 *
1291 * piece ::= atom
1292 * or atom multi
1293 */
1294 static int
1295nfa_regpiece()
1296{
1297 int i;
1298 int op;
1299 int ret;
1300 long minval, maxval;
1301 int greedy = TRUE; /* Braces are prefixed with '-' ? */
1302 char_u *old_regparse, *new_regparse;
1303 int c2;
1304 int *old_post_ptr, *my_post_start;
1305 int old_regnpar;
1306 int quest;
1307
1308 /* Save the current position in the regexp, so that we can use it if
1309 * <atom>{m,n} is next. */
1310 old_regparse = regparse;
1311 /* Save current number of open parenthesis, so we can use it if
1312 * <atom>{m,n} is next */
1313 old_regnpar = regnpar;
1314 /* store current pos in the postfix form, for \{m,n} involving 0s */
1315 my_post_start = post_ptr;
1316
1317 ret = nfa_regatom();
1318 if (ret == FAIL)
1319 return FAIL; /* cascaded error */
1320
1321 op = peekchr();
1322 if (re_multi_type(op) == NOT_MULTI)
1323 return OK;
1324
1325 skipchr();
1326 switch (op)
1327 {
1328 case Magic('*'):
1329 EMIT(NFA_STAR);
1330 break;
1331
1332 case Magic('+'):
1333 /*
1334 * Trick: Normally, (a*)\+ would match the whole input "aaa". The
1335 * first and only submatch would be "aaa". But the backtracking
1336 * engine interprets the plus as "try matching one more time", and
1337 * a* matches a second time at the end of the input, the empty
1338 * string.
1339 * The submatch will the empty string.
1340 *
1341 * In order to be consistent with the old engine, we disable
1342 * NFA_PLUS, and replace <atom>+ with <atom><atom>*
1343 */
1344 /* EMIT(NFA_PLUS); */
1345 regnpar = old_regnpar;
1346 regparse = old_regparse;
1347 curchr = -1;
1348 if (nfa_regatom() == FAIL)
1349 return FAIL;
1350 EMIT(NFA_STAR);
1351 EMIT(NFA_CONCAT);
1352 skipchr(); /* skip the \+ */
1353 break;
1354
1355 case Magic('@'):
1356 op = no_Magic(getchr());
1357 switch(op)
1358 {
1359 case '=':
1360 EMIT(NFA_PREV_ATOM_NO_WIDTH);
1361 break;
1362 case '!':
1363 case '<':
1364 case '>':
1365 /* Not supported yet */
1366 return FAIL;
1367 default:
1368 syntax_error = TRUE;
Bram Moolenaarba404472013-05-19 22:31:18 +02001369 EMSGN(_("E869: (NFA) Unknown operator '\\@%c'"), op);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02001370 return FAIL;
1371 }
1372 break;
1373
1374 case Magic('?'):
1375 case Magic('='):
1376 EMIT(NFA_QUEST);
1377 break;
1378
1379 case Magic('{'):
1380 /* a{2,5} will expand to 'aaa?a?a?'
1381 * a{-1,3} will expand to 'aa??a??', where ?? is the nongreedy
1382 * version of '?'
1383 * \v(ab){2,3} will expand to '(ab)(ab)(ab)?', where all the
1384 * parenthesis have the same id
1385 */
1386
1387 greedy = TRUE;
1388 c2 = peekchr();
1389 if (c2 == '-' || c2 == Magic('-'))
1390 {
1391 skipchr();
1392 greedy = FALSE;
1393 }
1394 if (!read_limits(&minval, &maxval))
1395 {
1396 syntax_error = TRUE;
1397 EMSG_RET_FAIL(_("E870: (NFA regexp) Error reading repetition limits"));
1398 }
1399 /* <atom>{0,inf}, <atom>{0,} and <atom>{} are equivalent to
1400 * <atom>* */
1401 if (minval == 0 && maxval == MAX_LIMIT && greedy)
1402 {
1403 EMIT(NFA_STAR);
1404 break;
1405 }
1406
1407 if (maxval > NFA_BRACES_MAXLIMIT)
1408 {
1409 /* This would yield a huge automaton and use too much memory.
1410 * Revert to old engine */
1411 return FAIL;
1412 }
1413
1414 /* Special case: x{0} or x{-0} */
1415 if (maxval == 0)
1416 {
1417 /* Ignore result of previous call to nfa_regatom() */
1418 post_ptr = my_post_start;
1419 /* NFA_SKIP_CHAR has 0-length and works everywhere */
1420 EMIT(NFA_SKIP_CHAR);
1421 return OK;
1422 }
1423
1424 /* Ignore previous call to nfa_regatom() */
1425 post_ptr = my_post_start;
1426 /* Save pos after the repeated atom and the \{} */
1427 new_regparse = regparse;
1428
1429 new_regparse = regparse;
1430 quest = (greedy == TRUE? NFA_QUEST : NFA_QUEST_NONGREEDY);
1431 for (i = 0; i < maxval; i++)
1432 {
1433 /* Goto beginning of the repeated atom */
1434 regparse = old_regparse;
1435 curchr = -1;
1436 /* Restore count of parenthesis */
1437 regnpar = old_regnpar;
1438 old_post_ptr = post_ptr;
1439 if (nfa_regatom() == FAIL)
1440 return FAIL;
1441 /* after "minval" times, atoms are optional */
1442 if (i + 1 > minval)
1443 EMIT(quest);
1444 if (old_post_ptr != my_post_start)
1445 EMIT(NFA_CONCAT);
1446 }
1447
1448 /* Go to just after the repeated atom and the \{} */
1449 regparse = new_regparse;
1450 curchr = -1;
1451
1452 break;
1453
1454
1455 default:
1456 break;
1457 } /* end switch */
1458
1459 if (re_multi_type(peekchr()) != NOT_MULTI)
1460 {
1461 /* Can't have a multi follow a multi. */
1462 syntax_error = TRUE;
1463 EMSG_RET_FAIL(_("E871: (NFA regexp) Can't have a multi follow a multi !"));
1464 }
1465
1466 return OK;
1467}
1468
1469/*
1470 * Parse one or more pieces, concatenated. It matches a match for the
1471 * first piece, followed by a match for the second piece, etc. Example:
1472 * "f[0-9]b", first matches "f", then a digit and then "b".
1473 *
1474 * concat ::= piece
1475 * or piece piece
1476 * or piece piece piece
1477 * etc.
1478 */
1479 static int
1480nfa_regconcat()
1481{
1482 int cont = TRUE;
1483 int first = TRUE;
1484
1485 while (cont)
1486 {
1487 switch (peekchr())
1488 {
1489 case NUL:
1490 case Magic('|'):
1491 case Magic('&'):
1492 case Magic(')'):
1493 cont = FALSE;
1494 break;
1495
1496 case Magic('Z'):
1497#ifdef FEAT_MBYTE
1498 regflags |= RF_ICOMBINE;
1499#endif
1500 skipchr_keepstart();
1501 break;
1502 case Magic('c'):
1503 regflags |= RF_ICASE;
1504 skipchr_keepstart();
1505 break;
1506 case Magic('C'):
1507 regflags |= RF_NOICASE;
1508 skipchr_keepstart();
1509 break;
1510 case Magic('v'):
1511 reg_magic = MAGIC_ALL;
1512 skipchr_keepstart();
1513 curchr = -1;
1514 break;
1515 case Magic('m'):
1516 reg_magic = MAGIC_ON;
1517 skipchr_keepstart();
1518 curchr = -1;
1519 break;
1520 case Magic('M'):
1521 reg_magic = MAGIC_OFF;
1522 skipchr_keepstart();
1523 curchr = -1;
1524 break;
1525 case Magic('V'):
1526 reg_magic = MAGIC_NONE;
1527 skipchr_keepstart();
1528 curchr = -1;
1529 break;
1530
1531 default:
1532 if (nfa_regpiece() == FAIL)
1533 return FAIL;
1534 if (first == FALSE)
1535 EMIT(NFA_CONCAT);
1536 else
1537 first = FALSE;
1538 break;
1539 }
1540 }
1541
1542 return OK;
1543}
1544
1545/*
1546 * Parse a branch, one or more concats, separated by "\&". It matches the
1547 * last concat, but only if all the preceding concats also match at the same
1548 * position. Examples:
1549 * "foobeep\&..." matches "foo" in "foobeep".
1550 * ".*Peter\&.*Bob" matches in a line containing both "Peter" and "Bob"
1551 *
1552 * branch ::= concat
1553 * or concat \& concat
1554 * or concat \& concat \& concat
1555 * etc.
1556 */
1557 static int
1558nfa_regbranch()
1559{
1560 int ch;
1561 int *old_post_ptr;
1562
1563 old_post_ptr = post_ptr;
1564
1565 /* First branch, possibly the only one */
1566 if (nfa_regconcat() == FAIL)
1567 return FAIL;
1568
1569 ch = peekchr();
1570 /* Try next concats */
1571 while (ch == Magic('&'))
1572 {
1573 skipchr();
1574 EMIT(NFA_NOPEN);
1575 EMIT(NFA_PREV_ATOM_NO_WIDTH);
1576 old_post_ptr = post_ptr;
1577 if (nfa_regconcat() == FAIL)
1578 return FAIL;
1579 /* if concat is empty, skip a input char. But do emit a node */
1580 if (old_post_ptr == post_ptr)
1581 EMIT(NFA_SKIP_CHAR);
1582 EMIT(NFA_CONCAT);
1583 ch = peekchr();
1584 }
1585
1586 /* Even if a branch is empty, emit one node for it */
1587 if (old_post_ptr == post_ptr)
1588 EMIT(NFA_SKIP_CHAR);
1589
1590 return OK;
1591}
1592
1593/*
1594 * Parse a pattern, one or more branches, separated by "\|". It matches
1595 * anything that matches one of the branches. Example: "foo\|beep" matches
1596 * "foo" and matches "beep". If more than one branch matches, the first one
1597 * is used.
1598 *
1599 * pattern ::= branch
1600 * or branch \| branch
1601 * or branch \| branch \| branch
1602 * etc.
1603 */
1604 static int
1605nfa_reg(paren)
1606 int paren; /* REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN */
1607{
1608 int parno = 0;
1609
1610#ifdef FEAT_SYN_HL
1611#endif
1612 if (paren == REG_PAREN)
1613 {
1614 if (regnpar >= NSUBEXP) /* Too many `(' */
1615 {
1616 syntax_error = TRUE;
1617 EMSG_RET_FAIL(_("E872: (NFA regexp) Too many '('"));
1618 }
1619 parno = regnpar++;
1620 }
1621
1622 if (nfa_regbranch() == FAIL)
1623 return FAIL; /* cascaded error */
1624
1625 while (peekchr() == Magic('|'))
1626 {
1627 skipchr();
1628 if (nfa_regbranch() == FAIL)
1629 return FAIL; /* cascaded error */
1630 EMIT(NFA_OR);
1631 }
1632
1633 /* Check for proper termination. */
1634 if (paren != REG_NOPAREN && getchr() != Magic(')'))
1635 {
1636 syntax_error = TRUE;
1637 if (paren == REG_NPAREN)
1638 EMSG2_RET_FAIL(_(e_unmatchedpp), reg_magic == MAGIC_ALL);
1639 else
1640 EMSG2_RET_FAIL(_(e_unmatchedp), reg_magic == MAGIC_ALL);
1641 }
1642 else if (paren == REG_NOPAREN && peekchr() != NUL)
1643 {
1644 syntax_error = TRUE;
1645 if (peekchr() == Magic(')'))
1646 EMSG2_RET_FAIL(_(e_unmatchedpar), reg_magic == MAGIC_ALL);
1647 else
1648 EMSG_RET_FAIL(_("E873: (NFA regexp) proper termination error"));
1649 }
1650 /*
1651 * Here we set the flag allowing back references to this set of
1652 * parentheses.
1653 */
1654 if (paren == REG_PAREN)
1655 {
1656 had_endbrace[parno] = TRUE; /* have seen the close paren */
1657 EMIT(NFA_MOPEN + parno);
1658 }
1659
1660 return OK;
1661}
1662
1663typedef struct
1664{
1665 char_u *start[NSUBEXP];
1666 char_u *end[NSUBEXP];
1667 lpos_T startpos[NSUBEXP];
1668 lpos_T endpos[NSUBEXP];
1669} regsub_T;
1670
1671static int nfa_regmatch __ARGS((nfa_state_T *start, regsub_T *submatch, regsub_T *m));
1672
1673#ifdef DEBUG
1674static char_u code[50];
1675
1676 static void
1677nfa_set_code(c)
1678 int c;
1679{
1680 int addnl = FALSE;
1681
1682 if (c >= NFA_FIRST_NL && c <= NFA_LAST_NL)
1683 {
1684 addnl = TRUE;
1685 c -= ADD_NL;
1686 }
1687
1688 STRCPY(code, "");
1689 switch (c)
1690 {
1691 case NFA_MATCH: STRCPY(code, "NFA_MATCH "); break;
1692 case NFA_SPLIT: STRCPY(code, "NFA_SPLIT "); break;
1693 case NFA_CONCAT: STRCPY(code, "NFA_CONCAT "); break;
1694 case NFA_NEWL: STRCPY(code, "NFA_NEWL "); break;
1695 case NFA_ZSTART: STRCPY(code, "NFA_ZSTART"); break;
1696 case NFA_ZEND: STRCPY(code, "NFA_ZEND"); break;
1697
1698 case NFA_PREV_ATOM_NO_WIDTH:
1699 STRCPY(code, "NFA_PREV_ATOM_NO_WIDTH"); break;
1700 case NFA_NOPEN: STRCPY(code, "NFA_MOPEN_INVISIBLE"); break;
1701 case NFA_NCLOSE: STRCPY(code, "NFA_MCLOSE_INVISIBLE"); break;
1702 case NFA_START_INVISIBLE: STRCPY(code, "NFA_START_INVISIBLE"); break;
1703 case NFA_END_INVISIBLE: STRCPY(code, "NFA_END_INVISIBLE"); break;
1704
1705 case NFA_MULTIBYTE: STRCPY(code, "NFA_MULTIBYTE"); break;
1706 case NFA_END_MULTIBYTE: STRCPY(code, "NFA_END_MULTIBYTE"); break;
1707
1708 case NFA_COMPOSING: STRCPY(code, "NFA_COMPOSING"); break;
1709 case NFA_END_COMPOSING: STRCPY(code, "NFA_END_COMPOSING"); break;
1710
1711 case NFA_MOPEN + 0:
1712 case NFA_MOPEN + 1:
1713 case NFA_MOPEN + 2:
1714 case NFA_MOPEN + 3:
1715 case NFA_MOPEN + 4:
1716 case NFA_MOPEN + 5:
1717 case NFA_MOPEN + 6:
1718 case NFA_MOPEN + 7:
1719 case NFA_MOPEN + 8:
1720 case NFA_MOPEN + 9:
1721 STRCPY(code, "NFA_MOPEN(x)");
1722 code[10] = c - NFA_MOPEN + '0';
1723 break;
1724 case NFA_MCLOSE + 0:
1725 case NFA_MCLOSE + 1:
1726 case NFA_MCLOSE + 2:
1727 case NFA_MCLOSE + 3:
1728 case NFA_MCLOSE + 4:
1729 case NFA_MCLOSE + 5:
1730 case NFA_MCLOSE + 6:
1731 case NFA_MCLOSE + 7:
1732 case NFA_MCLOSE + 8:
1733 case NFA_MCLOSE + 9:
1734 STRCPY(code, "NFA_MCLOSE(x)");
1735 code[11] = c - NFA_MCLOSE + '0';
1736 break;
1737 case NFA_EOL: STRCPY(code, "NFA_EOL "); break;
1738 case NFA_BOL: STRCPY(code, "NFA_BOL "); break;
1739 case NFA_EOW: STRCPY(code, "NFA_EOW "); break;
1740 case NFA_BOW: STRCPY(code, "NFA_BOW "); break;
1741 case NFA_STAR: STRCPY(code, "NFA_STAR "); break;
1742 case NFA_PLUS: STRCPY(code, "NFA_PLUS "); break;
1743 case NFA_NOT: STRCPY(code, "NFA_NOT "); break;
1744 case NFA_SKIP_CHAR: STRCPY(code, "NFA_SKIP_CHAR"); break;
1745 case NFA_OR: STRCPY(code, "NFA_OR"); break;
1746 case NFA_QUEST: STRCPY(code, "NFA_QUEST"); break;
1747 case NFA_QUEST_NONGREEDY: STRCPY(code, "NFA_QUEST_NON_GREEDY"); break;
1748 case NFA_END_NEG_RANGE: STRCPY(code, "NFA_END_NEG_RANGE"); break;
1749 case NFA_CLASS_ALNUM: STRCPY(code, "NFA_CLASS_ALNUM"); break;
1750 case NFA_CLASS_ALPHA: STRCPY(code, "NFA_CLASS_ALPHA"); break;
1751 case NFA_CLASS_BLANK: STRCPY(code, "NFA_CLASS_BLANK"); break;
1752 case NFA_CLASS_CNTRL: STRCPY(code, "NFA_CLASS_CNTRL"); break;
1753 case NFA_CLASS_DIGIT: STRCPY(code, "NFA_CLASS_DIGIT"); break;
1754 case NFA_CLASS_GRAPH: STRCPY(code, "NFA_CLASS_GRAPH"); break;
1755 case NFA_CLASS_LOWER: STRCPY(code, "NFA_CLASS_LOWER"); break;
1756 case NFA_CLASS_PRINT: STRCPY(code, "NFA_CLASS_PRINT"); break;
1757 case NFA_CLASS_PUNCT: STRCPY(code, "NFA_CLASS_PUNCT"); break;
1758 case NFA_CLASS_SPACE: STRCPY(code, "NFA_CLASS_SPACE"); break;
1759 case NFA_CLASS_UPPER: STRCPY(code, "NFA_CLASS_UPPER"); break;
1760 case NFA_CLASS_XDIGIT: STRCPY(code, "NFA_CLASS_XDIGIT"); break;
1761 case NFA_CLASS_TAB: STRCPY(code, "NFA_CLASS_TAB"); break;
1762 case NFA_CLASS_RETURN: STRCPY(code, "NFA_CLASS_RETURN"); break;
1763 case NFA_CLASS_BACKSPACE: STRCPY(code, "NFA_CLASS_BACKSPACE"); break;
1764 case NFA_CLASS_ESCAPE: STRCPY(code, "NFA_CLASS_ESCAPE"); break;
1765
1766 case NFA_ANY: STRCPY(code, "NFA_ANY"); break;
1767 case NFA_IDENT: STRCPY(code, "NFA_IDENT"); break;
1768 case NFA_SIDENT:STRCPY(code, "NFA_SIDENT"); break;
1769 case NFA_KWORD: STRCPY(code, "NFA_KWORD"); break;
1770 case NFA_SKWORD:STRCPY(code, "NFA_SKWORD"); break;
1771 case NFA_FNAME: STRCPY(code, "NFA_FNAME"); break;
1772 case NFA_SFNAME:STRCPY(code, "NFA_SFNAME"); break;
1773 case NFA_PRINT: STRCPY(code, "NFA_PRINT"); break;
1774 case NFA_SPRINT:STRCPY(code, "NFA_SPRINT"); break;
1775 case NFA_WHITE: STRCPY(code, "NFA_WHITE"); break;
1776 case NFA_NWHITE:STRCPY(code, "NFA_NWHITE"); break;
1777 case NFA_DIGIT: STRCPY(code, "NFA_DIGIT"); break;
1778 case NFA_NDIGIT:STRCPY(code, "NFA_NDIGIT"); break;
1779 case NFA_HEX: STRCPY(code, "NFA_HEX"); break;
1780 case NFA_NHEX: STRCPY(code, "NFA_NHEX"); break;
1781 case NFA_OCTAL: STRCPY(code, "NFA_OCTAL"); break;
1782 case NFA_NOCTAL:STRCPY(code, "NFA_NOCTAL"); break;
1783 case NFA_WORD: STRCPY(code, "NFA_WORD"); break;
1784 case NFA_NWORD: STRCPY(code, "NFA_NWORD"); break;
1785 case NFA_HEAD: STRCPY(code, "NFA_HEAD"); break;
1786 case NFA_NHEAD: STRCPY(code, "NFA_NHEAD"); break;
1787 case NFA_ALPHA: STRCPY(code, "NFA_ALPHA"); break;
1788 case NFA_NALPHA:STRCPY(code, "NFA_NALPHA"); break;
1789 case NFA_LOWER: STRCPY(code, "NFA_LOWER"); break;
1790 case NFA_NLOWER:STRCPY(code, "NFA_NLOWER"); break;
1791 case NFA_UPPER: STRCPY(code, "NFA_UPPER"); break;
1792 case NFA_NUPPER:STRCPY(code, "NFA_NUPPER"); break;
1793
1794 default:
1795 STRCPY(code, "CHAR(x)");
1796 code[5] = c;
1797 }
1798
1799 if (addnl == TRUE)
1800 STRCAT(code, " + NEWLINE ");
1801
1802}
1803
1804#ifdef ENABLE_LOG
1805static FILE *log_fd;
1806
1807/*
1808 * Print the postfix notation of the current regexp.
1809 */
1810 static void
1811nfa_postfix_dump(expr, retval)
1812 char_u *expr;
1813 int retval;
1814{
1815 int *p;
1816 FILE *f;
1817
1818 f = fopen("LOG.log", "a");
1819 if (f != NULL)
1820 {
1821 fprintf(f, "\n-------------------------\n");
1822 if (retval == FAIL)
1823 fprintf(f, ">>> NFA engine failed ... \n");
1824 else if (retval == OK)
1825 fprintf(f, ">>> NFA engine succeeded !\n");
1826 fprintf(f, "Regexp: \"%s\"\nPostfix notation (char): \"", expr);
Bram Moolenaar745fc022013-05-20 22:20:02 +02001827 for (p = post_start; *p && p < post_end; p++)
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02001828 {
1829 nfa_set_code(*p);
1830 fprintf(f, "%s, ", code);
1831 }
1832 fprintf(f, "\"\nPostfix notation (int): ");
Bram Moolenaar745fc022013-05-20 22:20:02 +02001833 for (p = post_start; *p && p < post_end; p++)
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02001834 fprintf(f, "%d ", *p);
1835 fprintf(f, "\n\n");
1836 fclose(f);
1837 }
1838}
1839
1840/*
1841 * Print the NFA starting with a root node "state".
1842 */
1843 static void
1844nfa_print_state(debugf, state, ident)
1845 FILE *debugf;
1846 nfa_state_T *state;
1847 int ident;
1848{
1849 int i;
1850
1851 if (state == NULL)
1852 return;
1853
1854 fprintf(debugf, "(%2d)", abs(state->id));
1855 for (i = 0; i < ident; i++)
1856 fprintf(debugf, "%c", ' ');
1857
1858 nfa_set_code(state->c);
1859 fprintf(debugf, "%s %s (%d) (id=%d)\n",
1860 state->negated ? "NOT" : "", code, state->c, abs(state->id));
1861 if (state->id < 0)
1862 return;
1863
1864 state->id = abs(state->id) * -1;
1865 nfa_print_state(debugf, state->out, ident + 4);
1866 nfa_print_state(debugf, state->out1, ident + 4);
1867}
1868
1869/*
1870 * Print the NFA state machine.
1871 */
1872 static void
1873nfa_dump(prog)
1874 nfa_regprog_T *prog;
1875{
1876 FILE *debugf = fopen("LOG.log", "a");
1877
1878 if (debugf != NULL)
1879 {
1880 nfa_print_state(debugf, prog->start, 0);
1881 fclose(debugf);
1882 }
1883}
1884#endif /* ENABLE_LOG */
1885#endif /* DEBUG */
1886
1887/*
1888 * Parse r.e. @expr and convert it into postfix form.
1889 * Return the postfix string on success, NULL otherwise.
1890 */
1891 static int *
1892re2post()
1893{
1894 if (nfa_reg(REG_NOPAREN) == FAIL)
1895 return NULL;
1896 EMIT(NFA_MOPEN);
1897 return post_start;
1898}
1899
1900/* NB. Some of the code below is inspired by Russ's. */
1901
1902/*
1903 * Represents an NFA state plus zero or one or two arrows exiting.
1904 * if c == MATCH, no arrows out; matching state.
1905 * If c == SPLIT, unlabeled arrows to out and out1 (if != NULL).
1906 * If c < 256, labeled arrow with character c to out.
1907 */
1908
1909static nfa_state_T *state_ptr; /* points to nfa_prog->state */
1910
1911/*
1912 * Allocate and initialize nfa_state_T.
1913 */
1914 static nfa_state_T *
1915new_state(c, out, out1)
1916 int c;
1917 nfa_state_T *out;
1918 nfa_state_T *out1;
1919{
1920 nfa_state_T *s;
1921
1922 if (istate >= nstate)
1923 return NULL;
1924
1925 s = &state_ptr[istate++];
1926
1927 s->c = c;
1928 s->out = out;
1929 s->out1 = out1;
1930
1931 s->id = istate;
1932 s->lastlist = 0;
1933 s->lastthread = NULL;
1934 s->visits = 0;
1935 s->negated = FALSE;
1936
1937 return s;
1938}
1939
1940/*
1941 * A partially built NFA without the matching state filled in.
1942 * Frag_T.start points at the start state.
1943 * Frag_T.out is a list of places that need to be set to the
1944 * next state for this fragment.
1945 */
1946typedef union Ptrlist Ptrlist;
1947struct Frag
1948{
1949 nfa_state_T *start;
1950 Ptrlist *out;
1951};
1952typedef struct Frag Frag_T;
1953
1954static Frag_T frag __ARGS((nfa_state_T *start, Ptrlist *out));
1955static Ptrlist *list1 __ARGS((nfa_state_T **outp));
1956static void patch __ARGS((Ptrlist *l, nfa_state_T *s));
1957static Ptrlist *append __ARGS((Ptrlist *l1, Ptrlist *l2));
1958static void st_push __ARGS((Frag_T s, Frag_T **p, Frag_T *stack_end));
1959static Frag_T st_pop __ARGS((Frag_T **p, Frag_T *stack));
1960
1961/*
Bram Moolenaar053bb602013-05-20 13:55:21 +02001962 * Initialize a Frag_T struct and return it.
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02001963 */
1964 static Frag_T
1965frag(start, out)
1966 nfa_state_T *start;
1967 Ptrlist *out;
1968{
Bram Moolenaar053bb602013-05-20 13:55:21 +02001969 Frag_T n;
1970
1971 n.start = start;
1972 n.out = out;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02001973 return n;
1974}
1975
1976/*
1977 * Since the out pointers in the list are always
1978 * uninitialized, we use the pointers themselves
1979 * as storage for the Ptrlists.
1980 */
1981union Ptrlist
1982{
1983 Ptrlist *next;
1984 nfa_state_T *s;
1985};
1986
1987/*
1988 * Create singleton list containing just outp.
1989 */
1990 static Ptrlist *
1991list1(outp)
1992 nfa_state_T **outp;
1993{
1994 Ptrlist *l;
1995
1996 l = (Ptrlist *)outp;
1997 l->next = NULL;
1998 return l;
1999}
2000
2001/*
2002 * Patch the list of states at out to point to start.
2003 */
2004 static void
2005patch(l, s)
2006 Ptrlist *l;
2007 nfa_state_T *s;
2008{
2009 Ptrlist *next;
2010
2011 for (; l; l = next)
2012 {
2013 next = l->next;
2014 l->s = s;
2015 }
2016}
2017
2018
2019/*
2020 * Join the two lists l1 and l2, returning the combination.
2021 */
2022 static Ptrlist *
2023append(l1, l2)
2024 Ptrlist *l1;
2025 Ptrlist *l2;
2026{
2027 Ptrlist *oldl1;
2028
2029 oldl1 = l1;
2030 while (l1->next)
2031 l1 = l1->next;
2032 l1->next = l2;
2033 return oldl1;
2034}
2035
2036/*
2037 * Stack used for transforming postfix form into NFA.
2038 */
2039static Frag_T empty;
2040
2041 static void
2042st_error(postfix, end, p)
2043 int *postfix;
2044 int *end;
2045 int *p;
2046{
2047 FILE *df;
2048 int *p2;
2049
2050 df = fopen("stack.err", "a");
2051 if (df)
2052 {
2053 fprintf(df, "Error popping the stack!\n");
2054#ifdef DEBUG
2055 fprintf(df, "Current regexp is \"%s\"\n", nfa_regengine.expr);
2056#endif
2057 fprintf(df, "Postfix form is: ");
2058#ifdef DEBUG
2059 for (p2 = postfix; p2 < end; p2++)
2060 {
2061 nfa_set_code(*p2);
2062 fprintf(df, "%s, ", code);
2063 }
2064 nfa_set_code(*p);
2065 fprintf(df, "\nCurrent position is: ");
2066 for (p2 = postfix; p2 <= p; p2 ++)
2067 {
2068 nfa_set_code(*p2);
2069 fprintf(df, "%s, ", code);
2070 }
2071#else
2072 for (p2 = postfix; p2 < end; p2++)
2073 {
2074 fprintf(df, "%d, ", *p2);
2075 }
2076 fprintf(df, "\nCurrent position is: ");
2077 for (p2 = postfix; p2 <= p; p2 ++)
2078 {
2079 fprintf(df, "%d, ", *p2);
2080 }
2081#endif
2082 fprintf(df, "\n--------------------------\n");
2083 fclose(df);
2084 }
2085 EMSG(_("E874: (NFA) Could not pop the stack !"));
2086}
2087
2088/*
2089 * Push an item onto the stack.
2090 */
2091 static void
2092st_push(s, p, stack_end)
2093 Frag_T s;
2094 Frag_T **p;
2095 Frag_T *stack_end;
2096{
2097 Frag_T *stackp = *p;
2098
2099 if (stackp >= stack_end)
2100 return;
2101 *stackp = s;
2102 *p = *p + 1;
2103}
2104
2105/*
2106 * Pop an item from the stack.
2107 */
2108 static Frag_T
2109st_pop(p, stack)
2110 Frag_T **p;
2111 Frag_T *stack;
2112{
2113 Frag_T *stackp;
2114
2115 *p = *p - 1;
2116 stackp = *p;
2117 if (stackp < stack)
2118 return empty;
2119 return **p;
2120}
2121
2122/*
2123 * Convert a postfix form into its equivalent NFA.
2124 * Return the NFA start state on success, NULL otherwise.
2125 */
2126 static nfa_state_T *
2127post2nfa(postfix, end, nfa_calc_size)
2128 int *postfix;
2129 int *end;
2130 int nfa_calc_size;
2131{
2132 int *p;
2133 int mopen;
2134 int mclose;
2135 Frag_T *stack = NULL;
2136 Frag_T *stackp = NULL;
2137 Frag_T *stack_end = NULL;
2138 Frag_T e1;
2139 Frag_T e2;
2140 Frag_T e;
2141 nfa_state_T *s;
2142 nfa_state_T *s1;
2143 nfa_state_T *matchstate;
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002144 nfa_state_T *ret = NULL;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002145
2146 if (postfix == NULL)
2147 return NULL;
2148
Bram Moolenaar053bb602013-05-20 13:55:21 +02002149#define PUSH(s) st_push((s), &stackp, stack_end)
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002150#define POP() st_pop(&stackp, stack); \
2151 if (stackp < stack) \
2152 { \
2153 st_error(postfix, end, p); \
2154 return NULL; \
2155 }
2156
2157 if (nfa_calc_size == FALSE)
2158 {
2159 /* Allocate space for the stack. Max states on the stack : nstate */
Bram Moolenaare3c7b862013-05-20 21:57:03 +02002160 stack = (Frag_T *) lalloc((nstate + 1) * sizeof(Frag_T), TRUE);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002161 stackp = stack;
Bram Moolenaare3c7b862013-05-20 21:57:03 +02002162 stack_end = stack + (nstate + 1);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002163 }
2164
2165 for (p = postfix; p < end; ++p)
2166 {
2167 switch (*p)
2168 {
2169 case NFA_CONCAT:
2170 /* Catenation.
2171 * Pay attention: this operator does not exist
2172 * in the r.e. itself (it is implicit, really).
2173 * It is added when r.e. is translated to postfix
2174 * form in re2post().
2175 *
2176 * No new state added here. */
2177 if (nfa_calc_size == TRUE)
2178 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002179 /* nstate += 0; */
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002180 break;
2181 }
2182 e2 = POP();
2183 e1 = POP();
2184 patch(e1.out, e2.start);
2185 PUSH(frag(e1.start, e2.out));
2186 break;
2187
2188 case NFA_NOT:
2189 /* Negation of a character */
2190 if (nfa_calc_size == TRUE)
2191 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002192 /* nstate += 0; */
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002193 break;
2194 }
2195 e1 = POP();
2196 e1.start->negated = TRUE;
2197 if (e1.start->c == NFA_MULTIBYTE || e1.start->c == NFA_COMPOSING)
2198 e1.start->out1->negated = TRUE;
2199 PUSH(e1);
2200 break;
2201
2202 case NFA_OR:
2203 /* Alternation */
2204 if (nfa_calc_size == TRUE)
2205 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002206 nstate++;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002207 break;
2208 }
2209 e2 = POP();
2210 e1 = POP();
2211 s = new_state(NFA_SPLIT, e1.start, e2.start);
2212 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002213 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002214 PUSH(frag(s, append(e1.out, e2.out)));
2215 break;
2216
2217 case NFA_STAR:
2218 /* Zero or more */
2219 if (nfa_calc_size == TRUE)
2220 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002221 nstate++;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002222 break;
2223 }
2224 e = POP();
2225 s = new_state(NFA_SPLIT, e.start, NULL);
2226 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002227 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002228 patch(e.out, s);
2229 PUSH(frag(s, list1(&s->out1)));
2230 break;
2231
2232 case NFA_QUEST:
2233 /* one or zero atoms=> greedy match */
2234 if (nfa_calc_size == TRUE)
2235 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002236 nstate++;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002237 break;
2238 }
2239 e = POP();
2240 s = new_state(NFA_SPLIT, e.start, NULL);
2241 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002242 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002243 PUSH(frag(s, append(e.out, list1(&s->out1))));
2244 break;
2245
2246 case NFA_QUEST_NONGREEDY:
2247 /* zero or one atoms => non-greedy match */
2248 if (nfa_calc_size == TRUE)
2249 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002250 nstate++;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002251 break;
2252 }
2253 e = POP();
2254 s = new_state(NFA_SPLIT, NULL, e.start);
2255 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002256 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002257 PUSH(frag(s, append(e.out, list1(&s->out))));
2258 break;
2259
2260 case NFA_PLUS:
2261 /* One or more */
2262 if (nfa_calc_size == TRUE)
2263 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002264 nstate++;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002265 break;
2266 }
2267 e = POP();
2268 s = new_state(NFA_SPLIT, e.start, NULL);
2269 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002270 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002271 patch(e.out, s);
2272 PUSH(frag(e.start, list1(&s->out1)));
2273 break;
2274
2275 case NFA_SKIP_CHAR:
2276 /* Symbol of 0-length, Used in a repetition
2277 * with max/min count of 0 */
2278 if (nfa_calc_size == TRUE)
2279 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002280 nstate++;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002281 break;
2282 }
2283 s = new_state(NFA_SKIP_CHAR, NULL, NULL);
2284 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002285 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002286 PUSH(frag(s, list1(&s->out)));
2287 break;
2288
2289 case NFA_PREV_ATOM_NO_WIDTH:
2290 /* The \@= operator: match the preceding atom with 0 width.
2291 * Surrounds the preceding atom with START_INVISIBLE and
2292 * END_INVISIBLE, similarly to MOPEN.
2293 */
2294 /* TODO: Maybe this drops the speed? */
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002295 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002296
2297 if (nfa_calc_size == TRUE)
2298 {
2299 nstate += 2;
2300 break;
2301 }
2302 e = POP();
2303 s1 = new_state(NFA_END_INVISIBLE, NULL, NULL);
2304 if (s1 == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002305 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002306 patch(e.out, s1);
2307
2308 s = new_state(NFA_START_INVISIBLE, e.start, s1);
2309 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002310 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002311 PUSH(frag(s, list1(&s1->out)));
2312 break;
2313
2314 case NFA_MOPEN + 0: /* Submatch */
2315 case NFA_MOPEN + 1:
2316 case NFA_MOPEN + 2:
2317 case NFA_MOPEN + 3:
2318 case NFA_MOPEN + 4:
2319 case NFA_MOPEN + 5:
2320 case NFA_MOPEN + 6:
2321 case NFA_MOPEN + 7:
2322 case NFA_MOPEN + 8:
2323 case NFA_MOPEN + 9:
2324 case NFA_NOPEN: /* \%( "Invisible Submatch" */
2325 case NFA_MULTIBYTE: /* mbyte char */
2326 case NFA_COMPOSING: /* composing char */
2327 if (nfa_calc_size == TRUE)
2328 {
2329 nstate += 2;
2330 break;
2331 }
2332
2333 mopen = *p;
2334 switch (*p)
2335 {
2336 case NFA_NOPEN:
2337 mclose = NFA_NCLOSE;
2338 break;
2339 case NFA_MULTIBYTE:
2340 mclose = NFA_END_MULTIBYTE;
2341 break;
2342 case NFA_COMPOSING:
2343 mclose = NFA_END_COMPOSING;
2344 break;
2345 default:
2346 /* NFA_MOPEN(0) ... NFA_MOPEN(9) */
2347 mclose = *p + NSUBEXP;
2348 break;
2349 }
2350
2351 /* Allow "NFA_MOPEN" as a valid postfix representation for
2352 * the empty regexp "". In this case, the NFA will be
2353 * NFA_MOPEN -> NFA_MCLOSE. Note that this also allows
2354 * empty groups of parenthesis, and empty mbyte chars */
2355 if (stackp == stack)
2356 {
2357 s = new_state(mopen, NULL, NULL);
2358 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002359 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002360 s1 = new_state(mclose, NULL, NULL);
2361 if (s1 == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002362 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002363 patch(list1(&s->out), s1);
2364 PUSH(frag(s, list1(&s1->out)));
2365 break;
2366 }
2367
2368 /* At least one node was emitted before NFA_MOPEN, so
2369 * at least one node will be between NFA_MOPEN and NFA_MCLOSE */
2370 e = POP();
2371 s = new_state(mopen, e.start, NULL); /* `(' */
2372 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002373 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002374
2375 s1 = new_state(mclose, NULL, NULL); /* `)' */
2376 if (s1 == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002377 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002378 patch(e.out, s1);
2379
2380 if (mopen == NFA_MULTIBYTE || mopen == NFA_COMPOSING)
2381 /* MULTIBYTE->out1 = END_MULTIBYTE
2382 * COMPOSING->out1 = END_COMPOSING */
2383 patch(list1(&s->out1), s1);
2384
2385 PUSH(frag(s, list1(&s1->out)));
2386 break;
2387
2388 case NFA_ZSTART:
2389 case NFA_ZEND:
2390 default:
2391 /* Operands */
2392 if (nfa_calc_size == TRUE)
2393 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002394 nstate++;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002395 break;
2396 }
2397 s = new_state(*p, NULL, NULL);
2398 if (s == NULL)
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002399 goto theend;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002400 PUSH(frag(s, list1(&s->out)));
2401 break;
2402
2403 } /* switch(*p) */
2404
2405 } /* for(p = postfix; *p; ++p) */
2406
2407 if (nfa_calc_size == TRUE)
2408 {
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02002409 nstate++;
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002410 goto theend; /* Return value when counting size is ignored anyway */
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002411 }
2412
2413 e = POP();
2414 if (stackp != stack)
2415 EMSG_RET_NULL(_("E875: (NFA regexp) (While converting from postfix to NFA), too many states left on stack"));
2416
2417 if (istate >= nstate)
2418 EMSG_RET_NULL(_("E876: (NFA regexp) Not enough space to store the whole NFA "));
2419
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002420 matchstate = &state_ptr[istate++]; /* the match state */
2421 matchstate->c = NFA_MATCH;
2422 matchstate->out = matchstate->out1 = NULL;
2423
2424 patch(e.out, matchstate);
Bram Moolenaarb09d9832013-05-21 16:28:11 +02002425 ret = e.start;
2426
2427theend:
2428 vim_free(stack);
2429 return ret;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002430
2431#undef POP1
2432#undef PUSH1
2433#undef POP2
2434#undef PUSH2
2435#undef POP
2436#undef PUSH
2437}
2438
2439/****************************************************************
2440 * NFA execution code.
2441 ****************************************************************/
2442
2443/* thread_T contains runtime information of a NFA state */
2444struct thread
2445{
2446 nfa_state_T *state;
2447 regsub_T sub; /* submatch info */
2448};
2449
2450typedef struct
2451{
2452 thread_T *t;
2453 int n;
2454} List;
2455
2456static void addstate __ARGS((List *l, nfa_state_T *state, regsub_T *m, int off, int lid, int *match));
2457
2458 static void
2459addstate(l, state, m, off, lid, match)
2460 List *l; /* runtime state list */
2461 nfa_state_T *state; /* state to update */
2462 regsub_T *m; /* pointers to subexpressions */
Bram Moolenaar35b23862013-05-22 23:00:40 +02002463 int off; /* byte offset, when -1 go to next line */
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002464 int lid;
2465 int *match; /* found match? */
2466{
2467 regsub_T save;
2468 int subidx = 0;
2469
2470 if (l == NULL || state == NULL)
2471 return;
2472
2473 switch (state->c)
2474 {
2475 case NFA_SPLIT:
2476 case NFA_NOT:
2477 case NFA_NOPEN:
2478 case NFA_NCLOSE:
2479 case NFA_MCLOSE:
2480 case NFA_MCLOSE + 1:
2481 case NFA_MCLOSE + 2:
2482 case NFA_MCLOSE + 3:
2483 case NFA_MCLOSE + 4:
2484 case NFA_MCLOSE + 5:
2485 case NFA_MCLOSE + 6:
2486 case NFA_MCLOSE + 7:
2487 case NFA_MCLOSE + 8:
2488 case NFA_MCLOSE + 9:
2489 /* Do not remember these nodes in list "thislist" or "nextlist" */
2490 break;
2491
2492 default:
2493 if (state->lastlist == lid)
2494 {
2495 if (++state->visits > 2)
2496 return;
2497 }
2498 else
2499 {
2500 /* add the state to the list */
2501 state->lastlist = lid;
2502 state->lastthread = &l->t[l->n++];
2503 state->lastthread->state = state;
2504 state->lastthread->sub = *m;
2505 }
2506 }
2507
2508#ifdef ENABLE_LOG
2509 nfa_set_code(state->c);
2510 fprintf(log_fd, "> Adding state %d to list. Character %s, code %d\n",
2511 abs(state->id), code, state->c);
2512#endif
2513 switch (state->c)
2514 {
2515 case NFA_MATCH:
2516 *match = TRUE;
2517 break;
2518
2519 case NFA_SPLIT:
2520 addstate(l, state->out, m, off, lid, match);
2521 addstate(l, state->out1, m, off, lid, match);
2522 break;
2523
2524 case NFA_SKIP_CHAR:
2525 addstate(l, state->out, m, off, lid, match);
2526 break;
2527
2528#if 0
2529 case NFA_END_NEG_RANGE:
2530 /* Nothing to handle here. nfa_regmatch() will take care of it */
2531 break;
2532
2533 case NFA_NOT:
2534 EMSG(_("E999: (NFA regexp internal error) Should not process NOT node !"));
2535#ifdef ENABLE_LOG
2536 fprintf(f, "\n\n>>> E999: Added state NFA_NOT to a list ... Something went wrong ! Why wasn't it processed already? \n\n");
2537#endif
2538 break;
2539
2540 case NFA_COMPOSING:
2541 /* nfa_regmatch() will match all the bytes of this composing char. */
2542 break;
2543
2544 case NFA_MULTIBYTE:
2545 /* nfa_regmatch() will match all the bytes of this multibyte char. */
2546 break;
2547#endif
2548
2549 case NFA_END_MULTIBYTE:
2550 /* Successfully matched this mbyte char */
2551 addstate(l, state->out, m, off, lid, match);
2552 break;
2553
2554 case NFA_NOPEN:
2555 case NFA_NCLOSE:
2556 addstate(l, state->out, m, off, lid, match);
2557 break;
2558
2559 /* If this state is reached, then a recursive call of nfa_regmatch()
2560 * succeeded. the next call saves the found submatches in the
2561 * first state after the "invisible" branch. */
2562#if 0
2563 case NFA_END_INVISIBLE:
2564 break;
2565#endif
2566
2567 case NFA_MOPEN + 0:
2568 case NFA_MOPEN + 1:
2569 case NFA_MOPEN + 2:
2570 case NFA_MOPEN + 3:
2571 case NFA_MOPEN + 4:
2572 case NFA_MOPEN + 5:
2573 case NFA_MOPEN + 6:
2574 case NFA_MOPEN + 7:
2575 case NFA_MOPEN + 8:
2576 case NFA_MOPEN + 9:
2577 case NFA_ZSTART:
2578 subidx = state->c - NFA_MOPEN;
2579 if (state->c == NFA_ZSTART)
2580 subidx = 0;
2581
2582 if (REG_MULTI)
2583 {
2584 save.startpos[subidx] = m->startpos[subidx];
2585 save.endpos[subidx] = m->endpos[subidx];
Bram Moolenaar35b23862013-05-22 23:00:40 +02002586 if (off == -1)
2587 {
2588 m->startpos[subidx].lnum = reglnum + 1;
2589 m->startpos[subidx].col = 0;
2590 }
2591 else
2592 {
2593 m->startpos[subidx].lnum = reglnum;
2594 m->startpos[subidx].col =
2595 (colnr_T)(reginput - regline + off);
2596 }
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002597 }
2598 else
2599 {
2600 save.start[subidx] = m->start[subidx];
2601 save.end[subidx] = m->end[subidx];
2602 m->start[subidx] = reginput + off;
2603 }
2604
2605 addstate(l, state->out, m, off, lid, match);
2606
2607 if (REG_MULTI)
2608 {
2609 m->startpos[subidx] = save.startpos[subidx];
2610 m->endpos[subidx] = save.endpos[subidx];
2611 }
2612 else
2613 {
2614 m->start[subidx] = save.start[subidx];
2615 m->end[subidx] = save.end[subidx];
2616 }
2617 break;
2618
2619 case NFA_MCLOSE + 0:
2620 if (nfa_has_zend == TRUE)
2621 {
2622 addstate(l, state->out, m, off, lid, match);
2623 break;
2624 }
2625 case NFA_MCLOSE + 1:
2626 case NFA_MCLOSE + 2:
2627 case NFA_MCLOSE + 3:
2628 case NFA_MCLOSE + 4:
2629 case NFA_MCLOSE + 5:
2630 case NFA_MCLOSE + 6:
2631 case NFA_MCLOSE + 7:
2632 case NFA_MCLOSE + 8:
2633 case NFA_MCLOSE + 9:
2634 case NFA_ZEND:
2635 subidx = state->c - NFA_MCLOSE;
2636 if (state->c == NFA_ZEND)
2637 subidx = 0;
2638
2639 if (REG_MULTI)
2640 {
2641 save.startpos[subidx] = m->startpos[subidx];
2642 save.endpos[subidx] = m->endpos[subidx];
Bram Moolenaar35b23862013-05-22 23:00:40 +02002643 if (off == -1)
2644 {
2645 m->endpos[subidx].lnum = reglnum + 1;
2646 m->endpos[subidx].col = 0;
2647 }
2648 else
2649 {
2650 m->endpos[subidx].lnum = reglnum;
2651 m->endpos[subidx].col = (colnr_T)(reginput - regline + off);
2652 }
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002653 }
2654 else
2655 {
2656 save.start[subidx] = m->start[subidx];
2657 save.end[subidx] = m->end[subidx];
2658 m->end[subidx] = reginput + off;
2659 }
2660
2661 addstate(l, state->out, m, off, lid, match);
2662
2663 if (REG_MULTI)
2664 {
2665 m->startpos[subidx] = save.startpos[subidx];
2666 m->endpos[subidx] = save.endpos[subidx];
2667 }
2668 else
2669 {
2670 m->start[subidx] = save.start[subidx];
2671 m->end[subidx] = save.end[subidx];
2672 }
2673 break;
2674 }
2675}
2676
2677/*
2678 * Check character class "class" against current character c.
2679 */
2680 static int
2681check_char_class(class, c)
2682 int class;
2683 int c;
2684{
2685 switch (class)
2686 {
2687 case NFA_CLASS_ALNUM:
Bram Moolenaar745fc022013-05-20 22:20:02 +02002688 if (c >= 1 && c <= 255 && isalnum(c))
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002689 return OK;
2690 break;
2691 case NFA_CLASS_ALPHA:
Bram Moolenaar745fc022013-05-20 22:20:02 +02002692 if (c >= 1 && c <= 255 && isalpha(c))
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002693 return OK;
2694 break;
2695 case NFA_CLASS_BLANK:
2696 if (c == ' ' || c == '\t')
2697 return OK;
2698 break;
2699 case NFA_CLASS_CNTRL:
Bram Moolenaar745fc022013-05-20 22:20:02 +02002700 if (c >= 1 && c <= 255 && iscntrl(c))
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002701 return OK;
2702 break;
2703 case NFA_CLASS_DIGIT:
2704 if (VIM_ISDIGIT(c))
2705 return OK;
2706 break;
2707 case NFA_CLASS_GRAPH:
Bram Moolenaar745fc022013-05-20 22:20:02 +02002708 if (c >= 1 && c <= 255 && isgraph(c))
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002709 return OK;
2710 break;
2711 case NFA_CLASS_LOWER:
2712 if (MB_ISLOWER(c))
2713 return OK;
2714 break;
2715 case NFA_CLASS_PRINT:
2716 if (vim_isprintc(c))
2717 return OK;
2718 break;
2719 case NFA_CLASS_PUNCT:
Bram Moolenaar745fc022013-05-20 22:20:02 +02002720 if (c >= 1 && c <= 255 && ispunct(c))
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002721 return OK;
2722 break;
2723 case NFA_CLASS_SPACE:
2724 if ((c >=9 && c <= 13) || (c == ' '))
2725 return OK;
2726 break;
2727 case NFA_CLASS_UPPER:
2728 if (MB_ISUPPER(c))
2729 return OK;
2730 break;
2731 case NFA_CLASS_XDIGIT:
2732 if (vim_isxdigit(c))
2733 return OK;
2734 break;
2735 case NFA_CLASS_TAB:
2736 if (c == '\t')
2737 return OK;
2738 break;
2739 case NFA_CLASS_RETURN:
2740 if (c == '\r')
2741 return OK;
2742 break;
2743 case NFA_CLASS_BACKSPACE:
2744 if (c == '\b')
2745 return OK;
2746 break;
2747 case NFA_CLASS_ESCAPE:
2748 if (c == '\033')
2749 return OK;
2750 break;
2751
2752 default:
2753 /* should not be here :P */
2754 EMSG_RET_FAIL(_("E877: (NFA regexp) Invalid character class "));
2755 }
2756 return FAIL;
2757}
2758
2759/*
2760 * Set all NFA nodes' list ID equal to -1.
2761 */
2762 static void
2763nfa_set_neg_listids(start)
2764 nfa_state_T *start;
2765{
2766 if (start == NULL)
2767 return;
2768 if (start->lastlist >= 0)
2769 {
2770 start->lastlist = -1;
2771 nfa_set_neg_listids(start->out);
2772 nfa_set_neg_listids(start->out1);
2773 }
2774}
2775
2776/*
2777 * Set all NFA nodes' list ID equal to 0.
2778 */
2779 static void
2780nfa_set_null_listids(start)
2781 nfa_state_T *start;
2782{
2783 if (start == NULL)
2784 return;
2785 if (start->lastlist == -1)
2786 {
2787 start->lastlist = 0;
2788 nfa_set_null_listids(start->out);
2789 nfa_set_null_listids(start->out1);
2790 }
2791}
2792
2793/*
2794 * Save list IDs for all NFA states in "list".
2795 */
2796 static void
2797nfa_save_listids(start, list)
2798 nfa_state_T *start;
2799 int *list;
2800{
2801 if (start == NULL)
2802 return;
2803 if (start->lastlist != -1)
2804 {
2805 list[abs(start->id)] = start->lastlist;
2806 start->lastlist = -1;
2807 nfa_save_listids(start->out, list);
2808 nfa_save_listids(start->out1, list);
2809 }
2810}
2811
2812/*
2813 * Restore list IDs from "list" to all NFA states.
2814 */
2815 static void
2816nfa_restore_listids(start, list)
2817 nfa_state_T *start;
2818 int *list;
2819{
2820 if (start == NULL)
2821 return;
2822 if (start->lastlist == -1)
2823 {
2824 start->lastlist = list[abs(start->id)];
2825 nfa_restore_listids(start->out, list);
2826 nfa_restore_listids(start->out1, list);
2827 }
2828}
2829
2830/*
2831 * Main matching routine.
2832 *
2833 * Run NFA to determine whether it matches reginput.
2834 *
2835 * Return TRUE if there is a match, FALSE otherwise.
2836 * Note: Caller must ensure that: start != NULL.
2837 */
2838 static int
2839nfa_regmatch(start, submatch, m)
2840 nfa_state_T *start;
2841 regsub_T *submatch;
2842 regsub_T *m;
2843{
2844 int c = -1;
2845 int n;
2846 int i = 0;
2847 int result;
2848 int size = 0;
2849 int match = FALSE;
2850 int flag = 0;
2851 int old_reglnum = -1;
Bram Moolenaar35b23862013-05-22 23:00:40 +02002852 int go_to_nextline;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002853 thread_T *t;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002854 char_u *old_reginput = NULL;
2855 char_u *old_regline = NULL;
2856 nfa_state_T *sta;
2857 nfa_state_T *end;
2858 List list[3];
2859 List *listtbl[2][2];
2860 List *ll;
2861 int listid = 1;
2862 int endnode = 0;
2863 List *thislist;
2864 List *nextlist;
2865 List *neglist;
2866 int *listids = NULL;
2867 int j = 0;
2868 int len = 0;
Bram Moolenaar7fcff1f2013-05-20 21:49:13 +02002869#ifdef NFA_REGEXP_DEBUG_LOG
2870 FILE *debug = fopen(NFA_REGEXP_DEBUG_LOG_NAME, "a");
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002871
2872 if (debug == NULL)
2873 {
Bram Moolenaar7fcff1f2013-05-20 21:49:13 +02002874 EMSG2(_("(NFA) COULD NOT OPEN %s !"), NFA_REGEXP_DEBUG_LOG_NAME);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002875 return FALSE;
2876 }
2877#endif
2878
2879 /* Allocate memory for the lists of nodes */
2880 size = (nstate + 1) * sizeof(thread_T);
2881 list[0].t = (thread_T *)lalloc(size, TRUE);
2882 list[1].t = (thread_T *)lalloc(size, TRUE);
2883 list[2].t = (thread_T *)lalloc(size, TRUE);
2884 if (list[0].t == NULL || list[1].t == NULL || list[2].t == NULL)
2885 goto theend;
2886 vim_memset(list[0].t, 0, size);
2887 vim_memset(list[1].t, 0, size);
2888 vim_memset(list[2].t, 0, size);
2889
2890#ifdef ENABLE_LOG
2891 log_fd = fopen(LOG_NAME, "a");
2892 if (log_fd != NULL)
2893 {
2894 fprintf(log_fd, "**********************************\n");
2895 nfa_set_code(start->c);
2896 fprintf(log_fd, " RUNNING nfa_regmatch() starting with state %d, code %s\n",
2897 abs(start->id), code);
2898 fprintf(log_fd, "**********************************\n");
2899 }
2900 else
2901 {
2902 EMSG(_("Could not open temporary log file for writing, displaying on stderr ... "));
2903 log_fd = stderr;
2904 }
2905#endif
2906
2907 thislist = &list[0];
2908 thislist->n = 0;
2909 nextlist = &list[1];
2910 nextlist->n = 0;
2911 neglist = &list[2];
2912 neglist->n = 0;
2913#ifdef ENABLE_LOG
2914 fprintf(log_fd, "(---) STARTSTATE\n");
2915#endif
2916 addstate(thislist, start, m, 0, listid, &match);
2917
2918 /* There are two cases when the NFA advances: 1. input char matches the
2919 * NFA node and 2. input char does not match the NFA node, but the next
2920 * node is NFA_NOT. The following macro calls addstate() according to
2921 * these rules. It is used A LOT, so use the "listtbl" table for speed */
2922 listtbl[0][0] = NULL;
2923 listtbl[0][1] = neglist;
2924 listtbl[1][0] = nextlist;
2925 listtbl[1][1] = NULL;
2926#define ADD_POS_NEG_STATE(node) \
2927 ll = listtbl[result ? 1 : 0][node->negated]; \
2928 if (ll != NULL) \
2929 addstate(ll, node->out , &t->sub, n, listid + 1, &match);
2930
2931
2932 /*
2933 * Run for each character.
2934 */
Bram Moolenaar35b23862013-05-22 23:00:40 +02002935 for (;;)
2936 {
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002937#ifdef FEAT_MBYTE
2938 if (has_mbyte)
2939 {
2940 c = (*mb_ptr2char)(reginput);
2941 n = (*mb_ptr2len)(reginput);
2942 }
2943 else
2944#endif
2945 {
2946 c = *reginput;
2947 n = 1;
2948 }
2949 if (c == NUL)
Bram Moolenaar35b23862013-05-22 23:00:40 +02002950 {
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002951 n = 0;
Bram Moolenaar35b23862013-05-22 23:00:40 +02002952 go_to_nextline = FALSE;
2953 }
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002954
2955 /* swap lists */
2956 thislist = &list[flag];
2957 nextlist = &list[flag ^= 1];
2958 nextlist->n = 0; /* `clear' nextlist */
2959 listtbl[1][0] = nextlist;
2960 ++listid;
2961
2962#ifdef ENABLE_LOG
2963 fprintf(log_fd, "------------------------------------------\n");
2964 fprintf(log_fd, ">>> Reginput is \"%s\"\n", reginput);
2965 fprintf(log_fd, ">>> Advanced one character ... Current char is %c (code %d) \n", c, (int)c);
2966 fprintf(log_fd, ">>> Thislist has %d states available: ", thislist->n);
2967 for (i = 0; i< thislist->n; i++)
2968 fprintf(log_fd, "%d ", abs(thislist->t[i].state->id));
2969 fprintf(log_fd, "\n");
2970#endif
2971
Bram Moolenaar7fcff1f2013-05-20 21:49:13 +02002972#ifdef NFA_REGEXP_DEBUG_LOG
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002973 fprintf(debug, "\n-------------------\n");
2974#endif
Bram Moolenaar66e83d72013-05-21 14:03:00 +02002975 /*
2976 * If the state lists are empty we can stop.
2977 */
2978 if (thislist->n == 0 && neglist->n == 0)
2979 break;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002980
2981 /* compute nextlist */
2982 for (i = 0; i < thislist->n || neglist->n > 0; ++i)
2983 {
2984 if (neglist->n > 0)
2985 {
2986 t = &neglist->t[0];
Bram Moolenaar0fabe3f2013-05-21 12:34:17 +02002987 neglist->n--;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002988 i--;
2989 }
2990 else
2991 t = &thislist->t[i];
2992
Bram Moolenaar7fcff1f2013-05-20 21:49:13 +02002993#ifdef NFA_REGEXP_DEBUG_LOG
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02002994 nfa_set_code(t->state->c);
2995 fprintf(debug, "%s, ", code);
2996#endif
2997#ifdef ENABLE_LOG
2998 nfa_set_code(t->state->c);
2999 fprintf(log_fd, "(%d) %s, code %d ... \n", abs(t->state->id),
3000 code, (int)t->state->c);
3001#endif
3002
3003 /*
3004 * Handle the possible codes of the current state.
3005 * The most important is NFA_MATCH.
3006 */
3007 switch (t->state->c)
3008 {
3009 case NFA_MATCH:
3010 match = TRUE;
3011 *submatch = t->sub;
3012#ifdef ENABLE_LOG
3013 for (j = 0; j < 4; j++)
3014 if (REG_MULTI)
3015 fprintf(log_fd, "\n *** group %d, start: c=%d, l=%d, end: c=%d, l=%d",
3016 j,
3017 t->sub.startpos[j].col,
3018 (int)t->sub.startpos[j].lnum,
3019 t->sub.endpos[j].col,
3020 (int)t->sub.endpos[j].lnum);
3021 else
3022 fprintf(log_fd, "\n *** group %d, start: \"%s\", end: \"%s\"",
3023 j,
3024 (char *)t->sub.start[j],
3025 (char *)t->sub.end[j]);
3026 fprintf(log_fd, "\n");
3027#endif
Bram Moolenaar35b23862013-05-22 23:00:40 +02003028 /* Found the left-most longest match, do not look at any other
3029 * states at this position. */
3030 goto nextchar;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003031
3032 case NFA_END_INVISIBLE:
3033 /* This is only encountered after a NFA_START_INVISIBLE node.
3034 * They surround a zero-width group, used with "\@=" and "\&".
3035 * If we got here, it means that the current "invisible" group
3036 * finished successfully, so return control to the parent
3037 * nfa_regmatch(). Submatches are stored in *m, and used in
3038 * the parent call. */
3039 if (start->c == NFA_MOPEN + 0)
3040 addstate(thislist, t->state->out, &t->sub, 0, listid,
3041 &match);
3042 else
3043 {
3044 *m = t->sub;
3045 match = TRUE;
3046 }
3047 break;
3048
3049 case NFA_START_INVISIBLE:
3050 /* Save global variables, and call nfa_regmatch() to check if
3051 * the current concat matches at this position. The concat
3052 * ends with the node NFA_END_INVISIBLE */
3053 old_reginput = reginput;
3054 old_regline = regline;
3055 old_reglnum = reglnum;
3056 if (listids == NULL)
3057 {
3058 listids = (int *) lalloc(sizeof(int) * nstate, TRUE);
3059 if (listids == NULL)
3060 {
3061 EMSG(_("E878: (NFA) Could not allocate memory for branch traversal!"));
3062 return 0;
3063 }
3064 }
3065#ifdef ENABLE_LOG
3066 if (log_fd != stderr)
3067 fclose(log_fd);
3068 log_fd = NULL;
3069#endif
3070 /* Have to clear the listid field of the NFA nodes, so that
3071 * nfa_regmatch() and addstate() can run properly after
3072 * recursion. */
3073 nfa_save_listids(start, listids);
3074 nfa_set_null_listids(start);
3075 result = nfa_regmatch(t->state->out, submatch, m);
3076 nfa_set_neg_listids(start);
3077 nfa_restore_listids(start, listids);
3078
3079#ifdef ENABLE_LOG
3080 log_fd = fopen(LOG_NAME, "a");
3081 if (log_fd != NULL)
3082 {
3083 fprintf(log_fd, "****************************\n");
3084 fprintf(log_fd, "FINISHED RUNNING nfa_regmatch() recursively\n");
3085 fprintf(log_fd, "MATCH = %s\n", result == TRUE ? "OK" : "FALSE");
3086 fprintf(log_fd, "****************************\n");
3087 }
3088 else
3089 {
3090 EMSG(_("Could not open temporary log file for writing, displaying on stderr ... "));
3091 log_fd = stderr;
3092 }
3093#endif
3094 if (result == TRUE)
3095 {
3096 /* Restore position in input text */
3097 reginput = old_reginput;
3098 regline = old_regline;
3099 reglnum = old_reglnum;
3100 /* Copy submatch info from the recursive call */
3101 if (REG_MULTI)
3102 for (j = 1; j < NSUBEXP; j++)
3103 {
3104 t->sub.startpos[j] = m->startpos[j];
3105 t->sub.endpos[j] = m->endpos[j];
3106 }
3107 else
3108 for (j = 1; j < NSUBEXP; j++)
3109 {
3110 t->sub.start[j] = m->start[j];
3111 t->sub.end[j] = m->end[j];
3112 }
3113 /* t->state->out1 is the corresponding END_INVISIBLE node */
3114 addstate(thislist, t->state->out1->out, &t->sub, 0, listid,
3115 &match);
3116 }
3117 else
3118 {
3119 /* continue with next input char */
3120 reginput = old_reginput;
3121 }
3122 break;
3123
3124 case NFA_BOL:
3125 if (reginput == regline)
3126 addstate(thislist, t->state->out, &t->sub, 0, listid,
3127 &match);
3128 break;
3129
3130 case NFA_EOL:
3131 if (c == NUL)
3132 addstate(thislist, t->state->out, &t->sub, 0, listid,
3133 &match);
3134 break;
3135
3136 case NFA_BOW:
3137 {
3138 int bow = TRUE;
3139
3140 if (c == NUL)
3141 bow = FALSE;
3142#ifdef FEAT_MBYTE
3143 else if (has_mbyte)
3144 {
3145 int this_class;
3146
3147 /* Get class of current and previous char (if it exists). */
Bram Moolenaarf878bf02013-05-21 21:20:20 +02003148 this_class = mb_get_class_buf(reginput, reg_buf);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003149 if (this_class <= 1)
3150 bow = FALSE;
3151 else if (reg_prev_class() == this_class)
3152 bow = FALSE;
3153 }
3154#endif
Bram Moolenaarf878bf02013-05-21 21:20:20 +02003155 else if (!vim_iswordc_buf(c, reg_buf)
3156 || (reginput > regline
3157 && vim_iswordc_buf(reginput[-1], reg_buf)))
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003158 bow = FALSE;
3159 if (bow)
3160 addstate(thislist, t->state->out, &t->sub, 0, listid,
3161 &match);
3162 break;
3163 }
3164
3165 case NFA_EOW:
3166 {
3167 int eow = TRUE;
3168
3169 if (reginput == regline)
3170 eow = FALSE;
3171#ifdef FEAT_MBYTE
3172 else if (has_mbyte)
3173 {
3174 int this_class, prev_class;
3175
3176 /* Get class of current and previous char (if it exists). */
Bram Moolenaarf878bf02013-05-21 21:20:20 +02003177 this_class = mb_get_class_buf(reginput, reg_buf);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003178 prev_class = reg_prev_class();
3179 if (this_class == prev_class
3180 || prev_class == 0 || prev_class == 1)
3181 eow = FALSE;
3182 }
3183#endif
Bram Moolenaarf878bf02013-05-21 21:20:20 +02003184 else if (!vim_iswordc_buf(reginput[-1], reg_buf)
3185 || (reginput[0] != NUL && vim_iswordc_buf(c, reg_buf)))
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003186 eow = FALSE;
3187 if (eow)
3188 addstate(thislist, t->state->out, &t->sub, 0, listid,
3189 &match);
3190 break;
3191 }
3192
3193 case NFA_MULTIBYTE:
3194 case NFA_COMPOSING:
3195 switch (t->state->c)
3196 {
3197 case NFA_MULTIBYTE: endnode = NFA_END_MULTIBYTE; break;
3198 case NFA_COMPOSING: endnode = NFA_END_COMPOSING; break;
3199 default: endnode = 0;
3200 }
3201
3202 result = OK;
3203 sta = t->state->out;
3204 len = 1;
3205 while (sta->c != endnode && len <= n)
3206 {
3207 if (reginput[len-1] != sta->c)
3208 {
3209 result = OK - 1;
3210 break;
3211 }
3212 len++;
3213 sta = sta->out;
3214 }
3215
3216 /* if input char length doesn't match regexp char length */
3217 if (len -1 < n || sta->c != endnode)
3218 result = OK - 1;
3219 end = t->state->out1; /* NFA_END_MULTIBYTE or
3220 NFA_END_COMPOSING */
3221 /* If \Z was present, then ignore composing characters */
3222 if (regflags & RF_ICOMBINE)
3223 result = 1 ^ sta->negated;
3224 ADD_POS_NEG_STATE(end);
3225 break;
3226
3227 case NFA_NEWL:
3228 if (!reg_line_lbr && REG_MULTI
Bram Moolenaar35b23862013-05-22 23:00:40 +02003229 && c == NUL && reglnum <= reg_maxline)
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003230 {
Bram Moolenaar35b23862013-05-22 23:00:40 +02003231 go_to_nextline = TRUE;
3232 /* Pass -1 for the offset, which means taking the position
3233 * at the start of the next line. */
3234 addstate(nextlist, t->state->out, &t->sub, -1,
3235 listid + 1, &match);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003236 }
3237 break;
3238
3239 case NFA_CLASS_ALNUM:
3240 case NFA_CLASS_ALPHA:
3241 case NFA_CLASS_BLANK:
3242 case NFA_CLASS_CNTRL:
3243 case NFA_CLASS_DIGIT:
3244 case NFA_CLASS_GRAPH:
3245 case NFA_CLASS_LOWER:
3246 case NFA_CLASS_PRINT:
3247 case NFA_CLASS_PUNCT:
3248 case NFA_CLASS_SPACE:
3249 case NFA_CLASS_UPPER:
3250 case NFA_CLASS_XDIGIT:
3251 case NFA_CLASS_TAB:
3252 case NFA_CLASS_RETURN:
3253 case NFA_CLASS_BACKSPACE:
3254 case NFA_CLASS_ESCAPE:
3255 result = check_char_class(t->state->c, c);
3256 ADD_POS_NEG_STATE(t->state);
3257 break;
3258
3259 case NFA_END_NEG_RANGE:
3260 /* This follows a series of negated nodes, like:
3261 * CHAR(x), NFA_NOT, CHAR(y), NFA_NOT etc. */
3262 if (c > 0)
3263 addstate(nextlist, t->state->out, &t->sub, n, listid + 1,
3264 &match);
3265 break;
3266
3267 case NFA_ANY:
Bram Moolenaar35b23862013-05-22 23:00:40 +02003268 /* Any char except '\0', (end of input) does not match. */
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003269 if (c > 0)
3270 addstate(nextlist, t->state->out, &t->sub, n, listid + 1,
3271 &match);
3272 break;
3273
3274 /*
3275 * Character classes like \a for alpha, \d for digit etc.
3276 */
3277 case NFA_IDENT: /* \i */
3278 result = vim_isIDc(c);
3279 ADD_POS_NEG_STATE(t->state);
3280 break;
3281
3282 case NFA_SIDENT: /* \I */
3283 result = !VIM_ISDIGIT(c) && vim_isIDc(c);
3284 ADD_POS_NEG_STATE(t->state);
3285 break;
3286
3287 case NFA_KWORD: /* \k */
Bram Moolenaarf878bf02013-05-21 21:20:20 +02003288 result = vim_iswordp_buf(reginput, reg_buf);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003289 ADD_POS_NEG_STATE(t->state);
3290 break;
3291
3292 case NFA_SKWORD: /* \K */
Bram Moolenaarf878bf02013-05-21 21:20:20 +02003293 result = !VIM_ISDIGIT(c) && vim_iswordp_buf(reginput, reg_buf);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003294 ADD_POS_NEG_STATE(t->state);
3295 break;
3296
3297 case NFA_FNAME: /* \f */
3298 result = vim_isfilec(c);
3299 ADD_POS_NEG_STATE(t->state);
3300 break;
3301
3302 case NFA_SFNAME: /* \F */
3303 result = !VIM_ISDIGIT(c) && vim_isfilec(c);
3304 ADD_POS_NEG_STATE(t->state);
3305 break;
3306
3307 case NFA_PRINT: /* \p */
Bram Moolenaar08050492013-05-21 12:43:56 +02003308 result = ptr2cells(reginput) == 1;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003309 ADD_POS_NEG_STATE(t->state);
3310 break;
3311
3312 case NFA_SPRINT: /* \P */
Bram Moolenaar08050492013-05-21 12:43:56 +02003313 result = !VIM_ISDIGIT(c) && ptr2cells(reginput) == 1;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003314 ADD_POS_NEG_STATE(t->state);
3315 break;
3316
3317 case NFA_WHITE: /* \s */
3318 result = vim_iswhite(c);
3319 ADD_POS_NEG_STATE(t->state);
3320 break;
3321
3322 case NFA_NWHITE: /* \S */
3323 result = c != NUL && !vim_iswhite(c);
3324 ADD_POS_NEG_STATE(t->state);
3325 break;
3326
3327 case NFA_DIGIT: /* \d */
3328 result = ri_digit(c);
3329 ADD_POS_NEG_STATE(t->state);
3330 break;
3331
3332 case NFA_NDIGIT: /* \D */
3333 result = c != NUL && !ri_digit(c);
3334 ADD_POS_NEG_STATE(t->state);
3335 break;
3336
3337 case NFA_HEX: /* \x */
3338 result = ri_hex(c);
3339 ADD_POS_NEG_STATE(t->state);
3340 break;
3341
3342 case NFA_NHEX: /* \X */
3343 result = c != NUL && !ri_hex(c);
3344 ADD_POS_NEG_STATE(t->state);
3345 break;
3346
3347 case NFA_OCTAL: /* \o */
3348 result = ri_octal(c);
3349 ADD_POS_NEG_STATE(t->state);
3350 break;
3351
3352 case NFA_NOCTAL: /* \O */
3353 result = c != NUL && !ri_octal(c);
3354 ADD_POS_NEG_STATE(t->state);
3355 break;
3356
3357 case NFA_WORD: /* \w */
3358 result = ri_word(c);
3359 ADD_POS_NEG_STATE(t->state);
3360 break;
3361
3362 case NFA_NWORD: /* \W */
3363 result = c != NUL && !ri_word(c);
3364 ADD_POS_NEG_STATE(t->state);
3365 break;
3366
3367 case NFA_HEAD: /* \h */
3368 result = ri_head(c);
3369 ADD_POS_NEG_STATE(t->state);
3370 break;
3371
3372 case NFA_NHEAD: /* \H */
3373 result = c != NUL && !ri_head(c);
3374 ADD_POS_NEG_STATE(t->state);
3375 break;
3376
3377 case NFA_ALPHA: /* \a */
3378 result = ri_alpha(c);
3379 ADD_POS_NEG_STATE(t->state);
3380 break;
3381
3382 case NFA_NALPHA: /* \A */
3383 result = c != NUL && !ri_alpha(c);
3384 ADD_POS_NEG_STATE(t->state);
3385 break;
3386
3387 case NFA_LOWER: /* \l */
3388 result = ri_lower(c);
3389 ADD_POS_NEG_STATE(t->state);
3390 break;
3391
3392 case NFA_NLOWER: /* \L */
3393 result = c != NUL && !ri_lower(c);
3394 ADD_POS_NEG_STATE(t->state);
3395 break;
3396
3397 case NFA_UPPER: /* \u */
3398 result = ri_upper(c);
3399 ADD_POS_NEG_STATE(t->state);
3400 break;
3401
3402 case NFA_NUPPER: /* \U */
3403 result = c != NUL && !ri_upper(c);
3404 ADD_POS_NEG_STATE(t->state);
3405 break;
3406
Bram Moolenaar12e40142013-05-21 15:33:41 +02003407 case NFA_MOPEN + 0:
3408 case NFA_MOPEN + 1:
3409 case NFA_MOPEN + 2:
3410 case NFA_MOPEN + 3:
3411 case NFA_MOPEN + 4:
3412 case NFA_MOPEN + 5:
3413 case NFA_MOPEN + 6:
3414 case NFA_MOPEN + 7:
3415 case NFA_MOPEN + 8:
3416 case NFA_MOPEN + 9:
3417 /* handled below */
3418 break;
3419
3420 case NFA_SKIP_CHAR:
3421 case NFA_ZSTART:
3422 /* TODO: should not happen? */
3423 break;
3424
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003425 default: /* regular character */
Bram Moolenaar12e40142013-05-21 15:33:41 +02003426 /* TODO: put this in #ifdef later */
3427 if (t->state->c < -256)
3428 EMSGN("INTERNAL: Negative state char: %ld", t->state->c);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003429 result = (no_Magic(t->state->c) == c);
Bram Moolenaar12e40142013-05-21 15:33:41 +02003430
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003431 if (!result)
3432 result = ireg_ic == TRUE
3433 && MB_TOLOWER(t->state->c) == MB_TOLOWER(c);
3434 ADD_POS_NEG_STATE(t->state);
3435 break;
3436 }
3437
3438 } /* for (thislist = thislist; thislist->state; thislist++) */
3439
3440 /* The first found match is the leftmost one, but there may be a
3441 * longer one. Keep running the NFA, but don't start from the
3442 * beginning. Also, do not add the start state in recursive calls of
3443 * nfa_regmatch(), because recursive calls should only start in the
3444 * first position. */
3445 if (match == FALSE && start->c == NFA_MOPEN + 0)
3446 {
3447#ifdef ENABLE_LOG
3448 fprintf(log_fd, "(---) STARTSTATE\n");
3449#endif
3450 addstate(nextlist, start, m, n, listid + 1, &match);
3451 }
3452
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003453#ifdef ENABLE_LOG
3454 fprintf(log_fd, ">>> Thislist had %d states available: ", thislist->n);
3455 for (i = 0; i< thislist->n; i++)
3456 fprintf(log_fd, "%d ", abs(thislist->t[i].state->id));
3457 fprintf(log_fd, "\n");
3458#endif
3459
3460nextchar:
Bram Moolenaar35b23862013-05-22 23:00:40 +02003461 /* Advance to the next character, or advance to the next line, or
3462 * finish. */
3463 if (n != 0)
3464 reginput += n;
3465 else if (go_to_nextline)
3466 reg_nextline();
3467 else
3468 break;
3469 }
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003470
3471#ifdef ENABLE_LOG
3472 if (log_fd != stderr)
3473 fclose(log_fd);
3474 log_fd = NULL;
3475#endif
3476
3477theend:
3478 /* Free memory */
3479 vim_free(list[0].t);
3480 vim_free(list[1].t);
3481 vim_free(list[2].t);
3482 list[0].t = list[1].t = list[2].t = NULL;
3483 if (listids != NULL)
3484 vim_free(listids);
3485#undef ADD_POS_NEG_STATE
Bram Moolenaar7fcff1f2013-05-20 21:49:13 +02003486#ifdef NFA_REGEXP_DEBUG_LOG
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003487 fclose(debug);
3488#endif
3489
3490 return match;
3491}
3492
3493/*
3494 * Try match of "prog" with at regline["col"].
3495 * Returns 0 for failure, number of lines contained in the match otherwise.
3496 */
3497 static long
3498nfa_regtry(start, col)
3499 nfa_state_T *start;
3500 colnr_T col;
3501{
3502 int i;
3503 regsub_T sub, m;
3504#ifdef ENABLE_LOG
3505 FILE *f;
3506#endif
3507
3508 reginput = regline + col;
3509 need_clear_subexpr = TRUE;
3510
3511#ifdef ENABLE_LOG
3512 f = fopen(LOG_NAME, "a");
3513 if (f != NULL)
3514 {
3515 fprintf(f, "\n\n\n\n\n\n\t\t=======================================================\n");
3516 fprintf(f, " =======================================================\n");
3517#ifdef DEBUG
3518 fprintf(f, "\tRegexp is \"%s\"\n", nfa_regengine.expr);
3519#endif
3520 fprintf(f, "\tInput text is \"%s\" \n", reginput);
3521 fprintf(f, " =======================================================\n\n\n\n\n\n\n");
3522 nfa_print_state(f, start, 0);
3523 fprintf(f, "\n\n");
3524 fclose(f);
3525 }
3526 else
3527 EMSG(_("Could not open temporary log file for writing "));
3528#endif
3529
3530 if (REG_MULTI)
3531 {
3532 /* Use 0xff to set lnum to -1 */
3533 vim_memset(sub.startpos, 0xff, sizeof(lpos_T) * NSUBEXP);
3534 vim_memset(sub.endpos, 0xff, sizeof(lpos_T) * NSUBEXP);
3535 vim_memset(m.startpos, 0xff, sizeof(lpos_T) * NSUBEXP);
3536 vim_memset(m.endpos, 0xff, sizeof(lpos_T) * NSUBEXP);
3537 }
3538 else
3539 {
3540 vim_memset(sub.start, 0, sizeof(char_u *) * NSUBEXP);
3541 vim_memset(sub.end, 0, sizeof(char_u *) * NSUBEXP);
3542 vim_memset(m.start, 0, sizeof(char_u *) * NSUBEXP);
3543 vim_memset(m.end, 0, sizeof(char_u *) * NSUBEXP);
3544 }
3545
3546 if (nfa_regmatch(start, &sub, &m) == FALSE)
3547 return 0;
3548
3549 cleanup_subexpr();
3550 if (REG_MULTI)
3551 {
3552 for (i = 0; i < NSUBEXP; i++)
3553 {
3554 reg_startpos[i] = sub.startpos[i];
3555 reg_endpos[i] = sub.endpos[i];
3556 }
3557
3558 if (reg_startpos[0].lnum < 0)
3559 {
3560 reg_startpos[0].lnum = 0;
3561 reg_startpos[0].col = col;
3562 }
3563 if (reg_endpos[0].lnum < 0)
3564 {
3565 reg_endpos[0].lnum = reglnum;
3566 reg_endpos[0].col = (int)(reginput - regline);
3567 }
3568 else
3569 /* Use line number of "\ze". */
3570 reglnum = reg_endpos[0].lnum;
3571 }
3572 else
3573 {
3574 for (i = 0; i < NSUBEXP; i++)
3575 {
3576 reg_startp[i] = sub.start[i];
3577 reg_endp[i] = sub.end[i];
3578 }
3579
3580 if (reg_startp[0] == NULL)
3581 reg_startp[0] = regline + col;
3582 if (reg_endp[0] == NULL)
3583 reg_endp[0] = reginput;
3584 }
3585
3586 return 1 + reglnum;
3587}
3588
3589/*
3590 * Match a regexp against a string ("line" points to the string) or multiple
3591 * lines ("line" is NULL, use reg_getline()).
3592 *
3593 * Returns 0 for failure, number of lines contained in the match otherwise.
3594 */
3595 static long
3596nfa_regexec_both(line, col)
3597 char_u *line;
3598 colnr_T col; /* column to start looking for match */
3599{
3600 nfa_regprog_T *prog;
3601 long retval = 0L;
3602 int i;
3603
3604 if (REG_MULTI)
3605 {
3606 prog = (nfa_regprog_T *)reg_mmatch->regprog;
3607 line = reg_getline((linenr_T)0); /* relative to the cursor */
3608 reg_startpos = reg_mmatch->startpos;
3609 reg_endpos = reg_mmatch->endpos;
3610 }
3611 else
3612 {
3613 prog = (nfa_regprog_T *)reg_match->regprog;
3614 reg_startp = reg_match->startp;
3615 reg_endp = reg_match->endp;
3616 }
3617
3618 /* Be paranoid... */
3619 if (prog == NULL || line == NULL)
3620 {
3621 EMSG(_(e_null));
3622 goto theend;
3623 }
3624
3625 /* If the start column is past the maximum column: no need to try. */
3626 if (ireg_maxcol > 0 && col >= ireg_maxcol)
3627 goto theend;
3628
3629 /* If pattern contains "\c" or "\C": overrule value of ireg_ic */
3630 if (prog->regflags & RF_ICASE)
3631 ireg_ic = TRUE;
3632 else if (prog->regflags & RF_NOICASE)
3633 ireg_ic = FALSE;
3634
3635#ifdef FEAT_MBYTE
3636 /* If pattern contains "\Z" overrule value of ireg_icombine */
3637 if (prog->regflags & RF_ICOMBINE)
3638 ireg_icombine = TRUE;
3639#endif
3640
3641 regline = line;
3642 reglnum = 0; /* relative to line */
3643
3644 nstate = prog->nstate;
3645
3646 for (i = 0; i < nstate; ++i)
3647 {
3648 prog->state[i].id = i;
3649 prog->state[i].lastlist = 0;
3650 prog->state[i].visits = 0;
3651 prog->state[i].lastthread = NULL;
3652 }
3653
3654 retval = nfa_regtry(prog->start, col);
3655
3656theend:
3657 return retval;
3658}
3659
3660/*
3661 * Compile a regular expression into internal code for the NFA matcher.
3662 * Returns the program in allocated space. Returns NULL for an error.
3663 */
3664 static regprog_T *
3665nfa_regcomp(expr, re_flags)
3666 char_u *expr;
3667 int re_flags;
3668{
3669 nfa_regprog_T *prog;
Bram Moolenaarca12d7c2013-05-20 21:26:33 +02003670 size_t prog_size;
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003671 int *postfix;
3672
3673 if (expr == NULL)
3674 return NULL;
3675
3676#ifdef DEBUG
3677 nfa_regengine.expr = expr;
3678#endif
3679
3680 init_class_tab();
3681
3682 if (nfa_regcomp_start(expr, re_flags) == FAIL)
3683 return NULL;
3684
3685 /* Space for compiled regexp */
3686 prog_size = sizeof(nfa_regprog_T) + sizeof(nfa_state_T) * nstate_max;
3687 prog = (nfa_regprog_T *)lalloc(prog_size, TRUE);
3688 if (prog == NULL)
3689 goto fail;
3690 vim_memset(prog, 0, prog_size);
3691
3692 /* Build postfix form of the regexp. Needed to build the NFA
3693 * (and count its size) */
3694 postfix = re2post();
3695 if (postfix == NULL)
3696 goto fail; /* Cascaded (syntax?) error */
3697
3698 /*
3699 * In order to build the NFA, we parse the input regexp twice:
3700 * 1. first pass to count size (so we can allocate space)
3701 * 2. second to emit code
3702 */
3703#ifdef ENABLE_LOG
3704 {
3705 FILE *f = fopen(LOG_NAME, "a");
3706
3707 if (f != NULL)
3708 {
3709 fprintf(f, "\n*****************************\n\n\n\n\tCompiling regexp \"%s\" ... hold on !\n", expr);
3710 fclose(f);
3711 }
3712 }
3713#endif
3714
3715 /*
3716 * PASS 1
3717 * Count number of NFA states in "nstate". Do not build the NFA.
3718 */
3719 post2nfa(postfix, post_ptr, TRUE);
3720 state_ptr = prog->state;
3721
3722 /*
3723 * PASS 2
3724 * Build the NFA
3725 */
3726 prog->start = post2nfa(postfix, post_ptr, FALSE);
3727 if (prog->start == NULL)
3728 goto fail;
3729
3730 prog->regflags = regflags;
3731 prog->engine = &nfa_regengine;
3732 prog->nstate = nstate;
3733#ifdef ENABLE_LOG
3734 nfa_postfix_dump(expr, OK);
3735 nfa_dump(prog);
3736#endif
3737
3738out:
3739 vim_free(post_start);
3740 post_start = post_ptr = post_end = NULL;
3741 state_ptr = NULL;
3742 return (regprog_T *)prog;
3743
3744fail:
3745 vim_free(prog);
3746 prog = NULL;
3747#ifdef ENABLE_LOG
3748 nfa_postfix_dump(expr, FAIL);
3749#endif
3750#ifdef DEBUG
3751 nfa_regengine.expr = NULL;
3752#endif
3753 goto out;
3754}
3755
3756
3757/*
3758 * Match a regexp against a string.
3759 * "rmp->regprog" is a compiled regexp as returned by nfa_regcomp().
3760 * Uses curbuf for line count and 'iskeyword'.
3761 *
3762 * Return TRUE if there is a match, FALSE if not.
3763 */
3764 static int
3765nfa_regexec(rmp, line, col)
3766 regmatch_T *rmp;
3767 char_u *line; /* string to match against */
3768 colnr_T col; /* column to start looking for match */
3769{
3770 reg_match = rmp;
3771 reg_mmatch = NULL;
3772 reg_maxline = 0;
3773 reg_line_lbr = FALSE;
3774 reg_buf = curbuf;
3775 reg_win = NULL;
3776 ireg_ic = rmp->rm_ic;
3777#ifdef FEAT_MBYTE
3778 ireg_icombine = FALSE;
3779#endif
3780 ireg_maxcol = 0;
3781 return (nfa_regexec_both(line, col) != 0);
3782}
3783
3784#if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) \
3785 || defined(FIND_REPLACE_DIALOG) || defined(PROTO)
3786
3787static int nfa_regexec_nl __ARGS((regmatch_T *rmp, char_u *line, colnr_T col));
3788
3789/*
3790 * Like nfa_regexec(), but consider a "\n" in "line" to be a line break.
3791 */
3792 static int
3793nfa_regexec_nl(rmp, line, col)
3794 regmatch_T *rmp;
3795 char_u *line; /* string to match against */
3796 colnr_T col; /* column to start looking for match */
3797{
3798 reg_match = rmp;
3799 reg_mmatch = NULL;
3800 reg_maxline = 0;
3801 reg_line_lbr = TRUE;
3802 reg_buf = curbuf;
3803 reg_win = NULL;
3804 ireg_ic = rmp->rm_ic;
3805#ifdef FEAT_MBYTE
3806 ireg_icombine = FALSE;
3807#endif
3808 ireg_maxcol = 0;
3809 return (nfa_regexec_both(line, col) != 0);
3810}
3811#endif
3812
3813
3814/*
3815 * Match a regexp against multiple lines.
3816 * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
3817 * Uses curbuf for line count and 'iskeyword'.
3818 *
3819 * Return zero if there is no match. Return number of lines contained in the
3820 * match otherwise.
3821 *
3822 * Note: the body is the same as bt_regexec() except for nfa_regexec_both()
3823 *
3824 * ! Also NOTE : match may actually be in another line. e.g.:
3825 * when r.e. is \nc, cursor is at 'a' and the text buffer looks like
3826 *
3827 * +-------------------------+
3828 * |a |
3829 * |b |
3830 * |c |
3831 * | |
3832 * +-------------------------+
3833 *
3834 * then nfa_regexec_multi() returns 3. while the original
3835 * vim_regexec_multi() returns 0 and a second call at line 2 will return 2.
3836 *
3837 * FIXME if this behavior is not compatible.
3838 */
3839 static long
3840nfa_regexec_multi(rmp, win, buf, lnum, col, tm)
3841 regmmatch_T *rmp;
3842 win_T *win; /* window in which to search or NULL */
3843 buf_T *buf; /* buffer in which to search */
3844 linenr_T lnum; /* nr of line to start looking for match */
3845 colnr_T col; /* column to start looking for match */
3846 proftime_T *tm UNUSED; /* timeout limit or NULL */
3847{
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003848 reg_match = NULL;
3849 reg_mmatch = rmp;
3850 reg_buf = buf;
3851 reg_win = win;
3852 reg_firstlnum = lnum;
3853 reg_maxline = reg_buf->b_ml.ml_line_count - lnum;
3854 reg_line_lbr = FALSE;
3855 ireg_ic = rmp->rmm_ic;
3856#ifdef FEAT_MBYTE
3857 ireg_icombine = FALSE;
3858#endif
3859 ireg_maxcol = rmp->rmm_maxcol;
3860
Bram Moolenaarf878bf02013-05-21 21:20:20 +02003861 return nfa_regexec_both(NULL, col);
Bram Moolenaarfbc0d2e2013-05-19 19:40:29 +02003862}
3863
3864#ifdef DEBUG
3865# undef ENABLE_LOG
3866#endif