PageRenderTime 68ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/gnu/usr.bin/grep/dfa.c

https://bitbucket.org/freebsd/freebsd-head/
C | 3585 lines | 2661 code | 319 blank | 605 comment | 855 complexity | 088a4dfee3d594749795281104e9c75c MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, BSD-3-Clause, LGPL-2.0, LGPL-2.1, BSD-2-Clause, 0BSD, JSON, AGPL-1.0, GPL-2.0
  1. /* dfa.c - deterministic extended regexp routines for GNU
  2. Copyright 1988, 1998, 2000 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */
  14. /* Written June, 1988 by Mike Haertel
  15. Modified July, 1988 by Arthur David Olson to assist BMG speedups */
  16. /* $FreeBSD$ */
  17. #ifdef HAVE_CONFIG_H
  18. #include <config.h>
  19. #endif
  20. #include <assert.h>
  21. #include <ctype.h>
  22. #include <stdio.h>
  23. #include <sys/types.h>
  24. #ifdef STDC_HEADERS
  25. #include <stdlib.h>
  26. #else
  27. extern char *calloc(), *malloc(), *realloc();
  28. extern void free();
  29. #endif
  30. #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
  31. #include <string.h>
  32. #else
  33. #include <strings.h>
  34. #endif
  35. #if HAVE_SETLOCALE
  36. # include <locale.h>
  37. #endif
  38. #if defined HAVE_WCTYPE_H && defined HAVE_WCHAR_H && defined HAVE_MBRTOWC
  39. /* We can handle multibyte string. */
  40. # define MBS_SUPPORT
  41. #endif
  42. #ifdef MBS_SUPPORT
  43. # include <wchar.h>
  44. # include <wctype.h>
  45. #endif
  46. #ifndef DEBUG /* use the same approach as regex.c */
  47. #undef assert
  48. #define assert(e)
  49. #endif /* DEBUG */
  50. #ifndef isgraph
  51. #define isgraph(C) (isprint(C) && !isspace(C))
  52. #endif
  53. #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
  54. #define ISALPHA(C) isalpha(C)
  55. #define ISUPPER(C) isupper(C)
  56. #define ISLOWER(C) islower(C)
  57. #define ISDIGIT(C) isdigit(C)
  58. #define ISXDIGIT(C) isxdigit(C)
  59. #define ISSPACE(C) isspace(C)
  60. #define ISPUNCT(C) ispunct(C)
  61. #define ISALNUM(C) isalnum(C)
  62. #define ISPRINT(C) isprint(C)
  63. #define ISGRAPH(C) isgraph(C)
  64. #define ISCNTRL(C) iscntrl(C)
  65. #else
  66. #define ISALPHA(C) (isascii(C) && isalpha(C))
  67. #define ISUPPER(C) (isascii(C) && isupper(C))
  68. #define ISLOWER(C) (isascii(C) && islower(C))
  69. #define ISDIGIT(C) (isascii(C) && isdigit(C))
  70. #define ISXDIGIT(C) (isascii(C) && isxdigit(C))
  71. #define ISSPACE(C) (isascii(C) && isspace(C))
  72. #define ISPUNCT(C) (isascii(C) && ispunct(C))
  73. #define ISALNUM(C) (isascii(C) && isalnum(C))
  74. #define ISPRINT(C) (isascii(C) && isprint(C))
  75. #define ISGRAPH(C) (isascii(C) && isgraph(C))
  76. #define ISCNTRL(C) (isascii(C) && iscntrl(C))
  77. #endif
  78. /* ISASCIIDIGIT differs from ISDIGIT, as follows:
  79. - Its arg may be any int or unsigned int; it need not be an unsigned char.
  80. - It's guaranteed to evaluate its argument exactly once.
  81. - It's typically faster.
  82. Posix 1003.2-1992 section 2.5.2.1 page 50 lines 1556-1558 says that
  83. only '0' through '9' are digits. Prefer ISASCIIDIGIT to ISDIGIT unless
  84. it's important to use the locale's definition of `digit' even when the
  85. host does not conform to Posix. */
  86. #define ISASCIIDIGIT(c) ((unsigned) (c) - '0' <= 9)
  87. /* If we (don't) have I18N. */
  88. /* glibc defines _ */
  89. #ifndef _
  90. # ifdef HAVE_LIBINTL_H
  91. # include <libintl.h>
  92. # ifndef _
  93. # define _(Str) gettext (Str)
  94. # endif
  95. # else
  96. # define _(Str) (Str)
  97. # endif
  98. #endif
  99. #include "regex.h"
  100. #include "dfa.h"
  101. #include "hard-locale.h"
  102. /* HPUX, define those as macros in sys/param.h */
  103. #ifdef setbit
  104. # undef setbit
  105. #endif
  106. #ifdef clrbit
  107. # undef clrbit
  108. #endif
  109. static void dfamust PARAMS ((struct dfa *dfa));
  110. static void regexp PARAMS ((int toplevel));
  111. static ptr_t
  112. xcalloc (size_t n, size_t s)
  113. {
  114. ptr_t r = calloc(n, s);
  115. if (!r)
  116. dfaerror(_("Memory exhausted"));
  117. return r;
  118. }
  119. static ptr_t
  120. xmalloc (size_t n)
  121. {
  122. ptr_t r = malloc(n);
  123. assert(n != 0);
  124. if (!r)
  125. dfaerror(_("Memory exhausted"));
  126. return r;
  127. }
  128. static ptr_t
  129. xrealloc (ptr_t p, size_t n)
  130. {
  131. ptr_t r = realloc(p, n);
  132. assert(n != 0);
  133. if (!r)
  134. dfaerror(_("Memory exhausted"));
  135. return r;
  136. }
  137. #define CALLOC(p, t, n) ((p) = (t *) xcalloc((size_t)(n), sizeof (t)))
  138. #define MALLOC(p, t, n) ((p) = (t *) xmalloc((n) * sizeof (t)))
  139. #define REALLOC(p, t, n) ((p) = (t *) xrealloc((ptr_t) (p), (n) * sizeof (t)))
  140. /* Reallocate an array of type t if nalloc is too small for index. */
  141. #define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
  142. if ((index) >= (nalloc)) \
  143. { \
  144. do \
  145. (nalloc) *= 2; \
  146. while ((index) >= (nalloc)); \
  147. REALLOC(p, t, nalloc); \
  148. }
  149. #ifdef DEBUG
  150. static void
  151. prtok (token t)
  152. {
  153. char const *s;
  154. if (t < 0)
  155. fprintf(stderr, "END");
  156. else if (t < NOTCHAR)
  157. fprintf(stderr, "%c", t);
  158. else
  159. {
  160. switch (t)
  161. {
  162. case EMPTY: s = "EMPTY"; break;
  163. case BACKREF: s = "BACKREF"; break;
  164. case BEGLINE: s = "BEGLINE"; break;
  165. case ENDLINE: s = "ENDLINE"; break;
  166. case BEGWORD: s = "BEGWORD"; break;
  167. case ENDWORD: s = "ENDWORD"; break;
  168. case LIMWORD: s = "LIMWORD"; break;
  169. case NOTLIMWORD: s = "NOTLIMWORD"; break;
  170. case QMARK: s = "QMARK"; break;
  171. case STAR: s = "STAR"; break;
  172. case PLUS: s = "PLUS"; break;
  173. case CAT: s = "CAT"; break;
  174. case OR: s = "OR"; break;
  175. case ORTOP: s = "ORTOP"; break;
  176. case LPAREN: s = "LPAREN"; break;
  177. case RPAREN: s = "RPAREN"; break;
  178. case CRANGE: s = "CRANGE"; break;
  179. #ifdef MBS_SUPPORT
  180. case ANYCHAR: s = "ANYCHAR"; break;
  181. case MBCSET: s = "MBCSET"; break;
  182. #endif /* MBS_SUPPORT */
  183. default: s = "CSET"; break;
  184. }
  185. fprintf(stderr, "%s", s);
  186. }
  187. }
  188. #endif /* DEBUG */
  189. /* Stuff pertaining to charclasses. */
  190. static int
  191. tstbit (unsigned b, charclass c)
  192. {
  193. return c[b / INTBITS] & 1 << b % INTBITS;
  194. }
  195. static void
  196. setbit (unsigned b, charclass c)
  197. {
  198. c[b / INTBITS] |= 1 << b % INTBITS;
  199. }
  200. static void
  201. clrbit (unsigned b, charclass c)
  202. {
  203. c[b / INTBITS] &= ~(1 << b % INTBITS);
  204. }
  205. static void
  206. copyset (charclass src, charclass dst)
  207. {
  208. memcpy (dst, src, sizeof (charclass));
  209. }
  210. static void
  211. zeroset (charclass s)
  212. {
  213. memset (s, 0, sizeof (charclass));
  214. }
  215. static void
  216. notset (charclass s)
  217. {
  218. int i;
  219. for (i = 0; i < CHARCLASS_INTS; ++i)
  220. s[i] = ~s[i];
  221. }
  222. static int
  223. equal (charclass s1, charclass s2)
  224. {
  225. return memcmp (s1, s2, sizeof (charclass)) == 0;
  226. }
  227. /* A pointer to the current dfa is kept here during parsing. */
  228. static struct dfa *dfa;
  229. /* Find the index of charclass s in dfa->charclasses, or allocate a new charclass. */
  230. static int
  231. charclass_index (charclass s)
  232. {
  233. int i;
  234. for (i = 0; i < dfa->cindex; ++i)
  235. if (equal(s, dfa->charclasses[i]))
  236. return i;
  237. REALLOC_IF_NECESSARY(dfa->charclasses, charclass, dfa->calloc, dfa->cindex);
  238. ++dfa->cindex;
  239. copyset(s, dfa->charclasses[i]);
  240. return i;
  241. }
  242. /* Syntax bits controlling the behavior of the lexical analyzer. */
  243. static reg_syntax_t syntax_bits, syntax_bits_set;
  244. /* Flag for case-folding letters into sets. */
  245. static int case_fold;
  246. /* End-of-line byte in data. */
  247. static unsigned char eolbyte;
  248. /* Entry point to set syntax options. */
  249. void
  250. dfasyntax (reg_syntax_t bits, int fold, unsigned char eol)
  251. {
  252. syntax_bits_set = 1;
  253. syntax_bits = bits;
  254. case_fold = fold;
  255. eolbyte = eol;
  256. }
  257. /* Like setbit, but if case is folded, set both cases of a letter. */
  258. static void
  259. setbit_case_fold (unsigned b, charclass c)
  260. {
  261. setbit (b, c);
  262. if (case_fold)
  263. {
  264. if (ISUPPER (b))
  265. setbit (tolower (b), c);
  266. else if (ISLOWER (b))
  267. setbit (toupper (b), c);
  268. }
  269. }
  270. /* Lexical analyzer. All the dross that deals with the obnoxious
  271. GNU Regex syntax bits is located here. The poor, suffering
  272. reader is referred to the GNU Regex documentation for the
  273. meaning of the @#%!@#%^!@ syntax bits. */
  274. static char const *lexstart; /* Pointer to beginning of input string. */
  275. static char const *lexptr; /* Pointer to next input character. */
  276. static int lexleft; /* Number of characters remaining. */
  277. static token lasttok; /* Previous token returned; initially END. */
  278. static int laststart; /* True if we're separated from beginning or (, |
  279. only by zero-width characters. */
  280. static int parens; /* Count of outstanding left parens. */
  281. static int minrep, maxrep; /* Repeat counts for {m,n}. */
  282. static int hard_LC_COLLATE; /* Nonzero if LC_COLLATE is hard. */
  283. #ifdef MBS_SUPPORT
  284. /* These variables are used only if (MB_CUR_MAX > 1). */
  285. static mbstate_t mbs; /* Mbstate for mbrlen(). */
  286. static int cur_mb_len; /* Byte length of the current scanning
  287. multibyte character. */
  288. static int cur_mb_index; /* Byte index of the current scanning multibyte
  289. character.
  290. singlebyte character : cur_mb_index = 0
  291. multibyte character
  292. 1st byte : cur_mb_index = 1
  293. 2nd byte : cur_mb_index = 2
  294. ...
  295. nth byte : cur_mb_index = n */
  296. static unsigned char *mblen_buf;/* Correspond to the input buffer in dfaexec().
  297. Each element store the amount of remain
  298. byte of corresponding multibyte character
  299. in the input string. A element's value
  300. is 0 if corresponding character is a
  301. singlebyte chracter.
  302. e.g. input : 'a', <mb(0)>, <mb(1)>, <mb(2)>
  303. mblen_buf : 0, 3, 2, 1
  304. */
  305. static wchar_t *inputwcs; /* Wide character representation of input
  306. string in dfaexec().
  307. The length of this array is same as
  308. the length of input string(char array).
  309. inputstring[i] is a single-byte char,
  310. or 1st byte of a multibyte char.
  311. And inputwcs[i] is the codepoint. */
  312. static unsigned char const *buf_begin;/* refference to begin in dfaexec(). */
  313. static unsigned char const *buf_end; /* refference to end in dfaexec(). */
  314. #endif /* MBS_SUPPORT */
  315. #ifdef MBS_SUPPORT
  316. /* This function update cur_mb_len, and cur_mb_index.
  317. p points current lexptr, len is the remaining buffer length. */
  318. static void
  319. update_mb_len_index (unsigned char const *p, int len)
  320. {
  321. /* If last character is a part of a multibyte character,
  322. we update cur_mb_index. */
  323. if (cur_mb_index)
  324. cur_mb_index = (cur_mb_index >= cur_mb_len)? 0
  325. : cur_mb_index + 1;
  326. /* If last character is a single byte character, or the
  327. last portion of a multibyte character, we check whether
  328. next character is a multibyte character or not. */
  329. if (! cur_mb_index)
  330. {
  331. cur_mb_len = mbrlen(p, len, &mbs);
  332. if (cur_mb_len > 1)
  333. /* It is a multibyte character.
  334. cur_mb_len was already set by mbrlen(). */
  335. cur_mb_index = 1;
  336. else if (cur_mb_len < 1)
  337. /* Invalid sequence. We treat it as a singlebyte character.
  338. cur_mb_index is aleady 0. */
  339. cur_mb_len = 1;
  340. /* Otherwise, cur_mb_len == 1, it is a singlebyte character.
  341. cur_mb_index is aleady 0. */
  342. }
  343. }
  344. #endif /* MBS_SUPPORT */
  345. #ifdef MBS_SUPPORT
  346. /* Note that characters become unsigned here. */
  347. # define FETCH(c, eoferr) \
  348. { \
  349. if (! lexleft) \
  350. { \
  351. if (eoferr != 0) \
  352. dfaerror (eoferr); \
  353. else \
  354. return lasttok = END; \
  355. } \
  356. if (MB_CUR_MAX > 1) \
  357. update_mb_len_index(lexptr, lexleft); \
  358. (c) = (unsigned char) *lexptr++; \
  359. --lexleft; \
  360. }
  361. /* This function fetch a wide character, and update cur_mb_len,
  362. used only if the current locale is a multibyte environment. */
  363. static wint_t
  364. fetch_wc (char const *eoferr)
  365. {
  366. wchar_t wc;
  367. if (! lexleft)
  368. {
  369. if (eoferr != 0)
  370. dfaerror (eoferr);
  371. else
  372. return WEOF;
  373. }
  374. cur_mb_len = mbrtowc(&wc, lexptr, lexleft, &mbs);
  375. if (cur_mb_len <= 0)
  376. {
  377. cur_mb_len = 1;
  378. wc = *lexptr;
  379. }
  380. lexptr += cur_mb_len;
  381. lexleft -= cur_mb_len;
  382. return wc;
  383. }
  384. #else
  385. /* Note that characters become unsigned here. */
  386. # define FETCH(c, eoferr) \
  387. { \
  388. if (! lexleft) \
  389. { \
  390. if (eoferr != 0) \
  391. dfaerror (eoferr); \
  392. else \
  393. return lasttok = END; \
  394. } \
  395. (c) = (unsigned char) *lexptr++; \
  396. --lexleft; \
  397. }
  398. #endif /* MBS_SUPPORT */
  399. #ifdef MBS_SUPPORT
  400. /* Multibyte character handling sub-routin for lex.
  401. This function parse a bracket expression and build a struct
  402. mb_char_classes. */
  403. static void
  404. parse_bracket_exp_mb ()
  405. {
  406. wint_t wc, wc1, wc2;
  407. /* Work area to build a mb_char_classes. */
  408. struct mb_char_classes *work_mbc;
  409. int chars_al, range_sts_al, range_ends_al, ch_classes_al,
  410. equivs_al, coll_elems_al;
  411. REALLOC_IF_NECESSARY(dfa->mbcsets, struct mb_char_classes,
  412. dfa->mbcsets_alloc, dfa->nmbcsets + 1);
  413. /* dfa->multibyte_prop[] hold the index of dfa->mbcsets.
  414. We will update dfa->multibyte_prop in addtok(), because we can't
  415. decide the index in dfa->tokens[]. */
  416. /* Initialize work are */
  417. work_mbc = &(dfa->mbcsets[dfa->nmbcsets++]);
  418. chars_al = 1;
  419. range_sts_al = range_ends_al = 0;
  420. ch_classes_al = equivs_al = coll_elems_al = 0;
  421. MALLOC(work_mbc->chars, wchar_t, chars_al);
  422. work_mbc->nchars = work_mbc->nranges = work_mbc->nch_classes = 0;
  423. work_mbc->nequivs = work_mbc->ncoll_elems = 0;
  424. work_mbc->chars = work_mbc->ch_classes = NULL;
  425. work_mbc->range_sts = work_mbc->range_ends = NULL;
  426. work_mbc->equivs = work_mbc->coll_elems = NULL;
  427. wc = fetch_wc(_("Unbalanced ["));
  428. if (wc == L'^')
  429. {
  430. wc = fetch_wc(_("Unbalanced ["));
  431. work_mbc->invert = 1;
  432. }
  433. else
  434. work_mbc->invert = 0;
  435. do
  436. {
  437. wc1 = WEOF; /* mark wc1 is not initialized". */
  438. /* Note that if we're looking at some other [:...:] construct,
  439. we just treat it as a bunch of ordinary characters. We can do
  440. this because we assume regex has checked for syntax errors before
  441. dfa is ever called. */
  442. if (wc == L'[' && (syntax_bits & RE_CHAR_CLASSES))
  443. {
  444. #define BRACKET_BUFFER_SIZE 128
  445. char str[BRACKET_BUFFER_SIZE];
  446. wc1 = wc;
  447. wc = fetch_wc(_("Unbalanced ["));
  448. /* If pattern contains `[[:', `[[.', or `[[='. */
  449. if (cur_mb_len == 1 && (wc == L':' || wc == L'.' || wc == L'='))
  450. {
  451. unsigned char c;
  452. unsigned char delim = (unsigned char)wc;
  453. int len = 0;
  454. for (;;)
  455. {
  456. if (! lexleft)
  457. dfaerror (_("Unbalanced ["));
  458. c = (unsigned char) *lexptr++;
  459. --lexleft;
  460. if ((c == delim && *lexptr == ']') || lexleft == 0)
  461. break;
  462. if (len < BRACKET_BUFFER_SIZE)
  463. str[len++] = c;
  464. else
  465. /* This is in any case an invalid class name. */
  466. str[0] = '\0';
  467. }
  468. str[len] = '\0';
  469. if (lexleft == 0)
  470. {
  471. REALLOC_IF_NECESSARY(work_mbc->chars, wchar_t, chars_al,
  472. work_mbc->nchars + 2);
  473. work_mbc->chars[work_mbc->nchars++] = L'[';
  474. work_mbc->chars[work_mbc->nchars++] = delim;
  475. break;
  476. }
  477. if (--lexleft, *lexptr++ != ']')
  478. dfaerror (_("Unbalanced ["));
  479. if (delim == ':')
  480. /* build character class. */
  481. {
  482. wctype_t wt;
  483. /* Query the character class as wctype_t. */
  484. wt = wctype (str);
  485. if (ch_classes_al == 0)
  486. MALLOC(work_mbc->ch_classes, wchar_t, ++ch_classes_al);
  487. REALLOC_IF_NECESSARY(work_mbc->ch_classes, wctype_t,
  488. ch_classes_al,
  489. work_mbc->nch_classes + 1);
  490. work_mbc->ch_classes[work_mbc->nch_classes++] = wt;
  491. }
  492. else if (delim == '=' || delim == '.')
  493. {
  494. char *elem;
  495. MALLOC(elem, char, len + 1);
  496. strncpy(elem, str, len + 1);
  497. if (delim == '=')
  498. /* build equivalent class. */
  499. {
  500. if (equivs_al == 0)
  501. MALLOC(work_mbc->equivs, char*, ++equivs_al);
  502. REALLOC_IF_NECESSARY(work_mbc->equivs, char*,
  503. equivs_al,
  504. work_mbc->nequivs + 1);
  505. work_mbc->equivs[work_mbc->nequivs++] = elem;
  506. }
  507. if (delim == '.')
  508. /* build collating element. */
  509. {
  510. if (coll_elems_al == 0)
  511. MALLOC(work_mbc->coll_elems, char*, ++coll_elems_al);
  512. REALLOC_IF_NECESSARY(work_mbc->coll_elems, char*,
  513. coll_elems_al,
  514. work_mbc->ncoll_elems + 1);
  515. work_mbc->coll_elems[work_mbc->ncoll_elems++] = elem;
  516. }
  517. }
  518. wc1 = wc = WEOF;
  519. }
  520. else
  521. /* We treat '[' as a normal character here. */
  522. {
  523. wc2 = wc1; wc1 = wc; wc = wc2; /* swap */
  524. }
  525. }
  526. else
  527. {
  528. if (wc == L'\\' && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  529. wc = fetch_wc(("Unbalanced ["));
  530. }
  531. if (wc1 == WEOF)
  532. wc1 = fetch_wc(_("Unbalanced ["));
  533. if (wc1 == L'-')
  534. /* build range characters. */
  535. {
  536. wc2 = fetch_wc(_("Unbalanced ["));
  537. if (wc2 == L']')
  538. {
  539. /* In the case [x-], the - is an ordinary hyphen,
  540. which is left in c1, the lookahead character. */
  541. lexptr -= cur_mb_len;
  542. lexleft += cur_mb_len;
  543. wc2 = wc;
  544. }
  545. else
  546. {
  547. if (wc2 == L'\\'
  548. && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  549. wc2 = fetch_wc(_("Unbalanced ["));
  550. wc1 = fetch_wc(_("Unbalanced ["));
  551. }
  552. if (range_sts_al == 0)
  553. {
  554. MALLOC(work_mbc->range_sts, wchar_t, ++range_sts_al);
  555. MALLOC(work_mbc->range_ends, wchar_t, ++range_ends_al);
  556. }
  557. REALLOC_IF_NECESSARY(work_mbc->range_sts, wchar_t,
  558. range_sts_al, work_mbc->nranges + 1);
  559. work_mbc->range_sts[work_mbc->nranges] = (wchar_t)wc;
  560. REALLOC_IF_NECESSARY(work_mbc->range_ends, wchar_t,
  561. range_ends_al, work_mbc->nranges + 1);
  562. work_mbc->range_ends[work_mbc->nranges++] = (wchar_t)wc2;
  563. }
  564. else if (wc != WEOF)
  565. /* build normal characters. */
  566. {
  567. REALLOC_IF_NECESSARY(work_mbc->chars, wchar_t, chars_al,
  568. work_mbc->nchars + 1);
  569. work_mbc->chars[work_mbc->nchars++] = (wchar_t)wc;
  570. }
  571. }
  572. while ((wc = wc1) != L']');
  573. }
  574. #endif /* MBS_SUPPORT */
  575. #ifdef __STDC__
  576. #define FUNC(F, P) static int F(int c) { return P(c); }
  577. #else
  578. #define FUNC(F, P) static int F(c) int c; { return P(c); }
  579. #endif
  580. FUNC(is_alpha, ISALPHA)
  581. FUNC(is_upper, ISUPPER)
  582. FUNC(is_lower, ISLOWER)
  583. FUNC(is_digit, ISDIGIT)
  584. FUNC(is_xdigit, ISXDIGIT)
  585. FUNC(is_space, ISSPACE)
  586. FUNC(is_punct, ISPUNCT)
  587. FUNC(is_alnum, ISALNUM)
  588. FUNC(is_print, ISPRINT)
  589. FUNC(is_graph, ISGRAPH)
  590. FUNC(is_cntrl, ISCNTRL)
  591. static int
  592. is_blank (int c)
  593. {
  594. return (c == ' ' || c == '\t');
  595. }
  596. /* The following list maps the names of the Posix named character classes
  597. to predicate functions that determine whether a given character is in
  598. the class. The leading [ has already been eaten by the lexical analyzer. */
  599. static struct {
  600. const char *name;
  601. int (*pred) PARAMS ((int));
  602. } const prednames[] = {
  603. { ":alpha:]", is_alpha },
  604. { ":upper:]", is_upper },
  605. { ":lower:]", is_lower },
  606. { ":digit:]", is_digit },
  607. { ":xdigit:]", is_xdigit },
  608. { ":space:]", is_space },
  609. { ":punct:]", is_punct },
  610. { ":alnum:]", is_alnum },
  611. { ":print:]", is_print },
  612. { ":graph:]", is_graph },
  613. { ":cntrl:]", is_cntrl },
  614. { ":blank:]", is_blank },
  615. { 0 }
  616. };
  617. /* Return non-zero if C is a `word-constituent' byte; zero otherwise. */
  618. #define IS_WORD_CONSTITUENT(C) (ISALNUM(C) || (C) == '_')
  619. static int
  620. looking_at (char const *s)
  621. {
  622. size_t len;
  623. len = strlen(s);
  624. if (lexleft < len)
  625. return 0;
  626. return strncmp(s, lexptr, len) == 0;
  627. }
  628. static token
  629. lex (void)
  630. {
  631. unsigned c, c1, c2;
  632. int backslash = 0, invert;
  633. charclass ccl;
  634. int i;
  635. /* Basic plan: We fetch a character. If it's a backslash,
  636. we set the backslash flag and go through the loop again.
  637. On the plus side, this avoids having a duplicate of the
  638. main switch inside the backslash case. On the minus side,
  639. it means that just about every case begins with
  640. "if (backslash) ...". */
  641. for (i = 0; i < 2; ++i)
  642. {
  643. FETCH(c, 0);
  644. #ifdef MBS_SUPPORT
  645. if (MB_CUR_MAX > 1 && cur_mb_index)
  646. /* If this is a part of a multi-byte character, we must treat
  647. this byte data as a normal character.
  648. e.g. In case of SJIS encoding, some character contains '\',
  649. but they must not be backslash. */
  650. goto normal_char;
  651. #endif /* MBS_SUPPORT */
  652. switch (c)
  653. {
  654. case '\\':
  655. if (backslash)
  656. goto normal_char;
  657. if (lexleft == 0)
  658. dfaerror(_("Unfinished \\ escape"));
  659. backslash = 1;
  660. break;
  661. case '^':
  662. if (backslash)
  663. goto normal_char;
  664. if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
  665. || lasttok == END
  666. || lasttok == LPAREN
  667. || lasttok == OR)
  668. return lasttok = BEGLINE;
  669. goto normal_char;
  670. case '$':
  671. if (backslash)
  672. goto normal_char;
  673. if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
  674. || lexleft == 0
  675. || (syntax_bits & RE_NO_BK_PARENS
  676. ? lexleft > 0 && *lexptr == ')'
  677. : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == ')')
  678. || (syntax_bits & RE_NO_BK_VBAR
  679. ? lexleft > 0 && *lexptr == '|'
  680. : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == '|')
  681. || ((syntax_bits & RE_NEWLINE_ALT)
  682. && lexleft > 0 && *lexptr == '\n'))
  683. return lasttok = ENDLINE;
  684. goto normal_char;
  685. case '1':
  686. case '2':
  687. case '3':
  688. case '4':
  689. case '5':
  690. case '6':
  691. case '7':
  692. case '8':
  693. case '9':
  694. if (backslash && !(syntax_bits & RE_NO_BK_REFS))
  695. {
  696. laststart = 0;
  697. return lasttok = BACKREF;
  698. }
  699. goto normal_char;
  700. case '`':
  701. if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  702. return lasttok = BEGLINE; /* FIXME: should be beginning of string */
  703. goto normal_char;
  704. case '\'':
  705. if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  706. return lasttok = ENDLINE; /* FIXME: should be end of string */
  707. goto normal_char;
  708. case '<':
  709. if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  710. return lasttok = BEGWORD;
  711. goto normal_char;
  712. case '>':
  713. if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  714. return lasttok = ENDWORD;
  715. goto normal_char;
  716. case 'b':
  717. if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  718. return lasttok = LIMWORD;
  719. goto normal_char;
  720. case 'B':
  721. if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  722. return lasttok = NOTLIMWORD;
  723. goto normal_char;
  724. case '?':
  725. if (syntax_bits & RE_LIMITED_OPS)
  726. goto normal_char;
  727. if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
  728. goto normal_char;
  729. if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  730. goto normal_char;
  731. return lasttok = QMARK;
  732. case '*':
  733. if (backslash)
  734. goto normal_char;
  735. if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  736. goto normal_char;
  737. return lasttok = STAR;
  738. case '+':
  739. if (syntax_bits & RE_LIMITED_OPS)
  740. goto normal_char;
  741. if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
  742. goto normal_char;
  743. if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  744. goto normal_char;
  745. return lasttok = PLUS;
  746. case '{':
  747. if (!(syntax_bits & RE_INTERVALS))
  748. goto normal_char;
  749. if (backslash != ((syntax_bits & RE_NO_BK_BRACES) == 0))
  750. goto normal_char;
  751. if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  752. goto normal_char;
  753. if (syntax_bits & RE_NO_BK_BRACES)
  754. {
  755. /* Scan ahead for a valid interval; if it's not valid,
  756. treat it as a literal '{'. */
  757. int lo = -1, hi = -1;
  758. char const *p = lexptr;
  759. char const *lim = p + lexleft;
  760. for (; p != lim && ISASCIIDIGIT (*p); p++)
  761. lo = (lo < 0 ? 0 : lo * 10) + *p - '0';
  762. if (p != lim && *p == ',')
  763. while (++p != lim && ISASCIIDIGIT (*p))
  764. hi = (hi < 0 ? 0 : hi * 10) + *p - '0';
  765. else
  766. hi = lo;
  767. if (p == lim || *p != '}'
  768. || lo < 0 || RE_DUP_MAX < hi || (0 <= hi && hi < lo))
  769. goto normal_char;
  770. }
  771. minrep = 0;
  772. /* Cases:
  773. {M} - exact count
  774. {M,} - minimum count, maximum is infinity
  775. {M,N} - M through N */
  776. FETCH(c, _("unfinished repeat count"));
  777. if (ISASCIIDIGIT (c))
  778. {
  779. minrep = c - '0';
  780. for (;;)
  781. {
  782. FETCH(c, _("unfinished repeat count"));
  783. if (! ISASCIIDIGIT (c))
  784. break;
  785. minrep = 10 * minrep + c - '0';
  786. }
  787. }
  788. else
  789. dfaerror(_("malformed repeat count"));
  790. if (c == ',')
  791. {
  792. FETCH (c, _("unfinished repeat count"));
  793. if (! ISASCIIDIGIT (c))
  794. maxrep = -1;
  795. else
  796. {
  797. maxrep = c - '0';
  798. for (;;)
  799. {
  800. FETCH (c, _("unfinished repeat count"));
  801. if (! ISASCIIDIGIT (c))
  802. break;
  803. maxrep = 10 * maxrep + c - '0';
  804. }
  805. if (0 <= maxrep && maxrep < minrep)
  806. dfaerror (_("malformed repeat count"));
  807. }
  808. }
  809. else
  810. maxrep = minrep;
  811. if (!(syntax_bits & RE_NO_BK_BRACES))
  812. {
  813. if (c != '\\')
  814. dfaerror(_("malformed repeat count"));
  815. FETCH(c, _("unfinished repeat count"));
  816. }
  817. if (c != '}')
  818. dfaerror(_("malformed repeat count"));
  819. laststart = 0;
  820. return lasttok = REPMN;
  821. case '|':
  822. if (syntax_bits & RE_LIMITED_OPS)
  823. goto normal_char;
  824. if (backslash != ((syntax_bits & RE_NO_BK_VBAR) == 0))
  825. goto normal_char;
  826. laststart = 1;
  827. return lasttok = OR;
  828. case '\n':
  829. if (syntax_bits & RE_LIMITED_OPS
  830. || backslash
  831. || !(syntax_bits & RE_NEWLINE_ALT))
  832. goto normal_char;
  833. laststart = 1;
  834. return lasttok = OR;
  835. case '(':
  836. if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
  837. goto normal_char;
  838. ++parens;
  839. laststart = 1;
  840. return lasttok = LPAREN;
  841. case ')':
  842. if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
  843. goto normal_char;
  844. if (parens == 0 && syntax_bits & RE_UNMATCHED_RIGHT_PAREN_ORD)
  845. goto normal_char;
  846. --parens;
  847. laststart = 0;
  848. return lasttok = RPAREN;
  849. case '.':
  850. if (backslash)
  851. goto normal_char;
  852. #ifdef MBS_SUPPORT
  853. if (MB_CUR_MAX > 1)
  854. {
  855. /* In multibyte environment period must match with a single
  856. character not a byte. So we use ANYCHAR. */
  857. laststart = 0;
  858. return lasttok = ANYCHAR;
  859. }
  860. #endif /* MBS_SUPPORT */
  861. zeroset(ccl);
  862. notset(ccl);
  863. if (!(syntax_bits & RE_DOT_NEWLINE))
  864. clrbit(eolbyte, ccl);
  865. if (syntax_bits & RE_DOT_NOT_NULL)
  866. clrbit('\0', ccl);
  867. laststart = 0;
  868. return lasttok = CSET + charclass_index(ccl);
  869. case 'w':
  870. case 'W':
  871. if (!backslash || (syntax_bits & RE_NO_GNU_OPS))
  872. goto normal_char;
  873. zeroset(ccl);
  874. for (c2 = 0; c2 < NOTCHAR; ++c2)
  875. if (IS_WORD_CONSTITUENT(c2))
  876. setbit(c2, ccl);
  877. if (c == 'W')
  878. notset(ccl);
  879. laststart = 0;
  880. return lasttok = CSET + charclass_index(ccl);
  881. case '[':
  882. if (backslash)
  883. goto normal_char;
  884. laststart = 0;
  885. #ifdef MBS_SUPPORT
  886. if (MB_CUR_MAX > 1)
  887. {
  888. /* In multibyte environment a bracket expression may contain
  889. multibyte characters, which must be treated as characters
  890. (not bytes). So we parse it by parse_bracket_exp_mb(). */
  891. parse_bracket_exp_mb();
  892. return lasttok = MBCSET;
  893. }
  894. #endif
  895. zeroset(ccl);
  896. FETCH(c, _("Unbalanced ["));
  897. if (c == '^')
  898. {
  899. FETCH(c, _("Unbalanced ["));
  900. invert = 1;
  901. }
  902. else
  903. invert = 0;
  904. do
  905. {
  906. /* Nobody ever said this had to be fast. :-)
  907. Note that if we're looking at some other [:...:]
  908. construct, we just treat it as a bunch of ordinary
  909. characters. We can do this because we assume
  910. regex has checked for syntax errors before
  911. dfa is ever called. */
  912. if (c == '[' && (syntax_bits & RE_CHAR_CLASSES))
  913. for (c1 = 0; prednames[c1].name; ++c1)
  914. if (looking_at(prednames[c1].name))
  915. {
  916. int (*pred) PARAMS ((int)) = prednames[c1].pred;
  917. for (c2 = 0; c2 < NOTCHAR; ++c2)
  918. if ((*pred)(c2))
  919. setbit_case_fold (c2, ccl);
  920. lexptr += strlen(prednames[c1].name);
  921. lexleft -= strlen(prednames[c1].name);
  922. FETCH(c1, _("Unbalanced ["));
  923. goto skip;
  924. }
  925. if (c == '\\' && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  926. FETCH(c, _("Unbalanced ["));
  927. FETCH(c1, _("Unbalanced ["));
  928. if (c1 == '-')
  929. {
  930. FETCH(c2, _("Unbalanced ["));
  931. if (c2 == ']')
  932. {
  933. /* In the case [x-], the - is an ordinary hyphen,
  934. which is left in c1, the lookahead character. */
  935. --lexptr;
  936. ++lexleft;
  937. }
  938. else
  939. {
  940. if (c2 == '\\'
  941. && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  942. FETCH(c2, _("Unbalanced ["));
  943. FETCH(c1, _("Unbalanced ["));
  944. if (!hard_LC_COLLATE) {
  945. for (; c <= c2; c++)
  946. setbit_case_fold (c, ccl);
  947. } else {
  948. /* POSIX locales are painful - leave the decision to libc */
  949. char expr[6] = { '[', c, '-', c2, ']', '\0' };
  950. regex_t re;
  951. if (regcomp (&re, expr, case_fold ? REG_ICASE : 0) == REG_NOERROR) {
  952. for (c = 0; c < NOTCHAR; ++c) {
  953. char buf[2] = { c, '\0' };
  954. regmatch_t mat;
  955. if (regexec (&re, buf, 1, &mat, 0) == REG_NOERROR
  956. && mat.rm_so == 0 && mat.rm_eo == 1)
  957. setbit_case_fold (c, ccl);
  958. }
  959. regfree (&re);
  960. }
  961. }
  962. continue;
  963. }
  964. }
  965. setbit_case_fold (c, ccl);
  966. skip:
  967. ;
  968. }
  969. while ((c = c1) != ']');
  970. if (invert)
  971. {
  972. notset(ccl);
  973. if (syntax_bits & RE_HAT_LISTS_NOT_NEWLINE)
  974. clrbit(eolbyte, ccl);
  975. }
  976. return lasttok = CSET + charclass_index(ccl);
  977. default:
  978. normal_char:
  979. laststart = 0;
  980. if (case_fold && ISALPHA(c))
  981. {
  982. zeroset(ccl);
  983. setbit_case_fold (c, ccl);
  984. return lasttok = CSET + charclass_index(ccl);
  985. }
  986. return c;
  987. }
  988. }
  989. /* The above loop should consume at most a backslash
  990. and some other character. */
  991. abort();
  992. return END; /* keeps pedantic compilers happy. */
  993. }
  994. /* Recursive descent parser for regular expressions. */
  995. static token tok; /* Lookahead token. */
  996. static int depth; /* Current depth of a hypothetical stack
  997. holding deferred productions. This is
  998. used to determine the depth that will be
  999. required of the real stack later on in
  1000. dfaanalyze(). */
  1001. /* Add the given token to the parse tree, maintaining the depth count and
  1002. updating the maximum depth if necessary. */
  1003. static void
  1004. addtok (token t)
  1005. {
  1006. #ifdef MBS_SUPPORT
  1007. if (MB_CUR_MAX > 1)
  1008. {
  1009. REALLOC_IF_NECESSARY(dfa->multibyte_prop, int, dfa->nmultibyte_prop,
  1010. dfa->tindex);
  1011. /* Set dfa->multibyte_prop. See struct dfa in dfa.h. */
  1012. if (t == MBCSET)
  1013. dfa->multibyte_prop[dfa->tindex] = ((dfa->nmbcsets - 1) << 2) + 3;
  1014. else if (t < NOTCHAR)
  1015. dfa->multibyte_prop[dfa->tindex]
  1016. = (cur_mb_len == 1)? 3 /* single-byte char */
  1017. : (((cur_mb_index == 1)? 1 : 0) /* 1st-byte of multibyte char */
  1018. + ((cur_mb_index == cur_mb_len)? 2 : 0)); /* last-byte */
  1019. else
  1020. /* It may be unnecesssary, but it is safer to treat other
  1021. symbols as singlebyte characters. */
  1022. dfa->multibyte_prop[dfa->tindex] = 3;
  1023. }
  1024. #endif
  1025. REALLOC_IF_NECESSARY(dfa->tokens, token, dfa->talloc, dfa->tindex);
  1026. dfa->tokens[dfa->tindex++] = t;
  1027. switch (t)
  1028. {
  1029. case QMARK:
  1030. case STAR:
  1031. case PLUS:
  1032. break;
  1033. case CAT:
  1034. case OR:
  1035. case ORTOP:
  1036. --depth;
  1037. break;
  1038. default:
  1039. ++dfa->nleaves;
  1040. case EMPTY:
  1041. ++depth;
  1042. break;
  1043. }
  1044. if (depth > dfa->depth)
  1045. dfa->depth = depth;
  1046. }
  1047. /* The grammar understood by the parser is as follows.
  1048. regexp:
  1049. regexp OR branch
  1050. branch
  1051. branch:
  1052. branch closure
  1053. closure
  1054. closure:
  1055. closure QMARK
  1056. closure STAR
  1057. closure PLUS
  1058. closure REPMN
  1059. atom
  1060. atom:
  1061. <normal character>
  1062. <multibyte character>
  1063. ANYCHAR
  1064. MBCSET
  1065. CSET
  1066. BACKREF
  1067. BEGLINE
  1068. ENDLINE
  1069. BEGWORD
  1070. ENDWORD
  1071. LIMWORD
  1072. NOTLIMWORD
  1073. CRANGE
  1074. LPAREN regexp RPAREN
  1075. <empty>
  1076. The parser builds a parse tree in postfix form in an array of tokens. */
  1077. static void
  1078. atom (void)
  1079. {
  1080. if ((tok >= 0 && tok < NOTCHAR) || tok >= CSET || tok == BACKREF
  1081. || tok == BEGLINE || tok == ENDLINE || tok == BEGWORD
  1082. #ifdef MBS_SUPPORT
  1083. || tok == ANYCHAR || tok == MBCSET /* MB_CUR_MAX > 1 */
  1084. #endif /* MBS_SUPPORT */
  1085. || tok == ENDWORD || tok == LIMWORD || tok == NOTLIMWORD)
  1086. {
  1087. addtok(tok);
  1088. tok = lex();
  1089. #ifdef MBS_SUPPORT
  1090. /* We treat a multibyte character as a single atom, so that DFA
  1091. can treat a multibyte character as a single expression.
  1092. e.g. We construct following tree from "<mb1><mb2>".
  1093. <mb1(1st-byte)><mb1(2nd-byte)><CAT><mb1(3rd-byte)><CAT>
  1094. <mb2(1st-byte)><mb2(2nd-byte)><CAT><mb2(3rd-byte)><CAT><CAT>
  1095. */
  1096. if (MB_CUR_MAX > 1)
  1097. {
  1098. while (cur_mb_index > 1 && tok >= 0 && tok < NOTCHAR)
  1099. {
  1100. addtok(tok);
  1101. addtok(CAT);
  1102. tok = lex();
  1103. }
  1104. }
  1105. #endif /* MBS_SUPPORT */
  1106. }
  1107. else if (tok == CRANGE)
  1108. {
  1109. /* A character range like "[a-z]" in a locale other than "C" or
  1110. "POSIX". This range might any sequence of one or more
  1111. characters. Unfortunately the POSIX locale primitives give
  1112. us no practical way to find what character sequences might be
  1113. matched. Treat this approximately like "(.\1)" -- i.e. match
  1114. one character, and then punt to the full matcher. */
  1115. charclass ccl;
  1116. zeroset (ccl);
  1117. notset (ccl);
  1118. addtok (CSET + charclass_index (ccl));
  1119. addtok (BACKREF);
  1120. addtok (CAT);
  1121. tok = lex ();
  1122. }
  1123. else if (tok == LPAREN)
  1124. {
  1125. tok = lex();
  1126. regexp(0);
  1127. if (tok != RPAREN)
  1128. dfaerror(_("Unbalanced ("));
  1129. tok = lex();
  1130. }
  1131. else
  1132. addtok(EMPTY);
  1133. }
  1134. /* Return the number of tokens in the given subexpression. */
  1135. static int
  1136. nsubtoks (int tindex)
  1137. {
  1138. int ntoks1;
  1139. switch (dfa->tokens[tindex - 1])
  1140. {
  1141. default:
  1142. return 1;
  1143. case QMARK:
  1144. case STAR:
  1145. case PLUS:
  1146. return 1 + nsubtoks(tindex - 1);
  1147. case CAT:
  1148. case OR:
  1149. case ORTOP:
  1150. ntoks1 = nsubtoks(tindex - 1);
  1151. return 1 + ntoks1 + nsubtoks(tindex - 1 - ntoks1);
  1152. }
  1153. }
  1154. /* Copy the given subexpression to the top of the tree. */
  1155. static void
  1156. copytoks (int tindex, int ntokens)
  1157. {
  1158. int i;
  1159. for (i = 0; i < ntokens; ++i)
  1160. addtok(dfa->tokens[tindex + i]);
  1161. }
  1162. static void
  1163. closure (void)
  1164. {
  1165. int tindex, ntokens, i;
  1166. atom();
  1167. while (tok == QMARK || tok == STAR || tok == PLUS || tok == REPMN)
  1168. if (tok == REPMN)
  1169. {
  1170. ntokens = nsubtoks(dfa->tindex);
  1171. tindex = dfa->tindex - ntokens;
  1172. if (maxrep < 0)
  1173. addtok(PLUS);
  1174. if (minrep == 0)
  1175. addtok(QMARK);
  1176. for (i = 1; i < minrep; ++i)
  1177. {
  1178. copytoks(tindex, ntokens);
  1179. addtok(CAT);
  1180. }
  1181. for (; i < maxrep; ++i)
  1182. {
  1183. copytoks(tindex, ntokens);
  1184. addtok(QMARK);
  1185. addtok(CAT);
  1186. }
  1187. tok = lex();
  1188. }
  1189. else
  1190. {
  1191. addtok(tok);
  1192. tok = lex();
  1193. }
  1194. }
  1195. static void
  1196. branch (void)
  1197. {
  1198. closure();
  1199. while (tok != RPAREN && tok != OR && tok >= 0)
  1200. {
  1201. closure();
  1202. addtok(CAT);
  1203. }
  1204. }
  1205. static void
  1206. regexp (int toplevel)
  1207. {
  1208. branch();
  1209. while (tok == OR)
  1210. {
  1211. tok = lex();
  1212. branch();
  1213. if (toplevel)
  1214. addtok(ORTOP);
  1215. else
  1216. addtok(OR);
  1217. }
  1218. }
  1219. /* Main entry point for the parser. S is a string to be parsed, len is the
  1220. length of the string, so s can include NUL characters. D is a pointer to
  1221. the struct dfa to parse into. */
  1222. void
  1223. dfaparse (char const *s, size_t len, struct dfa *d)
  1224. {
  1225. dfa = d;
  1226. lexstart = lexptr = s;
  1227. lexleft = len;
  1228. lasttok = END;
  1229. laststart = 1;
  1230. parens = 0;
  1231. hard_LC_COLLATE = hard_locale (LC_COLLATE);
  1232. #ifdef MBS_SUPPORT
  1233. if (MB_CUR_MAX > 1)
  1234. {
  1235. cur_mb_index = 0;
  1236. cur_mb_len = 0;
  1237. memset(&mbs, 0, sizeof(mbstate_t));
  1238. }
  1239. #endif /* MBS_SUPPORT */
  1240. if (! syntax_bits_set)
  1241. dfaerror(_("No syntax specified"));
  1242. tok = lex();
  1243. depth = d->depth;
  1244. regexp(1);
  1245. if (tok != END)
  1246. dfaerror(_("Unbalanced )"));
  1247. addtok(END - d->nregexps);
  1248. addtok(CAT);
  1249. if (d->nregexps)
  1250. addtok(ORTOP);
  1251. ++d->nregexps;
  1252. }
  1253. /* Some primitives for operating on sets of positions. */
  1254. /* Copy one set to another; the destination must be large enough. */
  1255. static void
  1256. copy (position_set const *src, position_set *dst)
  1257. {
  1258. int i;
  1259. for (i = 0; i < src->nelem; ++i)
  1260. dst->elems[i] = src->elems[i];
  1261. dst->nelem = src->nelem;
  1262. }
  1263. /* Insert a position in a set. Position sets are maintained in sorted
  1264. order according to index. If position already exists in the set with
  1265. the same index then their constraints are logically or'd together.
  1266. S->elems must point to an array large enough to hold the resulting set. */
  1267. static void
  1268. insert (position p, position_set *s)
  1269. {
  1270. int i;
  1271. position t1, t2;
  1272. for (i = 0; i < s->nelem && p.index < s->elems[i].index; ++i)
  1273. continue;
  1274. if (i < s->nelem && p.index == s->elems[i].index)
  1275. s->elems[i].constraint |= p.constraint;
  1276. else
  1277. {
  1278. t1 = p;
  1279. ++s->nelem;
  1280. while (i < s->nelem)
  1281. {
  1282. t2 = s->elems[i];
  1283. s->elems[i++] = t1;
  1284. t1 = t2;
  1285. }
  1286. }
  1287. }
  1288. /* Merge two sets of positions into a third. The result is exactly as if
  1289. the positions of both sets were inserted into an initially empty set. */
  1290. static void
  1291. merge (position_set const *s1, position_set const *s2, position_set *m)
  1292. {
  1293. int i = 0, j = 0;
  1294. m->nelem = 0;
  1295. while (i < s1->nelem && j < s2->nelem)
  1296. if (s1->elems[i].index > s2->elems[j].index)
  1297. m->elems[m->nelem++] = s1->elems[i++];
  1298. else if (s1->elems[i].index < s2->elems[j].index)
  1299. m->elems[m->nelem++] = s2->elems[j++];
  1300. else
  1301. {
  1302. m->elems[m->nelem] = s1->elems[i++];
  1303. m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
  1304. }
  1305. while (i < s1->nelem)
  1306. m->elems[m->nelem++] = s1->elems[i++];
  1307. while (j < s2->nelem)
  1308. m->elems[m->nelem++] = s2->elems[j++];
  1309. }
  1310. /* Delete a position from a set. */
  1311. static void
  1312. delete (position p, position_set *s)
  1313. {
  1314. int i;
  1315. for (i = 0; i < s->nelem; ++i)
  1316. if (p.index == s->elems[i].index)
  1317. break;
  1318. if (i < s->nelem)
  1319. for (--s->nelem; i < s->nelem; ++i)
  1320. s->elems[i] = s->elems[i + 1];
  1321. }
  1322. /* Find the index of the state corresponding to the given position set with
  1323. the given preceding context, or create a new state if there is no such
  1324. state. Newline and letter tell whether we got here on a newline or
  1325. letter, respectively. */
  1326. static int
  1327. state_index (struct dfa *d, position_set const *s, int newline, int letter)
  1328. {
  1329. int hash = 0;
  1330. int constraint;
  1331. int i, j;
  1332. newline = newline ? 1 : 0;
  1333. letter = letter ? 1 : 0;
  1334. for (i = 0; i < s->nelem; ++i)
  1335. hash ^= s->elems[i].index + s->elems[i].constraint;
  1336. /* Try to find a state that exactly matches the proposed one. */
  1337. for (i = 0; i < d->sindex; ++i)
  1338. {
  1339. if (hash != d->states[i].hash || s->nelem != d->states[i].elems.nelem
  1340. || newline != d->states[i].newline || letter != d->states[i].letter)
  1341. continue;
  1342. for (j = 0; j < s->nelem; ++j)
  1343. if (s->elems[j].constraint
  1344. != d->states[i].elems.elems[j].constraint
  1345. || s->elems[j].index != d->states[i].elems.elems[j].index)
  1346. break;
  1347. if (j == s->nelem)
  1348. return i;
  1349. }
  1350. /* We'll have to create a new state. */
  1351. REALLOC_IF_NECESSARY(d->states, dfa_state, d->salloc, d->sindex);
  1352. d->states[i].hash = hash;
  1353. MALLOC(d->states[i].elems.elems, position, s->nelem);
  1354. copy(s, &d->states[i].elems);
  1355. d->states[i].newline = newline;
  1356. d->states[i].letter = letter;
  1357. d->states[i].backref = 0;
  1358. d->states[i].constraint = 0;
  1359. d->states[i].first_end = 0;
  1360. #ifdef MBS_SUPPORT
  1361. if (MB_CUR_MAX > 1)
  1362. d->states[i].mbps.nelem = 0;
  1363. #endif
  1364. for (j = 0; j < s->nelem; ++j)
  1365. if (d->tokens[s->elems[j].index] < 0)
  1366. {
  1367. constraint = s->elems[j].constraint;
  1368. if (SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
  1369. || SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
  1370. || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
  1371. || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
  1372. d->states[i].constraint |= constraint;
  1373. if (! d->states[i].first_end)
  1374. d->states[i].first_end = d->tokens[s->elems[j].index];
  1375. }
  1376. else if (d->tokens[s->elems[j].index] == BACKREF)
  1377. {
  1378. d->states[i].constraint = NO_CONSTRAINT;
  1379. d->states[i].backref = 1;
  1380. }
  1381. ++d->sindex;
  1382. return i;
  1383. }
  1384. /* Find the epsilon closure of a set of positions. If any position of the set
  1385. contains a symbol that matches the empty string in some context, replace
  1386. that position with the elements of its follow labeled with an appropriate
  1387. constraint. Repeat exhaustively until no funny positions are left.
  1388. S->elems must be large enough to hold the result. */
  1389. static void
  1390. epsclosure (position_set *s, struct dfa const *d)
  1391. {
  1392. int i, j;
  1393. int *visited;
  1394. position p, old;
  1395. MALLOC(visited, int, d->tindex);
  1396. for (i = 0; i < d->tindex; ++i)
  1397. visited[i] = 0;
  1398. for (i = 0; i < s->nelem; ++i)
  1399. if (d->tokens[s->elems[i].index] >= NOTCHAR
  1400. && d->tokens[s->elems[i].index] != BACKREF
  1401. #ifdef MBS_SUPPORT
  1402. && d->tokens[s->elems[i].index] != ANYCHAR
  1403. && d->tokens[s->elems[i].index] != MBCSET
  1404. #endif
  1405. && d->tokens[s->elems[i].index] < CSET)
  1406. {
  1407. old = s->elems[i];
  1408. p.constraint = old.constraint;
  1409. delete(s->elems[i], s);
  1410. if (visited[old.index])
  1411. {
  1412. --i;
  1413. continue;
  1414. }
  1415. visited[old.index] = 1;
  1416. switch (d->tokens[old.index])
  1417. {
  1418. case BEGLINE:
  1419. p.constraint &= BEGLINE_CONSTRAINT;
  1420. break;
  1421. case ENDLINE:
  1422. p.constraint &= ENDLINE_CONSTRAINT;
  1423. break;
  1424. case BEGWORD:
  1425. p.constraint &= BEGWORD_CONSTRAINT;
  1426. break;
  1427. case ENDWORD:
  1428. p.constraint &= ENDWORD_CONSTRAINT;
  1429. break;
  1430. case LIMWORD:
  1431. p.constraint &= LIMWORD_CONSTRAINT;
  1432. break;
  1433. case NOTLIMWORD:
  1434. p.constraint &= NOTLIMWORD_CONSTRAINT;
  1435. break;
  1436. default:
  1437. break;
  1438. }
  1439. for (j = 0; j < d->follows[old.index].nelem; ++j)
  1440. {
  1441. p.index = d->follows[old.index].elems[j].index;
  1442. insert(p, s);
  1443. }
  1444. /* Force rescan to start at the beginning. */
  1445. i = -1;
  1446. }
  1447. free(visited);
  1448. }
  1449. /* Perform bottom-up analysis on the parse tree, computing various functions.
  1450. Note that at this point, we're pretending constructs like \< are real
  1451. characters rather than constraints on what can follow them.
  1452. Nullable: A node is nullable if it is at the root of a regexp that can
  1453. match the empty string.
  1454. * EMPTY leaves are nullable.
  1455. * No other leaf is nullable.
  1456. * A QMARK or STAR node is nullable.
  1457. * A PLUS node is nullable if its argument is nullable.
  1458. * A CAT node is nullable if both its arguments are nullable.
  1459. * An OR node is nullable if either argument is nullable.
  1460. Firstpos: The firstpos of a node is the set of positions (nonempty leaves)
  1461. that could correspond to the first character of a string matching the
  1462. regexp rooted at the given node.
  1463. * EMPTY leaves have empty firstpos.
  1464. * The firstpos of a nonempty leaf is that leaf itself.
  1465. * The firstpos of a QMARK, STAR, or PLUS node is the firstpos of its
  1466. argument.
  1467. * The firstpos of a CAT node is the firstpos of the left argument, union
  1468. the firstpos of the right if the left argument is nullable.
  1469. * The firstpos of an OR node is the union of firstpos of each argument.
  1470. Lastpos: The lastpos of a node is the set of positions that could
  1471. correspond to the last character of a string matching the regexp at
  1472. the given node.
  1473. * EMPTY leaves have empty lastpos.
  1474. * The lastpos of a nonempty leaf is that leaf itself.
  1475. * The lastpos of a QMARK, STAR, or PLUS node is the lastpos of its
  1476. argument.
  1477. * The lastpos of a CAT node is the lastpos of its right argument, union
  1478. the lastpos of the left if the right argument is nullable.
  1479. * The lastpos of an OR node is the union of the lastpos of each argument.
  1480. Follow: The follow of a position is the set of positions that could
  1481. correspond to the character following a character matching the node in
  1482. a string matching the regexp. At this point we consider special symbols
  1483. that match the empty string in some context to be just normal characters.
  1484. Later, if we find that a special symbol is in a follow set, we will
  1485. replace it with the elements of its follow, labeled with an appropriate
  1486. constraint.
  1487. * Every node in the firstpos of the argument of a STAR or PLUS node is in
  1488. the follow of every node in the lastpos.
  1489. * Every node in the firstpos of the second argument of a CAT node is in
  1490. the follow of every node in the lastpos of the first argument.
  1491. Because of the postfix representation of the parse tree, the depth-first
  1492. analysis is conveniently done by a linear scan with the aid of a stack.
  1493. Sets are stored as arrays of the elements, obeying a stack-like allocation
  1494. scheme; the number of elements in each set deeper in the stack can be
  1495. used to determine the address of a particular set's array. */
  1496. void
  1497. dfaanalyze (struct dfa *d, int searchflag)
  1498. {
  1499. int *nullable; /* Nullable stack. */
  1500. int *nfirstpos; /* Element count stack for firstpos sets. */
  1501. position *firstpos; /* Array where firstpos elements are stored. */
  1502. int *nlastpos; /* Element count stack for lastpos sets. */
  1503. position *lastpos; /* Array where lastpos elements are stored. */
  1504. int *nalloc; /* Sizes of arrays allocated to follow sets. */
  1505. position_set tmp; /* Temporary set for merging sets. */
  1506. position_set merged; /* Result of merging sets. */
  1507. int wants_newline; /* True if some position wants newline info. */
  1508. int *o_nullable;
  1509. int *o_nfirst, *o_nlast;
  1510. position *o_firstpos, *o_lastpos;
  1511. int i, j;
  1512. position *pos;
  1513. #ifdef DEBUG
  1514. fprintf(stderr, "dfaanalyze:\n");
  1515. for (i = 0; i < d->tindex; ++i)
  1516. {
  1517. fprintf(stderr, " %d:", i);
  1518. prtok(d->tokens[i]);
  1519. }
  1520. putc('\n', stderr);
  1521. #endif
  1522. d->searchflag = searchflag;
  1523. MALLOC(nullable, int, d->depth);
  1524. o_nullable = nullable;
  1525. MALLOC(nfirstpos, int, d->depth);
  1526. o_nfirst = nfirstpos;
  1527. MALLOC(firstpos, position, d->nleaves);
  1528. o_firstpos = firstpos, firstpos += d->nleaves;
  1529. MALLOC(nlastpos, int, d->depth);
  1530. o_nlast = nlastpos;
  1531. MALLOC(lastpos, position, d->nleaves);
  1532. o_lastpos = lastpos, lastpos += d->nleaves;
  1533. MALLOC(nalloc, int, d->tindex);
  1534. for (i = 0; i < d->tindex; ++i)
  1535. nalloc[i] = 0;
  1536. MALLOC(merged.elems, position, d->nleaves);
  1537. CALLOC(d->follows, position_set, d->tindex);
  1538. for (i = 0; i < d->tindex; ++i)
  1539. #ifdef DEBUG
  1540. { /* Nonsyntactic #ifdef goo... */
  1541. #endif
  1542. switch (d->tokens[i])
  1543. {
  1544. case EMPTY:
  1545. /* The empty set is nullable. */
  1546. *nullable++ = 1;
  1547. /* The firstpos and lastpos of the empty leaf are both empty. */
  1548. *nfirstpos++ = *nlastpos++ = 0;
  1549. break;
  1550. case STAR:
  1551. case PLUS:
  1552. /* Every element in the firstpos of the argument is in the follow
  1553. of every element in the lastpos. */
  1554. tmp.nelem = nfirstpos[-1];
  1555. tmp.elems = firstpos;
  1556. pos = lastpos;
  1557. for (j = 0; j < nlastpos[-1]; ++j)
  1558. {
  1559. merge(&tmp, &d->follows[pos[j].index], &merged);
  1560. REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
  1561. nalloc[pos[j].index], merged.nelem - 1);
  1562. copy(&merged, &d->follows[pos[j].index]);
  1563. }
  1564. case QMARK:
  1565. /* A QMARK or STAR node is automatically nullable. */
  1566. if (d->tokens[i] != PLUS)
  1567. nullable[-1] = 1;
  1568. break;
  1569. case CAT:
  1570. /* Every element in the firstpos of the second argument is in the
  1571. follow of every element in the lastpos of the first argument. */
  1572. tmp.nelem = nfirstpos[-1];
  1573. tmp.elems = firstpos;
  1574. pos = lastpos + nlastpos[-1];
  1575. for (j = 0; j < nlastpos[-2]; ++j)
  1576. {
  1577. merge(&tmp, &d->follows[pos[j].index], &merged);
  1578. REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
  1579. nalloc[pos[j].index], merged.nelem - 1);
  1580. copy(&merged, &d->follows[pos[j].index]);
  1581. }
  1582. /* The firstpos of a CAT node is the firstpos of the first argument,
  1583. union that of the second argument if the first is nullable. */
  1584. if (nullable[-2])
  1585. nfirstpos[-2] += nfirstpos[-1];
  1586. else
  1587. firstpos += nfirstpos[-1];
  1588. --nfirstpos;
  1589. /* The lastpos of a CAT node is the lastpos of the second argument,
  1590. union that of the first argument if the second is nullable. */
  1591. if (nullable[-1])
  1592. nlastpos[-2] += nlastpos[-1];
  1593. else
  1594. {
  1595. pos = lastpos + nlastpos[-2];
  1596. for (j = nlastpos[-1] - 1; j >= 0; --j)
  1597. pos[j] = lastpos[j];
  1598. lastpos += nlastpos[-2];
  1599. nlastpos[-2] = nlastpos[-1];
  1600. }
  1601. --nlastpos;
  1602. /* A CAT node is nullable if both arguments are nullable. */
  1603. nullable[-2] = nullable[-1] && nullable[-2];
  1604. --nullable;
  1605. break;
  1606. case OR:
  1607. case ORTOP:
  1608. /* The firstpos is the union of the firstpos of each argument. */
  1609. nfirstpos[-2] += nfirstpos[-1];
  1610. --nfirstpos;
  1611. /* The lastpos is the union of the lastpos of each argument. */
  1612. nlastpos[-2] += nlastpos[-1];
  1613. --nlastpos;
  1614. /* An OR node is nullable if either argument is nullable. */
  1615. nullable[-2] = nullable[-1] || nullable[-2];
  1616. --nullable;
  1617. break;
  1618. default:
  1619. /* Anything else is a nonempty position. (Note that special
  1620. constructs like \< are treated as nonempty strings here;
  1621. an "epsilon closure" effectively makes them nullable later.
  1622. Backreferences have to get a real position so we can detect
  1623. transitions on them later. But they are nullable. */
  1624. *nullable++ = d->tokens[i] == BACKREF;
  1625. /* This position is in its own firstpos and lastpos. */
  1626. *nfirstpos++ = *nlastpos++ = 1;
  1627. --firstpos, --lastpos;
  1628. firstpos->index = lastpos->index = i;
  1629. firstpos->constraint = lastpos->constraint = NO_CONSTRAINT;
  1630. /* Allocate the follow set for this position. */
  1631. nalloc[i] = 1;
  1632. MALLOC(d->follows[i].elems, position, nalloc[i]);
  1633. break;
  1634. }
  1635. #ifdef DEBUG
  1636. /* ... balance the above nonsyntactic #ifdef goo... */
  1637. fprintf(stderr, "node %d:", i);
  1638. prtok(d->tokens[i]);
  1639. putc('\n', stderr);
  1640. fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
  1641. fprintf(stderr, " firstpos:");
  1642. for (j = nfirstpos[-1] - 1; j >= 0; --j)
  1643. {
  1644. fprintf(stderr, " %d:", firstpos[j].index);
  1645. prtok(d->tokens[firstpos[j].index]);
  1646. }
  1647. fprintf(stderr, "\n lastpos:");
  1648. for (j = nlastpos[-1] - 1; j >= 0; --j)
  1649. {
  1650. fprintf(stderr, " %d:", lastpos[j].index);
  1651. prtok(d->tokens[lastpos[j].index]);
  1652. }
  1653. putc('\n', stderr);
  1654. }
  1655. #endif
  1656. /* For each follow set that is the follow set of a real position, replace
  1657. it with its epsilon closure. */
  1658. for (i = 0; i < d->tindex; ++i)
  1659. if (d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF
  1660. #ifdef MBS_SUPPORT
  1661. || d->tokens[i] == ANYCHAR
  1662. || d->tokens[i] == MBCSET
  1663. #endif
  1664. || d->tokens[i] >= CSET)
  1665. {
  1666. #ifdef DEBUG
  1667. fprintf(stderr, "follows(%d:", i);
  1668. prtok(d->tokens[i]);
  1669. fprintf(stderr, "):");
  1670. for (j = d->follows[i].nelem - 1; j >= 0; --j)
  1671. {
  1672. fprintf(stderr, " %d:", d->follows[i].elems[j].index);
  1673. prtok(d->tokens[d->follows[i].elems[j].index]);
  1674. }
  1675. putc('\n', stderr);
  1676. #endif
  1677. copy(&d->follows[i], &merged);
  1678. epsclosure(&merged, d);
  1679. if (d->follows[i].nelem < merged.nelem)
  1680. REALLOC(d->follows[i].elems, position, merged.nelem);
  1681. copy(&merged, &d->follows[i]);
  1682. }
  1683. /* Get the epsilon closure of the firstpos of the regexp. The result will
  1684. be the set of positions of state 0. */
  1685. merged.nelem = 0;
  1686. for (i = 0; i < nfirstpos[-1]; ++i)
  1687. insert(firstpos[i], &merged);
  1688. epsclosure(&merged, d);
  1689. /* Check if any of the positions of state 0 will want newline context. */
  1690. wants_newline = 0;
  1691. for (i = 0; i < merged.nelem; ++i)
  1692. if (PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
  1693. wants_newline = 1;
  1694. /* Build the initial state. */
  1695. d->salloc = 1;
  1696. d->sindex = 0;
  1697. MALLOC(d->states, dfa_state, d->salloc);
  1698. state_index(d, &merged, wants_newline, 0);
  1699. free(o_nullable);
  1700. free(o_nfirst);
  1701. free(o_firstpos);
  1702. free(o_nlast);
  1703. free(o_lastpos);
  1704. free(nalloc);
  1705. free(merged.elems);
  1706. }
  1707. /* Find, for each character, the transition out of state s of d, and store
  1708. it in the appropriate slot of trans.
  1709. We divide the positions of s into groups (positions can appear in more
  1710. than one group). Each group is labeled with a set of characters that
  1711. every position in the group matches (taking into account, if necessary,
  1712. preceding context information of s). For each group, find the union
  1713. of the its elements' follows. This set is the set of positions of the
  1714. new state. For each character in the group's label, set the transition
  1715. on this character to be to a state corresponding to the set's positions,
  1716. and its associated backward context information, if necessary.
  1717. If we are building a searching matcher, we include the positions of state
  1718. 0 in every state.
  1719. The collection of groups is constructed by building an equivalence-class
  1720. partition of the positions of s.
  1721. For each position, find the set of characters C that it matches. Eliminate
  1722. any characters from C that fail on grounds of backward context.
  1723. Search through the groups, looking for a group whose label L has nonempty
  1724. intersection with C. If L - C is nonempty, create a new group labeled
  1725. L - C and having the same positions as the current group, and set L to
  1726. the intersection of L and C. Insert the position in this group, set
  1727. C = C - L, and resume scanning.
  1728. If after comparing with every group there are characters remaining in C,
  1729. create a new group labeled with the characters of C and insert this
  1730. position in that group. */
  1731. void
  1732. dfastate (int s, struct dfa *d, int trans[])
  1733. {
  1734. position_set grps[NOTCHAR]; /* As many as will ever be needed. */
  1735. charclass labels[NOTCHAR]; /* Labels corresponding to the groups. */
  1736. int ngrps = 0; /* Number of groups actually used. */
  1737. position pos; /* Current position being considered. */
  1738. charclass matches; /* Set of matching characters. */
  1739. int matchesf; /* True if matches is nonempty. */
  1740. charclass intersect; /* Intersection with some label set. */
  1741. int intersectf; /* True if intersect is nonempty. */
  1742. charclass leftovers; /* Stuff in the label that didn't match. */
  1743. int leftoversf; /* True if leftovers is nonempty. */
  1744. static charclass letters; /* Set of characters considered letters. */
  1745. static charclass newline; /* Set of characters that aren't newline. */
  1746. position_set follows; /* Union of the follows of some group. */
  1747. position_set tmp; /* Temporary space for merging sets. */
  1748. int state; /* New state. */
  1749. int wants_newline; /* New state wants to know newline context. */
  1750. int state_newline; /* New state on a newline transition. */
  1751. int wants_letter; /* New state wants to know letter context. */
  1752. int state_letter; /* New state on a letter transition. */
  1753. static int initialized; /* Flag for static initialization. */
  1754. #ifdef MBS_SUPPORT
  1755. int next_isnt_1st_byte = 0; /* Flag If we can't add state0. */
  1756. #endif
  1757. int i, j, k;
  1758. /* Initialize the set of letters, if necessary. */
  1759. if (! initialized)
  1760. {
  1761. initialized = 1;
  1762. for (i = 0; i < NOTCHAR; ++i)
  1763. if (IS_WORD_CONSTITUENT(i))
  1764. setbit(i, letters);
  1765. setbit(eolbyte, newline);
  1766. }
  1767. zeroset(matches);
  1768. for (i = 0; i < d->states[s].elems.nelem; ++i)
  1769. {
  1770. pos = d->states[s].elems.elems[i];
  1771. if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR)
  1772. setbit(d->tokens[pos.index], matches);
  1773. else if (d->tokens[pos.index] >= CSET)
  1774. copyset(d->charclasses[d->tokens[pos.index] - CSET], matches);
  1775. #ifdef MBS_SUPPORT
  1776. else if (d->tokens[pos.index] == ANYCHAR
  1777. || d->tokens[pos.index] == MBCSET)
  1778. /* MB_CUR_MAX > 1 */
  1779. {
  1780. /* ANYCHAR and MBCSET must match with a single character, so we
  1781. must put it to d->states[s].mbps, which contains the positions
  1782. which can match with a single character not a byte. */
  1783. if (d->states[s].mbps.nelem == 0)
  1784. {
  1785. MALLOC(d->states[s].mbps.elems, position,
  1786. d->states[s].elems.nelem);
  1787. }
  1788. insert(pos, &(d->states[s].mbps));
  1789. continue;
  1790. }
  1791. #endif /* MBS_SUPPORT */
  1792. else
  1793. continue;
  1794. /* Some characters may need to be eliminated from matches because
  1795. they fail in the current context. */
  1796. if (pos.constraint != 0xFF)
  1797. {
  1798. if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1799. d->states[s].newline, 1))
  1800. clrbit(eolbyte, matches);
  1801. if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1802. d->states[s].newline, 0))
  1803. for (j = 0; j < CHARCLASS_INTS; ++j)
  1804. matches[j] &= newline[j];
  1805. if (! MATCHES_LETTER_CONTEXT(pos.constraint,
  1806. d->states[s].letter, 1))
  1807. for (j = 0; j < CHARCLASS_INTS; ++j)
  1808. matches[j] &= ~letters[j];
  1809. if (! MATCHES_LETTER_CONTEXT(pos.constraint,
  1810. d->states[s].letter, 0))
  1811. for (j = 0; j < CHARCLASS_INTS; ++j)
  1812. matches[j] &= letters[j];
  1813. /* If there are no characters left, there's no point in going on. */
  1814. for (j = 0; j < CHARCLASS_INTS && !matches[j]; ++j)
  1815. continue;
  1816. if (j == CHARCLASS_INTS)
  1817. continue;
  1818. }
  1819. for (j = 0; j < ngrps; ++j)
  1820. {
  1821. /* If matches contains a single character only, and the current
  1822. group's label doesn't contain that character, go on to the
  1823. next group. */
  1824. if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR
  1825. && !tstbit(d->tokens[pos.index], labels[j]))
  1826. continue;
  1827. /* Check if this group's label has a nonempty intersection with
  1828. matches. */
  1829. intersectf = 0;
  1830. for (k = 0; k < CHARCLASS_INTS; ++k)
  1831. (intersect[k] = matches[k] & labels[j][k]) ? (intersectf = 1) : 0;
  1832. if (! intersectf)
  1833. continue;
  1834. /* It does; now find the set differences both ways. */
  1835. leftoversf = matchesf = 0;
  1836. for (k = 0; k < CHARCLASS_INTS; ++k)
  1837. {
  1838. /* Even an optimizing compiler can't know this for sure. */
  1839. int match = matches[k], label = labels[j][k];
  1840. (leftovers[k] = ~match & label) ? (leftoversf = 1) : 0;
  1841. (matches[k] = match & ~label) ? (matchesf = 1) : 0;
  1842. }
  1843. /* If there were leftovers, create a new group labeled with them. */
  1844. if (leftoversf)
  1845. {
  1846. copyset(leftovers, labels[ngrps]);
  1847. copyset(intersect, labels[j]);
  1848. MALLOC(grps[ngrps].elems, position, d->nleaves);
  1849. copy(&grps[j], &grps[ngrps]);
  1850. ++ngrps;
  1851. }
  1852. /* Put the position in the current group. Note that there is no
  1853. reason to call insert() here. */
  1854. grps[j].elems[grps[j].nelem++] = pos;
  1855. /* If every character matching the current position has been
  1856. accounted for, we're done. */
  1857. if (! matchesf)
  1858. break;
  1859. }
  1860. /* If we've passed the last group, and there are still characters
  1861. unaccounted for, then we'll have to create a new group. */
  1862. if (j == ngrps)
  1863. {
  1864. copyset(matches, labels[ngrps]);
  1865. zeroset(matches);
  1866. MALLOC(grps[ngrps].elems, position, d->nleaves);
  1867. grps[ngrps].nelem = 1;
  1868. grps[ngrps].elems[0] = pos;
  1869. ++ngrps;
  1870. }
  1871. }
  1872. MALLOC(follows.elems, position, d->nleaves);
  1873. MALLOC(tmp.elems, position, d->nleaves);
  1874. /* If we are a searching matcher, the default transition is to a state
  1875. containing the positions of state 0, otherwise the default transition
  1876. is to fail miserably. */
  1877. if (d->searchflag)
  1878. {
  1879. wants_newline = 0;
  1880. wants_letter = 0;
  1881. for (i = 0; i < d->states[0].elems.nelem; ++i)
  1882. {
  1883. if (PREV_NEWLINE_DEPENDENT(d->states[0].elems.elems[i].constraint))
  1884. wants_newline = 1;
  1885. if (PREV_LETTER_DEPENDENT(d->states[0].elems.elems[i].constraint))
  1886. wants_letter = 1;
  1887. }
  1888. copy(&d->states[0].elems, &follows);
  1889. state = state_index(d, &follows, 0, 0);
  1890. if (wants_newline)
  1891. state_newline = state_index(d, &follows, 1, 0);
  1892. else
  1893. state_newline = state;
  1894. if (wants_letter)
  1895. state_letter = state_index(d, &follows, 0, 1);
  1896. else
  1897. state_letter = state;
  1898. for (i = 0; i < NOTCHAR; ++i)
  1899. trans[i] = (IS_WORD_CONSTITUENT(i)) ? state_letter : state;
  1900. trans[eolbyte] = state_newline;
  1901. }
  1902. else
  1903. for (i = 0; i < NOTCHAR; ++i)
  1904. trans[i] = -1;
  1905. for (i = 0; i < ngrps; ++i)
  1906. {
  1907. follows.nelem = 0;
  1908. /* Find the union of the follows of the positions of the group.
  1909. This is a hideously inefficient loop. Fix it someday. */
  1910. for (j = 0; j < grps[i].nelem; ++j)
  1911. for (k = 0; k < d->follows[grps[i].elems[j].index].nelem; ++k)
  1912. insert(d->follows[grps[i].elems[j].index].elems[k], &follows);
  1913. #ifdef MBS_SUPPORT
  1914. if (MB_CUR_MAX > 1)
  1915. {
  1916. /* If a token in follows.elems is not 1st byte of a multibyte
  1917. character, or the states of follows must accept the bytes
  1918. which are not 1st byte of the multibyte character.
  1919. Then, if a state of follows encounter a byte, it must not be
  1920. a 1st byte of a multibyte character nor singlebyte character.
  1921. We cansel to add state[0].follows to next state, because
  1922. state[0] must accept 1st-byte
  1923. For example, we assume <sb a> is a certain singlebyte
  1924. character, <mb A> is a certain multibyte character, and the
  1925. codepoint of <sb a> equals the 2nd byte of the codepoint of
  1926. <mb A>.
  1927. When state[0] accepts <sb a>, state[i] transit to state[i+1]
  1928. by accepting accepts 1st byte of <mb A>, and state[i+1]
  1929. accepts 2nd byte of <mb A>, if state[i+1] encounter the
  1930. codepoint of <sb a>, it must not be <sb a> but 2nd byte of
  1931. <mb A>, so we can not add state[0]. */
  1932. next_isnt_1st_byte = 0;
  1933. for (j = 0; j < follows.nelem; ++j)
  1934. {
  1935. if (!(d->multibyte_prop[follows.elems[j].index] & 1))
  1936. {
  1937. next_isnt_1st_byte = 1;
  1938. break;
  1939. }
  1940. }
  1941. }
  1942. #endif
  1943. /* If we are building a searching matcher, throw in the positions
  1944. of state 0 as well. */
  1945. #ifdef MBS_SUPPORT
  1946. if (d->searchflag && (MB_CUR_MAX == 1 || !next_isnt_1st_byte))
  1947. #else
  1948. if (d->searchflag)
  1949. #endif
  1950. for (j = 0; j < d->states[0].elems.nelem; ++j)
  1951. insert(d->states[0].elems.elems[j], &follows);
  1952. /* Find out if the new state will want any context information. */
  1953. wants_newline = 0;
  1954. if (tstbit(eolbyte, labels[i]))
  1955. for (j = 0; j < follows.nelem; ++j)
  1956. if (PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
  1957. wants_newline = 1;
  1958. wants_letter = 0;
  1959. for (j = 0; j < CHARCLASS_INTS; ++j)
  1960. if (labels[i][j] & letters[j])
  1961. break;
  1962. if (j < CHARCLASS_INTS)
  1963. for (j = 0; j < follows.nelem; ++j)
  1964. if (PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
  1965. wants_letter = 1;
  1966. /* Find the state(s) corresponding to the union of the follows. */
  1967. state = state_index(d, &follows, 0, 0);
  1968. if (wants_newline)
  1969. state_newline = state_index(d, &follows, 1, 0);
  1970. else
  1971. state_newline = state;
  1972. if (wants_letter)
  1973. state_letter = state_index(d, &follows, 0, 1);
  1974. else
  1975. state_letter = state;
  1976. /* Set the transitions for each character in the current label. */
  1977. for (j = 0; j < CHARCLASS_INTS; ++j)
  1978. for (k = 0; k < INTBITS; ++k)
  1979. if (labels[i][j] & 1 << k)
  1980. {
  1981. int c = j * INTBITS + k;
  1982. if (c == eolbyte)
  1983. trans[c] = state_newline;
  1984. else if (IS_WORD_CONSTITUENT(c))
  1985. trans[c] = state_letter;
  1986. else if (c < NOTCHAR)
  1987. trans[c] = state;
  1988. }
  1989. }
  1990. for (i = 0; i < ngrps; ++i)
  1991. free(grps[i].elems);
  1992. free(follows.elems);
  1993. free(tmp.elems);
  1994. }
  1995. /* Some routines for manipulating a compiled dfa's transition tables.
  1996. Each state may or may not have a transition table; if it does, and it
  1997. is a non-accepting state, then d->trans[state] points to its table.
  1998. If it is an accepting state then d->fails[state] points to its table.
  1999. If it has no table at all, then d->trans[state] is NULL.
  2000. TODO: Improve this comment, get rid of the unnecessary redundancy. */
  2001. static void
  2002. build_state (int s, struct dfa *d)
  2003. {
  2004. int *trans; /* The new transition table. */
  2005. int i;
  2006. /* Set an upper limit on the number of transition tables that will ever
  2007. exist at once. 1024 is arbitrary. The idea is that the frequently
  2008. used transition tables will be quickly rebuilt, whereas the ones that
  2009. were only needed once or twice will be cleared away. */
  2010. if (d->trcount >= 1024)
  2011. {
  2012. for (i = 0; i < d->tralloc; ++i)
  2013. if (d->trans[i])
  2014. {
  2015. free((ptr_t) d->trans[i]);
  2016. d->trans[i] = NULL;
  2017. }
  2018. else if (d->fails[i])
  2019. {
  2020. free((ptr_t) d->fails[i]);
  2021. d->fails[i] = NULL;
  2022. }
  2023. d->trcount = 0;
  2024. }
  2025. ++d->trcount;
  2026. /* Set up the success bits for this state. */
  2027. d->success[s] = 0;
  2028. if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 1, d->states[s].letter, 0,
  2029. s, *d))
  2030. d->success[s] |= 4;
  2031. if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 1,
  2032. s, *d))
  2033. d->success[s] |= 2;
  2034. if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 0,
  2035. s, *d))
  2036. d->success[s] |= 1;
  2037. MALLOC(trans, int, NOTCHAR);
  2038. dfastate(s, d, trans);
  2039. /* Now go through the new transition table, and make sure that the trans
  2040. and fail arrays are allocated large enough to hold a pointer for the
  2041. largest state mentioned in the table. */
  2042. for (i = 0; i < NOTCHAR; ++i)
  2043. if (trans[i] >= d->tralloc)
  2044. {
  2045. int oldalloc = d->tralloc;
  2046. while (trans[i] >= d->tralloc)
  2047. d->tralloc *= 2;
  2048. REALLOC(d->realtrans, int *, d->tralloc + 1);
  2049. d->trans = d->realtrans + 1;
  2050. REALLOC(d->fails, int *, d->tralloc);
  2051. REALLOC(d->success, int, d->tralloc);
  2052. while (oldalloc < d->tralloc)
  2053. {
  2054. d->trans[oldalloc] = NULL;
  2055. d->fails[oldalloc++] = NULL;
  2056. }
  2057. }
  2058. /* Newline is a sentinel. */
  2059. trans[eolbyte] = -1;
  2060. if (ACCEPTING(s, *d))
  2061. d->fails[s] = trans;
  2062. else
  2063. d->trans[s] = trans;
  2064. }
  2065. static void
  2066. build_state_zero (struct dfa *d)
  2067. {
  2068. d->tralloc = 1;
  2069. d->trcount = 0;
  2070. CALLOC(d->realtrans, int *, d->tralloc + 1);
  2071. d->trans = d->realtrans + 1;
  2072. CALLOC(d->fails, int *, d->tralloc);
  2073. MALLOC(d->success, int, d->tralloc);
  2074. build_state(0, d);
  2075. }
  2076. #ifdef MBS_SUPPORT
  2077. /* Multibyte character handling sub-routins for dfaexec. */
  2078. /* Initial state may encounter the byte which is not a singlebyte character
  2079. nor 1st byte of a multibyte character. But it is incorrect for initial
  2080. state to accept such a byte.
  2081. For example, in sjis encoding the regular expression like "\\" accepts
  2082. the codepoint 0x5c, but should not accept the 2nd byte of the codepoint
  2083. 0x815c. Then Initial state must skip the bytes which are not a singlebyte
  2084. character nor 1st byte of a multibyte character. */
  2085. #define SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p) \
  2086. if (s == 0) \
  2087. { \
  2088. while (inputwcs[p - buf_begin] == 0 \
  2089. && mblen_buf[p - buf_begin] > 0 \
  2090. && p < buf_end) \
  2091. ++p; \
  2092. if (p >= end) \
  2093. { \
  2094. free(mblen_buf); \
  2095. free(inputwcs); \
  2096. return (size_t) -1; \
  2097. } \
  2098. }
  2099. static void
  2100. realloc_trans_if_necessary(struct dfa *d, int new_state)
  2101. {
  2102. /* Make sure that the trans and fail arrays are allocated large enough
  2103. to hold a pointer for the new state. */
  2104. if (new_state >= d->tralloc)
  2105. {
  2106. int oldalloc = d->tralloc;
  2107. while (new_state >= d->tralloc)
  2108. d->tralloc *= 2;
  2109. REALLOC(d->realtrans, int *, d->tralloc + 1);
  2110. d->trans = d->realtrans + 1;
  2111. REALLOC(d->fails, int *, d->tralloc);
  2112. REALLOC(d->success, int, d->tralloc);
  2113. while (oldalloc < d->tralloc)
  2114. {
  2115. d->trans[oldalloc] = NULL;
  2116. d->fails[oldalloc++] = NULL;
  2117. }
  2118. }
  2119. }
  2120. /* Return values of transit_state_singlebyte(), and
  2121. transit_state_consume_1char. */
  2122. typedef enum
  2123. {
  2124. TRANSIT_STATE_IN_PROGRESS, /* State transition has not finished. */
  2125. TRANSIT_STATE_DONE, /* State transition has finished. */
  2126. TRANSIT_STATE_END_BUFFER /* Reach the end of the buffer. */
  2127. } status_transit_state;
  2128. /* Consume a single byte and transit state from 's' to '*next_state'.
  2129. This function is almost same as the state transition routin in dfaexec().
  2130. But state transition is done just once, otherwise matching succeed or
  2131. reach the end of the buffer. */
  2132. static status_transit_state
  2133. transit_state_singlebyte (struct dfa *d, int s, unsigned char const *p,
  2134. int *next_state)
  2135. {
  2136. int *t;
  2137. int works = s;
  2138. status_transit_state rval = TRANSIT_STATE_IN_PROGRESS;
  2139. while (rval == TRANSIT_STATE_IN_PROGRESS)
  2140. {
  2141. if ((t = d->trans[works]) != NULL)
  2142. {
  2143. works = t[*p];
  2144. rval = TRANSIT_STATE_DONE;
  2145. if (works < 0)
  2146. works = 0;
  2147. }
  2148. else if (works < 0)
  2149. {
  2150. if (p == buf_end)
  2151. /* At the moment, it must not happen. */
  2152. return TRANSIT_STATE_END_BUFFER;
  2153. works = 0;
  2154. }
  2155. else if (d->fails[works])
  2156. {
  2157. works = d->fails[works][*p];
  2158. rval = TRANSIT_STATE_DONE;
  2159. }
  2160. else
  2161. {
  2162. build_state(works, d);
  2163. }
  2164. }
  2165. *next_state = works;
  2166. return rval;
  2167. }
  2168. /* Check whether period can match or not in the current context. If it can,
  2169. return the amount of the bytes with which period can match, otherwise
  2170. return 0.
  2171. `pos' is the position of the period. `index' is the index from the
  2172. buf_begin, and it is the current position in the buffer. */
  2173. static int
  2174. match_anychar (struct dfa *d, int s, position pos, int index)
  2175. {
  2176. int newline = 0;
  2177. int letter = 0;
  2178. wchar_t wc;
  2179. int mbclen;
  2180. wc = inputwcs[index];
  2181. mbclen = (mblen_buf[index] == 0)? 1 : mblen_buf[index];
  2182. /* Check context. */
  2183. if (wc == (wchar_t)eolbyte)
  2184. {
  2185. if (!(syntax_bits & RE_DOT_NEWLINE))
  2186. return 0;
  2187. newline = 1;
  2188. }
  2189. else if (wc == (wchar_t)'\0')
  2190. {
  2191. if (syntax_bits & RE_DOT_NOT_NULL)
  2192. return 0;
  2193. newline = 1;
  2194. }
  2195. if (iswalnum(wc) || wc == L'_')
  2196. letter = 1;
  2197. if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].newline,
  2198. newline, d->states[s].letter, letter))
  2199. return 0;
  2200. return mbclen;
  2201. }
  2202. /* Check whether bracket expression can match or not in the current context.
  2203. If it can, return the amount of the bytes with which expression can match,
  2204. otherwise return 0.
  2205. `pos' is the position of the bracket expression. `index' is the index
  2206. from the buf_begin, and it is the current position in the buffer. */
  2207. int
  2208. match_mb_charset (struct dfa *d, int s, position pos, int index)
  2209. {
  2210. int i;
  2211. int match; /* Flag which represent that matching succeed. */
  2212. int match_len; /* Length of the character (or collating element)
  2213. with which this operator match. */
  2214. int op_len; /* Length of the operator. */
  2215. char buffer[128];
  2216. wchar_t wcbuf[6];
  2217. /* Pointer to the structure to which we are currently reffering. */
  2218. struct mb_char_classes *work_mbc;
  2219. int newline = 0;
  2220. int letter = 0;
  2221. wchar_t wc; /* Current reffering character. */
  2222. wc = inputwcs[index];
  2223. /* Check context. */
  2224. if (wc == (wchar_t)eolbyte)
  2225. {
  2226. if (!(syntax_bits & RE_DOT_NEWLINE))
  2227. return 0;
  2228. newline = 1;
  2229. }
  2230. else if (wc == (wchar_t)'\0')
  2231. {
  2232. if (syntax_bits & RE_DOT_NOT_NULL)
  2233. return 0;
  2234. newline = 1;
  2235. }
  2236. if (iswalnum(wc) || wc == L'_')
  2237. letter = 1;
  2238. if (!SUCCEEDS_IN_CONTEXT(pos.constraint, d->states[s].newline,
  2239. newline, d->states[s].letter, letter))
  2240. return 0;
  2241. /* Assign the current reffering operator to work_mbc. */
  2242. work_mbc = &(d->mbcsets[(d->multibyte_prop[pos.index]) >> 2]);
  2243. match = !work_mbc->invert;
  2244. match_len = (mblen_buf[index] == 0)? 1 : mblen_buf[index];
  2245. /* match with a character class? */
  2246. for (i = 0; i<work_mbc->nch_classes; i++)
  2247. {
  2248. if (iswctype((wint_t)wc, work_mbc->ch_classes[i]))
  2249. goto charset_matched;
  2250. }
  2251. strncpy(buffer, buf_begin + index, match_len);
  2252. buffer[match_len] = '\0';
  2253. /* match with an equivalent class? */
  2254. for (i = 0; i<work_mbc->nequivs; i++)
  2255. {
  2256. op_len = strlen(work_mbc->equivs[i]);
  2257. strncpy(buffer, buf_begin + index, op_len);
  2258. buffer[op_len] = '\0';
  2259. if (strcoll(work_mbc->equivs[i], buffer) == 0)
  2260. {
  2261. match_len = op_len;
  2262. goto charset_matched;
  2263. }
  2264. }
  2265. /* match with a collating element? */
  2266. for (i = 0; i<work_mbc->ncoll_elems; i++)
  2267. {
  2268. op_len = strlen(work_mbc->coll_elems[i]);
  2269. strncpy(buffer, buf_begin + index, op_len);
  2270. buffer[op_len] = '\0';
  2271. if (strcoll(work_mbc->coll_elems[i], buffer) == 0)
  2272. {
  2273. match_len = op_len;
  2274. goto charset_matched;
  2275. }
  2276. }
  2277. wcbuf[0] = wc;
  2278. wcbuf[1] = wcbuf[3] = wcbuf[5] = '\0';
  2279. /* match with a range? */
  2280. for (i = 0; i<work_mbc->nranges; i++)
  2281. {
  2282. wcbuf[2] = work_mbc->range_sts[i];
  2283. wcbuf[4] = work_mbc->range_ends[i];
  2284. if (wcscoll(wcbuf, wcbuf+2) >= 0 &&
  2285. wcscoll(wcbuf+4, wcbuf) >= 0)
  2286. goto charset_matched;
  2287. }
  2288. /* match with a character? */
  2289. if (case_fold)
  2290. wc = towlower (wc);
  2291. for (i = 0; i<work_mbc->nchars; i++)
  2292. {
  2293. if (wc == work_mbc->chars[i])
  2294. goto charset_matched;
  2295. }
  2296. match = !match;
  2297. charset_matched:
  2298. return match ? match_len : 0;
  2299. }
  2300. /* Check each of `d->states[s].mbps.elem' can match or not. Then return the
  2301. array which corresponds to `d->states[s].mbps.elem' and each element of
  2302. the array contains the amount of the bytes with which the element can
  2303. match.
  2304. `index' is the index from the buf_begin, and it is the current position
  2305. in the buffer.
  2306. Caller MUST free the array which this function return. */
  2307. static int*
  2308. check_matching_with_multibyte_ops (struct dfa *d, int s, int index)
  2309. {
  2310. int i;
  2311. int* rarray;
  2312. MALLOC(rarray, int, d->states[s].mbps.nelem);
  2313. for (i = 0; i < d->states[s].mbps.nelem; ++i)
  2314. {
  2315. position pos = d->states[s].mbps.elems[i];
  2316. switch(d->tokens[pos.index])
  2317. {
  2318. case ANYCHAR:
  2319. rarray[i] = match_anychar(d, s, pos, index);
  2320. break;
  2321. case MBCSET:
  2322. rarray[i] = match_mb_charset(d, s, pos, index);
  2323. break;
  2324. default:
  2325. break; /* can not happen. */
  2326. }
  2327. }
  2328. return rarray;
  2329. }
  2330. /* Consume a single character and enumerate all of the positions which can
  2331. be next position from the state `s'.
  2332. `match_lens' is the input. It can be NULL, but it can also be the output
  2333. of check_matching_with_multibyte_ops() for optimization.
  2334. `mbclen' and `pps' are the output. `mbclen' is the length of the
  2335. character consumed, and `pps' is the set this function enumerate. */
  2336. static status_transit_state
  2337. transit_state_consume_1char (struct dfa *d, int s, unsigned char const **pp,
  2338. int *match_lens, int *mbclen, position_set *pps)
  2339. {
  2340. int i, j;
  2341. int s1, s2;
  2342. int* work_mbls;
  2343. status_transit_state rs = TRANSIT_STATE_DONE;
  2344. /* Calculate the length of the (single/multi byte) character
  2345. to which p points. */
  2346. *mbclen = (mblen_buf[*pp - buf_begin] == 0)? 1
  2347. : mblen_buf[*pp - buf_begin];
  2348. /* Calculate the state which can be reached from the state `s' by
  2349. consuming `*mbclen' single bytes from the buffer. */
  2350. s1 = s;
  2351. for (i = 0; i < *mbclen; i++)
  2352. {
  2353. s2 = s1;
  2354. rs = transit_state_singlebyte(d, s2, (*pp)++, &s1);
  2355. }
  2356. /* Copy the positions contained by `s1' to the set `pps'. */
  2357. copy(&(d->states[s1].elems), pps);
  2358. /* Check (inputed)match_lens, and initialize if it is NULL. */
  2359. if (match_lens == NULL && d->states[s].mbps.nelem != 0)
  2360. work_mbls = check_matching_with_multibyte_ops(d, s, *pp - buf_begin);
  2361. else
  2362. work_mbls = match_lens;
  2363. /* Add all of the positions which can be reached from `s' by consuming
  2364. a single character. */
  2365. for (i = 0; i < d->states[s].mbps.nelem ; i++)
  2366. {
  2367. if (work_mbls[i] == *mbclen)
  2368. for (j = 0; j < d->follows[d->states[s].mbps.elems[i].index].nelem;
  2369. j++)
  2370. insert(d->follows[d->states[s].mbps.elems[i].index].elems[j],
  2371. pps);
  2372. }
  2373. if (match_lens == NULL && work_mbls != NULL)
  2374. free(work_mbls);
  2375. return rs;
  2376. }
  2377. /* Transit state from s, then return new state and update the pointer of the
  2378. buffer. This function is for some operator which can match with a multi-
  2379. byte character or a collating element(which may be multi characters). */
  2380. static int
  2381. transit_state (struct dfa *d, int s, unsigned char const **pp)
  2382. {
  2383. int s1;
  2384. int mbclen; /* The length of current input multibyte character. */
  2385. int maxlen = 0;
  2386. int i, j;
  2387. int *match_lens = NULL;
  2388. int nelem = d->states[s].mbps.nelem; /* Just a alias. */
  2389. position_set follows;
  2390. unsigned char const *p1 = *pp;
  2391. status_transit_state rs;
  2392. wchar_t wc;
  2393. if (nelem > 0)
  2394. /* This state has (a) multibyte operator(s).
  2395. We check whether each of them can match or not. */
  2396. {
  2397. /* Note: caller must free the return value of this function. */
  2398. match_lens = check_matching_with_multibyte_ops(d, s, *pp - buf_begin);
  2399. for (i = 0; i < nelem; i++)
  2400. /* Search the operator which match the longest string,
  2401. in this state. */
  2402. {
  2403. if (match_lens[i] > maxlen)
  2404. maxlen = match_lens[i];
  2405. }
  2406. }
  2407. if (nelem == 0 || maxlen == 0)
  2408. /* This state has no multibyte operator which can match.
  2409. We need to check only one singlebyte character. */
  2410. {
  2411. status_transit_state rs;
  2412. rs = transit_state_singlebyte(d, s, *pp, &s1);
  2413. /* We must update the pointer if state transition succeeded. */
  2414. if (rs == TRANSIT_STATE_DONE)
  2415. ++*pp;
  2416. if (match_lens != NULL)
  2417. free(match_lens);
  2418. return s1;
  2419. }
  2420. /* This state has some operators which can match a multibyte character. */
  2421. follows.nelem = 0;
  2422. MALLOC(follows.elems, position, d->nleaves);
  2423. /* `maxlen' may be longer than the length of a character, because it may
  2424. not be a character but a (multi character) collating element.
  2425. We enumerate all of the positions which `s' can reach by consuming
  2426. `maxlen' bytes. */
  2427. rs = transit_state_consume_1char(d, s, pp, match_lens, &mbclen, &follows);
  2428. wc = inputwcs[*pp - mbclen - buf_begin];
  2429. s1 = state_index(d, &follows, wc == L'\n', iswalnum(wc));
  2430. realloc_trans_if_necessary(d, s1);
  2431. while (*pp - p1 < maxlen)
  2432. {
  2433. follows.nelem = 0;
  2434. rs = transit_state_consume_1char(d, s1, pp, NULL, &mbclen, &follows);
  2435. for (i = 0; i < nelem ; i++)
  2436. {
  2437. if (match_lens[i] == *pp - p1)
  2438. for (j = 0;
  2439. j < d->follows[d->states[s1].mbps.elems[i].index].nelem; j++)
  2440. insert(d->follows[d->states[s1].mbps.elems[i].index].elems[j],
  2441. &follows);
  2442. }
  2443. wc = inputwcs[*pp - mbclen - buf_begin];
  2444. s1 = state_index(d, &follows, wc == L'\n', iswalnum(wc));
  2445. realloc_trans_if_necessary(d, s1);
  2446. }
  2447. free(match_lens);
  2448. free(follows.elems);
  2449. return s1;
  2450. }
  2451. #endif
  2452. /* Search through a buffer looking for a match to the given struct dfa.
  2453. Find the first occurrence of a string matching the regexp in the buffer,
  2454. and the shortest possible version thereof. Return the offset of the first
  2455. character after the match, or (size_t) -1 if none is found. BEGIN points to
  2456. the beginning of the buffer, and SIZE is the size of the buffer. If SIZE
  2457. is nonzero, BEGIN[SIZE - 1] must be a newline. BACKREF points to a place
  2458. where we're supposed to store a 1 if backreferencing happened and the
  2459. match needs to be verified by a backtracking matcher. Otherwise
  2460. we store a 0 in *backref. */
  2461. size_t
  2462. dfaexec (struct dfa *d, char const *begin, size_t size, int *backref)
  2463. {
  2464. register int s; /* Current state. */
  2465. register unsigned char const *p; /* Current input character. */
  2466. register unsigned char const *end; /* One past the last input character. */
  2467. register int **trans, *t; /* Copy of d->trans so it can be optimized
  2468. into a register. */
  2469. register unsigned char eol = eolbyte; /* Likewise for eolbyte. */
  2470. static int sbit[NOTCHAR]; /* Table for anding with d->success. */
  2471. static int sbit_init;
  2472. if (! sbit_init)
  2473. {
  2474. int i;
  2475. sbit_init = 1;
  2476. for (i = 0; i < NOTCHAR; ++i)
  2477. sbit[i] = (IS_WORD_CONSTITUENT(i)) ? 2 : 1;
  2478. sbit[eol] = 4;
  2479. }
  2480. if (! d->tralloc)
  2481. build_state_zero(d);
  2482. s = 0;
  2483. p = (unsigned char const *) begin;
  2484. end = p + size;
  2485. trans = d->trans;
  2486. #ifdef MBS_SUPPORT
  2487. if (MB_CUR_MAX > 1)
  2488. {
  2489. int remain_bytes, i;
  2490. buf_begin = begin;
  2491. buf_end = end;
  2492. /* initialize mblen_buf, and inputwcs. */
  2493. MALLOC(mblen_buf, unsigned char, end - (unsigned char const *)begin + 2);
  2494. MALLOC(inputwcs, wchar_t, end - (unsigned char const *)begin + 2);
  2495. memset(&mbs, 0, sizeof(mbstate_t));
  2496. remain_bytes = 0;
  2497. for (i = 0; i < end - (unsigned char const *)begin + 1; i++)
  2498. {
  2499. if (remain_bytes == 0)
  2500. {
  2501. remain_bytes
  2502. = mbrtowc(inputwcs + i, begin + i,
  2503. end - (unsigned char const *)begin - i + 1, &mbs);
  2504. if (remain_bytes <= 1)
  2505. {
  2506. remain_bytes = 0;
  2507. inputwcs[i] = (wchar_t)begin[i];
  2508. mblen_buf[i] = 0;
  2509. }
  2510. else
  2511. {
  2512. mblen_buf[i] = remain_bytes;
  2513. remain_bytes--;
  2514. }
  2515. }
  2516. else
  2517. {
  2518. mblen_buf[i] = remain_bytes;
  2519. inputwcs[i] = 0;
  2520. remain_bytes--;
  2521. }
  2522. }
  2523. mblen_buf[i] = 0;
  2524. inputwcs[i] = 0; /* sentinel */
  2525. }
  2526. #endif /* MBS_SUPPORT */
  2527. for (;;)
  2528. {
  2529. #ifdef MBS_SUPPORT
  2530. if (MB_CUR_MAX > 1)
  2531. while ((t = trans[s]))
  2532. {
  2533. if (d->states[s].mbps.nelem != 0)
  2534. {
  2535. /* Can match with a multibyte character( and multi character
  2536. collating element). */
  2537. unsigned char const *nextp;
  2538. SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p);
  2539. nextp = p;
  2540. s = transit_state(d, s, &nextp);
  2541. p = nextp;
  2542. /* Trans table might be updated. */
  2543. trans = d->trans;
  2544. }
  2545. else
  2546. {
  2547. SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p);
  2548. s = t[*p++];
  2549. }
  2550. }
  2551. else
  2552. #endif /* MBS_SUPPORT */
  2553. while ((t = trans[s]))
  2554. s = t[*p++];
  2555. if (s < 0)
  2556. {
  2557. if (p == end)
  2558. {
  2559. #ifdef MBS_SUPPORT
  2560. if (MB_CUR_MAX > 1)
  2561. {
  2562. free(mblen_buf);
  2563. free(inputwcs);
  2564. }
  2565. #endif /* MBS_SUPPORT */
  2566. return (size_t) -1;
  2567. }
  2568. s = 0;
  2569. }
  2570. else if ((t = d->fails[s]))
  2571. {
  2572. if (d->success[s] & sbit[*p])
  2573. {
  2574. if (backref)
  2575. *backref = (d->states[s].backref != 0);
  2576. #ifdef MBS_SUPPORT
  2577. if (MB_CUR_MAX > 1)
  2578. {
  2579. free(mblen_buf);
  2580. free(inputwcs);
  2581. }
  2582. #endif /* MBS_SUPPORT */
  2583. return (char const *) p - begin;
  2584. }
  2585. #ifdef MBS_SUPPORT
  2586. if (MB_CUR_MAX > 1)
  2587. {
  2588. SKIP_REMAINS_MB_IF_INITIAL_STATE(s, p);
  2589. if (d->states[s].mbps.nelem != 0)
  2590. {
  2591. /* Can match with a multibyte character( and multi
  2592. character collating element). */
  2593. unsigned char const *nextp;
  2594. nextp = p;
  2595. s = transit_state(d, s, &nextp);
  2596. p = nextp;
  2597. /* Trans table might be updated. */
  2598. trans = d->trans;
  2599. }
  2600. else
  2601. s = t[*p++];
  2602. }
  2603. else
  2604. #endif /* MBS_SUPPORT */
  2605. s = t[*p++];
  2606. }
  2607. else
  2608. {
  2609. build_state(s, d);
  2610. trans = d->trans;
  2611. }
  2612. }
  2613. }
  2614. /* Initialize the components of a dfa that the other routines don't
  2615. initialize for themselves. */
  2616. void
  2617. dfainit (struct dfa *d)
  2618. {
  2619. d->calloc = 1;
  2620. MALLOC(d->charclasses, charclass, d->calloc);
  2621. d->cindex = 0;
  2622. d->talloc = 1;
  2623. MALLOC(d->tokens, token, d->talloc);
  2624. d->tindex = d->depth = d->nleaves = d->nregexps = 0;
  2625. #ifdef MBS_SUPPORT
  2626. if (MB_CUR_MAX > 1)
  2627. {
  2628. d->nmultibyte_prop = 1;
  2629. MALLOC(d->multibyte_prop, int, d->nmultibyte_prop);
  2630. d->nmbcsets = 0;
  2631. d->mbcsets_alloc = 1;
  2632. MALLOC(d->mbcsets, struct mb_char_classes, d->mbcsets_alloc);
  2633. }
  2634. #endif
  2635. d->searchflag = 0;
  2636. d->tralloc = 0;
  2637. d->musts = 0;
  2638. }
  2639. /* Parse and analyze a single string of the given length. */
  2640. void
  2641. dfacomp (char const *s, size_t len, struct dfa *d, int searchflag)
  2642. {
  2643. if (case_fold) /* dummy folding in service of dfamust() */
  2644. {
  2645. char *lcopy;
  2646. int i;
  2647. lcopy = malloc(len);
  2648. if (!lcopy)
  2649. dfaerror(_("out of memory"));
  2650. /* This is a kludge. */
  2651. case_fold = 0;
  2652. for (i = 0; i < len; ++i)
  2653. if (ISUPPER ((unsigned char) s[i]))
  2654. lcopy[i] = tolower ((unsigned char) s[i]);
  2655. else
  2656. lcopy[i] = s[i];
  2657. dfainit(d);
  2658. dfaparse(lcopy, len, d);
  2659. free(lcopy);
  2660. dfamust(d);
  2661. d->cindex = d->tindex = d->depth = d->nleaves = d->nregexps = 0;
  2662. case_fold = 1;
  2663. dfaparse(s, len, d);
  2664. dfaanalyze(d, searchflag);
  2665. }
  2666. else
  2667. {
  2668. dfainit(d);
  2669. dfaparse(s, len, d);
  2670. dfamust(d);
  2671. dfaanalyze(d, searchflag);
  2672. }
  2673. }
  2674. /* Free the storage held by the components of a dfa. */
  2675. void
  2676. dfafree (struct dfa *d)
  2677. {
  2678. int i;
  2679. struct dfamust *dm, *ndm;
  2680. free((ptr_t) d->charclasses);
  2681. free((ptr_t) d->tokens);
  2682. #ifdef MBS_SUPPORT
  2683. if (MB_CUR_MAX > 1)
  2684. {
  2685. free((ptr_t) d->multibyte_prop);
  2686. for (i = 0; i < d->nmbcsets; ++i)
  2687. {
  2688. int j;
  2689. struct mb_char_classes *p = &(d->mbcsets[i]);
  2690. if (p->chars != NULL)
  2691. free(p->chars);
  2692. if (p->ch_classes != NULL)
  2693. free(p->ch_classes);
  2694. if (p->range_sts != NULL)
  2695. free(p->range_sts);
  2696. if (p->range_ends != NULL)
  2697. free(p->range_ends);
  2698. for (j = 0; j < p->nequivs; ++j)
  2699. free(p->equivs[j]);
  2700. if (p->equivs != NULL)
  2701. free(p->equivs);
  2702. for (j = 0; j < p->ncoll_elems; ++j)
  2703. free(p->coll_elems[j]);
  2704. if (p->coll_elems != NULL)
  2705. free(p->coll_elems);
  2706. }
  2707. free((ptr_t) d->mbcsets);
  2708. }
  2709. #endif /* MBS_SUPPORT */
  2710. for (i = 0; i < d->sindex; ++i)
  2711. free((ptr_t) d->states[i].elems.elems);
  2712. free((ptr_t) d->states);
  2713. for (i = 0; i < d->tindex; ++i)
  2714. if (d->follows[i].elems)
  2715. free((ptr_t) d->follows[i].elems);
  2716. free((ptr_t) d->follows);
  2717. for (i = 0; i < d->tralloc; ++i)
  2718. if (d->trans[i])
  2719. free((ptr_t) d->trans[i]);
  2720. else if (d->fails[i])
  2721. free((ptr_t) d->fails[i]);
  2722. if (d->realtrans) free((ptr_t) d->realtrans);
  2723. if (d->fails) free((ptr_t) d->fails);
  2724. if (d->success) free((ptr_t) d->success);
  2725. for (dm = d->musts; dm; dm = ndm)
  2726. {
  2727. ndm = dm->next;
  2728. free(dm->must);
  2729. free((ptr_t) dm);
  2730. }
  2731. }
  2732. /* Having found the postfix representation of the regular expression,
  2733. try to find a long sequence of characters that must appear in any line
  2734. containing the r.e.
  2735. Finding a "longest" sequence is beyond the scope here;
  2736. we take an easy way out and hope for the best.
  2737. (Take "(ab|a)b"--please.)
  2738. We do a bottom-up calculation of sequences of characters that must appear
  2739. in matches of r.e.'s represented by trees rooted at the nodes of the postfix
  2740. representation:
  2741. sequences that must appear at the left of the match ("left")
  2742. sequences that must appear at the right of the match ("right")
  2743. lists of sequences that must appear somewhere in the match ("in")
  2744. sequences that must constitute the match ("is")
  2745. When we get to the root of the tree, we use one of the longest of its
  2746. calculated "in" sequences as our answer. The sequence we find is returned in
  2747. d->must (where "d" is the single argument passed to "dfamust");
  2748. the length of the sequence is returned in d->mustn.
  2749. The sequences calculated for the various types of node (in pseudo ANSI c)
  2750. are shown below. "p" is the operand of unary operators (and the left-hand
  2751. operand of binary operators); "q" is the right-hand operand of binary
  2752. operators.
  2753. "ZERO" means "a zero-length sequence" below.
  2754. Type left right is in
  2755. ---- ---- ----- -- --
  2756. char c # c # c # c # c
  2757. ANYCHAR ZERO ZERO ZERO ZERO
  2758. MBCSET ZERO ZERO ZERO ZERO
  2759. CSET ZERO ZERO ZERO ZERO
  2760. STAR ZERO ZERO ZERO ZERO
  2761. QMARK ZERO ZERO ZERO ZERO
  2762. PLUS p->left p->right ZERO p->in
  2763. CAT (p->is==ZERO)? (q->is==ZERO)? (p->is!=ZERO && p->in plus
  2764. p->left : q->right : q->is!=ZERO) ? q->in plus
  2765. p->is##q->left p->right##q->is p->is##q->is : p->right##q->left
  2766. ZERO
  2767. OR longest common longest common (do p->is and substrings common to
  2768. leading trailing q->is have same p->in and q->in
  2769. (sub)sequence (sub)sequence length and
  2770. of p->left of p->right content) ?
  2771. and q->left and q->right p->is : NULL
  2772. If there's anything else we recognize in the tree, all four sequences get set
  2773. to zero-length sequences. If there's something we don't recognize in the tree,
  2774. we just return a zero-length sequence.
  2775. Break ties in favor of infrequent letters (choosing 'zzz' in preference to
  2776. 'aaa')?
  2777. And. . .is it here or someplace that we might ponder "optimizations" such as
  2778. egrep 'psi|epsilon' -> egrep 'psi'
  2779. egrep 'pepsi|epsilon' -> egrep 'epsi'
  2780. (Yes, we now find "epsi" as a "string
  2781. that must occur", but we might also
  2782. simplify the *entire* r.e. being sought)
  2783. grep '[c]' -> grep 'c'
  2784. grep '(ab|a)b' -> grep 'ab'
  2785. grep 'ab*' -> grep 'a'
  2786. grep 'a*b' -> grep 'b'
  2787. There are several issues:
  2788. Is optimization easy (enough)?
  2789. Does optimization actually accomplish anything,
  2790. or is the automaton you get from "psi|epsilon" (for example)
  2791. the same as the one you get from "psi" (for example)?
  2792. Are optimizable r.e.'s likely to be used in real-life situations
  2793. (something like 'ab*' is probably unlikely; something like is
  2794. 'psi|epsilon' is likelier)? */
  2795. static char *
  2796. icatalloc (char *old, char *new)
  2797. {
  2798. char *result;
  2799. size_t oldsize, newsize;
  2800. newsize = (new == NULL) ? 0 : strlen(new);
  2801. if (old == NULL)
  2802. oldsize = 0;
  2803. else if (newsize == 0)
  2804. return old;
  2805. else oldsize = strlen(old);
  2806. if (old == NULL)
  2807. result = (char *) malloc(newsize + 1);
  2808. else
  2809. result = (char *) realloc((void *) old, oldsize + newsize + 1);
  2810. if (result != NULL && new != NULL)
  2811. (void) strcpy(result + oldsize, new);
  2812. return result;
  2813. }
  2814. static char *
  2815. icpyalloc (char *string)
  2816. {
  2817. return icatalloc((char *) NULL, string);
  2818. }
  2819. static char *
  2820. istrstr (char *lookin, char *lookfor)
  2821. {
  2822. char *cp;
  2823. size_t len;
  2824. len = strlen(lookfor);
  2825. for (cp = lookin; *cp != '\0'; ++cp)
  2826. if (strncmp(cp, lookfor, len) == 0)
  2827. return cp;
  2828. return NULL;
  2829. }
  2830. static void
  2831. ifree (char *cp)
  2832. {
  2833. if (cp != NULL)
  2834. free(cp);
  2835. }
  2836. static void
  2837. freelist (char **cpp)
  2838. {
  2839. int i;
  2840. if (cpp == NULL)
  2841. return;
  2842. for (i = 0; cpp[i] != NULL; ++i)
  2843. {
  2844. free(cpp[i]);
  2845. cpp[i] = NULL;
  2846. }
  2847. }
  2848. static char **
  2849. enlist (char **cpp, char *new, size_t len)
  2850. {
  2851. int i, j;
  2852. if (cpp == NULL)
  2853. return NULL;
  2854. if ((new = icpyalloc(new)) == NULL)
  2855. {
  2856. freelist(cpp);
  2857. return NULL;
  2858. }
  2859. new[len] = '\0';
  2860. /* Is there already something in the list that's new (or longer)? */
  2861. for (i = 0; cpp[i] != NULL; ++i)
  2862. if (istrstr(cpp[i], new) != NULL)
  2863. {
  2864. free(new);
  2865. return cpp;
  2866. }
  2867. /* Eliminate any obsoleted strings. */
  2868. j = 0;
  2869. while (cpp[j] != NULL)
  2870. if (istrstr(new, cpp[j]) == NULL)
  2871. ++j;
  2872. else
  2873. {
  2874. free(cpp[j]);
  2875. if (--i == j)
  2876. break;
  2877. cpp[j] = cpp[i];
  2878. cpp[i] = NULL;
  2879. }
  2880. /* Add the new string. */
  2881. cpp = (char **) realloc((char *) cpp, (i + 2) * sizeof *cpp);
  2882. if (cpp == NULL)
  2883. return NULL;
  2884. cpp[i] = new;
  2885. cpp[i + 1] = NULL;
  2886. return cpp;
  2887. }
  2888. /* Given pointers to two strings, return a pointer to an allocated
  2889. list of their distinct common substrings. Return NULL if something
  2890. seems wild. */
  2891. static char **
  2892. comsubs (char *left, char *right)
  2893. {
  2894. char **cpp;
  2895. char *lcp;
  2896. char *rcp;
  2897. size_t i, len;
  2898. if (left == NULL || right == NULL)
  2899. return NULL;
  2900. cpp = (char **) malloc(sizeof *cpp);
  2901. if (cpp == NULL)
  2902. return NULL;
  2903. cpp[0] = NULL;
  2904. for (lcp = left; *lcp != '\0'; ++lcp)
  2905. {
  2906. len = 0;
  2907. rcp = strchr (right, *lcp);
  2908. while (rcp != NULL)
  2909. {
  2910. for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i)
  2911. continue;
  2912. if (i > len)
  2913. len = i;
  2914. rcp = strchr (rcp + 1, *lcp);
  2915. }
  2916. if (len == 0)
  2917. continue;
  2918. if ((cpp = enlist(cpp, lcp, len)) == NULL)
  2919. break;
  2920. }
  2921. return cpp;
  2922. }
  2923. static char **
  2924. addlists (char **old, char **new)
  2925. {
  2926. int i;
  2927. if (old == NULL || new == NULL)
  2928. return NULL;
  2929. for (i = 0; new[i] != NULL; ++i)
  2930. {
  2931. old = enlist(old, new[i], strlen(new[i]));
  2932. if (old == NULL)
  2933. break;
  2934. }
  2935. return old;
  2936. }
  2937. /* Given two lists of substrings, return a new list giving substrings
  2938. common to both. */
  2939. static char **
  2940. inboth (char **left, char **right)
  2941. {
  2942. char **both;
  2943. char **temp;
  2944. int lnum, rnum;
  2945. if (left == NULL || right == NULL)
  2946. return NULL;
  2947. both = (char **) malloc(sizeof *both);
  2948. if (both == NULL)
  2949. return NULL;
  2950. both[0] = NULL;
  2951. for (lnum = 0; left[lnum] != NULL; ++lnum)
  2952. {
  2953. for (rnum = 0; right[rnum] != NULL; ++rnum)
  2954. {
  2955. temp = comsubs(left[lnum], right[rnum]);
  2956. if (temp == NULL)
  2957. {
  2958. freelist(both);
  2959. return NULL;
  2960. }
  2961. both = addlists(both, temp);
  2962. freelist(temp);
  2963. free(temp);
  2964. if (both == NULL)
  2965. return NULL;
  2966. }
  2967. }
  2968. return both;
  2969. }
  2970. typedef struct
  2971. {
  2972. char **in;
  2973. char *left;
  2974. char *right;
  2975. char *is;
  2976. } must;
  2977. static void
  2978. resetmust (must *mp)
  2979. {
  2980. mp->left[0] = mp->right[0] = mp->is[0] = '\0';
  2981. freelist(mp->in);
  2982. }
  2983. static void
  2984. dfamust (struct dfa *dfa)
  2985. {
  2986. must *musts;
  2987. must *mp;
  2988. char *result;
  2989. int ri;
  2990. int i;
  2991. int exact;
  2992. token t;
  2993. static must must0;
  2994. struct dfamust *dm;
  2995. static char empty_string[] = "";
  2996. result = empty_string;
  2997. exact = 0;
  2998. musts = (must *) malloc((dfa->tindex + 1) * sizeof *musts);
  2999. if (musts == NULL)
  3000. return;
  3001. mp = musts;
  3002. for (i = 0; i <= dfa->tindex; ++i)
  3003. mp[i] = must0;
  3004. for (i = 0; i <= dfa->tindex; ++i)
  3005. {
  3006. mp[i].in = (char **) malloc(sizeof *mp[i].in);
  3007. mp[i].left = malloc(2);
  3008. mp[i].right = malloc(2);
  3009. mp[i].is = malloc(2);
  3010. if (mp[i].in == NULL || mp[i].left == NULL ||
  3011. mp[i].right == NULL || mp[i].is == NULL)
  3012. goto done;
  3013. mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
  3014. mp[i].in[0] = NULL;
  3015. }
  3016. #ifdef DEBUG
  3017. fprintf(stderr, "dfamust:\n");
  3018. for (i = 0; i < dfa->tindex; ++i)
  3019. {
  3020. fprintf(stderr, " %d:", i);
  3021. prtok(dfa->tokens[i]);
  3022. }
  3023. putc('\n', stderr);
  3024. #endif
  3025. for (ri = 0; ri < dfa->tindex; ++ri)
  3026. {
  3027. switch (t = dfa->tokens[ri])
  3028. {
  3029. case LPAREN:
  3030. case RPAREN:
  3031. goto done; /* "cannot happen" */
  3032. case EMPTY:
  3033. case BEGLINE:
  3034. case ENDLINE:
  3035. case BEGWORD:
  3036. case ENDWORD:
  3037. case LIMWORD:
  3038. case NOTLIMWORD:
  3039. case BACKREF:
  3040. resetmust(mp);
  3041. break;
  3042. case STAR:
  3043. case QMARK:
  3044. if (mp <= musts)
  3045. goto done; /* "cannot happen" */
  3046. --mp;
  3047. resetmust(mp);
  3048. break;
  3049. case OR:
  3050. case ORTOP:
  3051. if (mp < &musts[2])
  3052. goto done; /* "cannot happen" */
  3053. {
  3054. char **new;
  3055. must *lmp;
  3056. must *rmp;
  3057. int j, ln, rn, n;
  3058. rmp = --mp;
  3059. lmp = --mp;
  3060. /* Guaranteed to be. Unlikely, but. . . */
  3061. if (strcmp(lmp->is, rmp->is) != 0)
  3062. lmp->is[0] = '\0';
  3063. /* Left side--easy */
  3064. i = 0;
  3065. while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i])
  3066. ++i;
  3067. lmp->left[i] = '\0';
  3068. /* Right side */
  3069. ln = strlen(lmp->right);
  3070. rn = strlen(rmp->right);
  3071. n = ln;
  3072. if (n > rn)
  3073. n = rn;
  3074. for (i = 0; i < n; ++i)
  3075. if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1])
  3076. break;
  3077. for (j = 0; j < i; ++j)
  3078. lmp->right[j] = lmp->right[(ln - i) + j];
  3079. lmp->right[j] = '\0';
  3080. new = inboth(lmp->in, rmp->in);
  3081. if (new == NULL)
  3082. goto done;
  3083. freelist(lmp->in);
  3084. free((char *) lmp->in);
  3085. lmp->in = new;
  3086. }
  3087. break;
  3088. case PLUS:
  3089. if (mp <= musts)
  3090. goto done; /* "cannot happen" */
  3091. --mp;
  3092. mp->is[0] = '\0';
  3093. break;
  3094. case END:
  3095. if (mp != &musts[1])
  3096. goto done; /* "cannot happen" */
  3097. for (i = 0; musts[0].in[i] != NULL; ++i)
  3098. if (strlen(musts[0].in[i]) > strlen(result))
  3099. result = musts[0].in[i];
  3100. if (strcmp(result, musts[0].is) == 0)
  3101. exact = 1;
  3102. goto done;
  3103. case CAT:
  3104. if (mp < &musts[2])
  3105. goto done; /* "cannot happen" */
  3106. {
  3107. must *lmp;
  3108. must *rmp;
  3109. rmp = --mp;
  3110. lmp = --mp;
  3111. /* In. Everything in left, plus everything in
  3112. right, plus catenation of
  3113. left's right and right's left. */
  3114. lmp->in = addlists(lmp->in, rmp->in);
  3115. if (lmp->in == NULL)
  3116. goto done;
  3117. if (lmp->right[0] != '\0' &&
  3118. rmp->left[0] != '\0')
  3119. {
  3120. char *tp;
  3121. tp = icpyalloc(lmp->right);
  3122. if (tp == NULL)
  3123. goto done;
  3124. tp = icatalloc(tp, rmp->left);
  3125. if (tp == NULL)
  3126. goto done;
  3127. lmp->in = enlist(lmp->in, tp,
  3128. strlen(tp));
  3129. free(tp);
  3130. if (lmp->in == NULL)
  3131. goto done;
  3132. }
  3133. /* Left-hand */
  3134. if (lmp->is[0] != '\0')
  3135. {
  3136. lmp->left = icatalloc(lmp->left,
  3137. rmp->left);
  3138. if (lmp->left == NULL)
  3139. goto done;
  3140. }
  3141. /* Right-hand */
  3142. if (rmp->is[0] == '\0')
  3143. lmp->right[0] = '\0';
  3144. lmp->right = icatalloc(lmp->right, rmp->right);
  3145. if (lmp->right == NULL)
  3146. goto done;
  3147. /* Guaranteed to be */
  3148. if (lmp->is[0] != '\0' && rmp->is[0] != '\0')
  3149. {
  3150. lmp->is = icatalloc(lmp->is, rmp->is);
  3151. if (lmp->is == NULL)
  3152. goto done;
  3153. }
  3154. else
  3155. lmp->is[0] = '\0';
  3156. }
  3157. break;
  3158. default:
  3159. if (t < END)
  3160. {
  3161. /* "cannot happen" */
  3162. goto done;
  3163. }
  3164. else if (t == '\0')
  3165. {
  3166. /* not on *my* shift */
  3167. goto done;
  3168. }
  3169. else if (t >= CSET
  3170. #ifdef MBS_SUPPORT
  3171. || t == ANYCHAR
  3172. || t == MBCSET
  3173. #endif /* MBS_SUPPORT */
  3174. )
  3175. {
  3176. /* easy enough */
  3177. resetmust(mp);
  3178. }
  3179. else
  3180. {
  3181. /* plain character */
  3182. resetmust(mp);
  3183. mp->is[0] = mp->left[0] = mp->right[0] = t;
  3184. mp->is[1] = mp->left[1] = mp->right[1] = '\0';
  3185. mp->in = enlist(mp->in, mp->is, (size_t)1);
  3186. if (mp->in == NULL)
  3187. goto done;
  3188. }
  3189. break;
  3190. }
  3191. #ifdef DEBUG
  3192. fprintf(stderr, " node: %d:", ri);
  3193. prtok(dfa->tokens[ri]);
  3194. fprintf(stderr, "\n in:");
  3195. for (i = 0; mp->in[i]; ++i)
  3196. fprintf(stderr, " \"%s\"", mp->in[i]);
  3197. fprintf(stderr, "\n is: \"%s\"\n", mp->is);
  3198. fprintf(stderr, " left: \"%s\"\n", mp->left);
  3199. fprintf(stderr, " right: \"%s\"\n", mp->right);
  3200. #endif
  3201. ++mp;
  3202. }
  3203. done:
  3204. if (strlen(result))
  3205. {
  3206. dm = (struct dfamust *) malloc(sizeof (struct dfamust));
  3207. dm->exact = exact;
  3208. dm->must = malloc(strlen(result) + 1);
  3209. strcpy(dm->must, result);
  3210. dm->next = dfa->musts;
  3211. dfa->musts = dm;
  3212. }
  3213. mp = musts;
  3214. for (i = 0; i <= dfa->tindex; ++i)
  3215. {
  3216. freelist(mp[i].in);
  3217. ifree((char *) mp[i].in);
  3218. ifree(mp[i].left);
  3219. ifree(mp[i].right);
  3220. ifree(mp[i].is);
  3221. }
  3222. free((char *) mp);
  3223. }
  3224. /* vim:set shiftwidth=2: */