PageRenderTime 48ms CodeModel.GetById 10ms 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

Large files files are truncated, but you can click here to view the full file

  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] == MBCSE

Large files files are truncated, but you can click here to view the full file