PageRenderTime 64ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/nbsd_libc/regex/regcomp.c

http://github.com/vivekp/minix-nbsd
C | 1902 lines | 1352 code | 207 blank | 343 comment | 382 complexity | e2375ed9debc1c5ae9df78e34d157768 MD5 | raw file
Possible License(s): AGPL-1.0, BSD-3-Clause
  1. /* $NetBSD: regcomp.c,v 1.29 2009/02/12 05:06:54 lukem Exp $ */
  2. /*-
  3. * Copyright (c) 1992, 1993, 1994
  4. * The Regents of the University of California. All rights reserved.
  5. *
  6. * This code is derived from software contributed to Berkeley by
  7. * Henry Spencer.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in the
  16. * documentation and/or other materials provided with the distribution.
  17. * 3. Neither the name of the University nor the names of its contributors
  18. * may be used to endorse or promote products derived from this software
  19. * without specific prior written permission.
  20. *
  21. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  22. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  25. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. * SUCH DAMAGE.
  32. *
  33. * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
  34. */
  35. /*-
  36. * Copyright (c) 1992, 1993, 1994 Henry Spencer.
  37. *
  38. * This code is derived from software contributed to Berkeley by
  39. * Henry Spencer.
  40. *
  41. * Redistribution and use in source and binary forms, with or without
  42. * modification, are permitted provided that the following conditions
  43. * are met:
  44. * 1. Redistributions of source code must retain the above copyright
  45. * notice, this list of conditions and the following disclaimer.
  46. * 2. Redistributions in binary form must reproduce the above copyright
  47. * notice, this list of conditions and the following disclaimer in the
  48. * documentation and/or other materials provided with the distribution.
  49. * 3. All advertising materials mentioning features or use of this software
  50. * must display the following acknowledgement:
  51. * This product includes software developed by the University of
  52. * California, Berkeley and its contributors.
  53. * 4. Neither the name of the University nor the names of its contributors
  54. * may be used to endorse or promote products derived from this software
  55. * without specific prior written permission.
  56. *
  57. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  58. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  59. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  60. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  61. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  62. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  63. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  64. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  65. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  66. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  67. * SUCH DAMAGE.
  68. *
  69. * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
  70. */
  71. #include <sys/cdefs.h>
  72. #if defined(LIBC_SCCS) && !defined(lint)
  73. #if 0
  74. static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
  75. #else
  76. __RCSID("$NetBSD: regcomp.c,v 1.29 2009/02/12 05:06:54 lukem Exp $");
  77. #endif
  78. #endif /* LIBC_SCCS and not lint */
  79. #include "namespace.h"
  80. #include <sys/types.h>
  81. #include <assert.h>
  82. #include <ctype.h>
  83. #include <limits.h>
  84. #include <stdio.h>
  85. #include <stdlib.h>
  86. #include <string.h>
  87. #include <regex.h>
  88. #ifdef __weak_alias
  89. __weak_alias(regcomp,_regcomp)
  90. #endif
  91. #include "utils.h"
  92. #include "regex2.h"
  93. #include "cclass.h"
  94. #include "cname.h"
  95. /*
  96. * parse structure, passed up and down to avoid global variables and
  97. * other clumsinesses
  98. */
  99. struct parse {
  100. const char *next; /* next character in RE */
  101. const char *end; /* end of string (-> NUL normally) */
  102. int error; /* has an error been seen? */
  103. sop *strip; /* malloced strip */
  104. sopno ssize; /* malloced strip size (allocated) */
  105. sopno slen; /* malloced strip length (used) */
  106. int ncsalloc; /* number of csets allocated */
  107. struct re_guts *g;
  108. # define NPAREN 10 /* we need to remember () 1-9 for back refs */
  109. sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
  110. sopno pend[NPAREN]; /* -> ) ([0] unused) */
  111. };
  112. /* ========= begin header generated by ./mkh ========= */
  113. #ifdef __cplusplus
  114. extern "C" {
  115. #endif
  116. /* === regcomp.c === */
  117. static void p_ere(struct parse *p, int stop);
  118. static void p_ere_exp(struct parse *p);
  119. static void p_str(struct parse *p);
  120. static void p_bre(struct parse *p, int end1, int end2);
  121. static int p_simp_re(struct parse *p, int starordinary);
  122. static int p_count(struct parse *p);
  123. static void p_bracket(struct parse *p);
  124. static void p_b_term(struct parse *p, cset *cs);
  125. static void p_b_cclass(struct parse *p, cset *cs);
  126. static void p_b_eclass(struct parse *p, cset *cs);
  127. static char p_b_symbol(struct parse *p);
  128. static char p_b_coll_elem(struct parse *p, int endc);
  129. static int othercase(int ch);
  130. static void bothcases(struct parse *p, int ch);
  131. static void ordinary(struct parse *p, int ch);
  132. static void nonnewline(struct parse *p);
  133. static void repeat(struct parse *p, sopno start, int from, int to);
  134. static int seterr(struct parse *p, int e);
  135. static cset *allocset(struct parse *p);
  136. static void freeset(struct parse *p, cset *cs);
  137. static int freezeset(struct parse *p, cset *cs);
  138. static int firstch(struct parse *p, cset *cs);
  139. static int nch(struct parse *p, cset *cs);
  140. static void mcadd(struct parse *p, cset *cs, const char *cp);
  141. #if 0
  142. static void mcsub(cset *cs, char *cp);
  143. static int mcin(cset *cs, char *cp);
  144. static char *mcfind(cset *cs, char *cp);
  145. #endif
  146. static void mcinvert(struct parse *p, cset *cs);
  147. static void mccase(struct parse *p, cset *cs);
  148. static int isinsets(struct re_guts *g, int c);
  149. static int samesets(struct re_guts *g, int c1, int c2);
  150. static void categorize(struct parse *p, struct re_guts *g);
  151. static sopno dupl(struct parse *p, sopno start, sopno finish);
  152. static void doemit(struct parse *p, sop op, sopno opnd);
  153. static void doinsert(struct parse *p, sop op, sopno opnd, sopno pos);
  154. static void dofwd(struct parse *p, sopno pos, sopno value);
  155. static void enlarge(struct parse *p, sopno size);
  156. static void stripsnug(struct parse *p, struct re_guts *g);
  157. static void findmust(struct parse *p, struct re_guts *g);
  158. static sopno pluscount(struct parse *p, struct re_guts *g);
  159. #ifdef __cplusplus
  160. }
  161. #endif
  162. /* ========= end header generated by ./mkh ========= */
  163. static char nuls[10]; /* place to point scanner in event of error */
  164. /*
  165. * macros for use with parse structure
  166. * BEWARE: these know that the parse structure is named `p' !!!
  167. */
  168. #define PEEK() (*p->next)
  169. #define PEEK2() (*(p->next+1))
  170. #define MORE() (p->next < p->end)
  171. #define MORE2() (p->next+1 < p->end)
  172. #define SEE(c) (MORE() && PEEK() == (c))
  173. #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
  174. #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
  175. #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
  176. #define NEXT() (p->next++)
  177. #define NEXT2() (p->next += 2)
  178. #define NEXTn(n) (p->next += (n))
  179. #define GETNEXT() (*p->next++)
  180. #define SETERROR(e) seterr(p, (e))
  181. #define REQUIRE(co, e) (void) ((co) || SETERROR(e))
  182. #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
  183. #define MUSTEAT(c, e) (void) (REQUIRE(MORE() && GETNEXT() == (c), e))
  184. #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
  185. #define EMIT(op, sopnd) doemit(p, (sop)(op), sopnd)
  186. #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
  187. #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
  188. #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
  189. #define HERE() (p->slen)
  190. #define THERE() (p->slen - 1)
  191. #define THERETHERE() (p->slen - 2)
  192. #define DROP(n) (p->slen -= (n))
  193. #ifndef NDEBUG
  194. static int never = 0; /* for use in asserts; shuts lint up */
  195. #else
  196. #define never 0 /* some <assert.h>s have bugs too */
  197. #endif
  198. /*
  199. - regcomp - interface for parser and compilation
  200. = extern int regcomp(regex_t *, const char *, int);
  201. = #define REG_BASIC 0000
  202. = #define REG_EXTENDED 0001
  203. = #define REG_ICASE 0002
  204. = #define REG_NOSUB 0004
  205. = #define REG_NEWLINE 0010
  206. = #define REG_NOSPEC 0020
  207. = #define REG_PEND 0040
  208. = #define REG_DUMP 0200
  209. */
  210. int /* 0 success, otherwise REG_something */
  211. regcomp(
  212. regex_t *preg,
  213. const char *pattern,
  214. int cflags)
  215. {
  216. struct parse pa;
  217. struct re_guts *g;
  218. struct parse *p = &pa;
  219. int i;
  220. size_t len;
  221. #ifdef REDEBUG
  222. # define GOODFLAGS(f) (f)
  223. #else
  224. # define GOODFLAGS(f) ((f)&~REG_DUMP)
  225. #endif
  226. _DIAGASSERT(preg != NULL);
  227. _DIAGASSERT(pattern != NULL);
  228. cflags = GOODFLAGS(cflags);
  229. if ((cflags&REG_EXTENDED) && (cflags&REG_NOSPEC))
  230. return(REG_INVARG);
  231. if (cflags&REG_PEND) {
  232. if (preg->re_endp < pattern)
  233. return(REG_INVARG);
  234. len = preg->re_endp - pattern;
  235. } else
  236. len = strlen(pattern);
  237. /* do the mallocs early so failure handling is easy */
  238. g = (struct re_guts *)malloc(sizeof(struct re_guts) +
  239. (NC-1)*sizeof(cat_t));
  240. if (g == NULL)
  241. return(REG_ESPACE);
  242. p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
  243. p->strip = (sop *)malloc(p->ssize * sizeof(sop));
  244. p->slen = 0;
  245. if (p->strip == NULL) {
  246. free(g);
  247. return(REG_ESPACE);
  248. }
  249. /* set things up */
  250. p->g = g;
  251. p->next = pattern;
  252. p->end = p->next + len;
  253. p->error = 0;
  254. p->ncsalloc = 0;
  255. for (i = 0; i < NPAREN; i++) {
  256. p->pbegin[i] = 0;
  257. p->pend[i] = 0;
  258. }
  259. g->csetsize = NC;
  260. g->sets = NULL;
  261. g->setbits = NULL;
  262. g->ncsets = 0;
  263. g->cflags = cflags;
  264. g->iflags = 0;
  265. g->nbol = 0;
  266. g->neol = 0;
  267. g->must = NULL;
  268. g->mlen = 0;
  269. g->nsub = 0;
  270. g->ncategories = 1; /* category 0 is "everything else" */
  271. g->categories = &g->catspace[-(CHAR_MIN)];
  272. (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
  273. g->backrefs = 0;
  274. /* do it */
  275. EMIT(OEND, 0);
  276. g->firststate = THERE();
  277. if (cflags&REG_EXTENDED)
  278. p_ere(p, OUT);
  279. else if (cflags&REG_NOSPEC)
  280. p_str(p);
  281. else
  282. p_bre(p, OUT, OUT);
  283. EMIT(OEND, 0);
  284. g->laststate = THERE();
  285. /* tidy up loose ends and fill things in */
  286. categorize(p, g);
  287. stripsnug(p, g);
  288. findmust(p, g);
  289. g->nplus = pluscount(p, g);
  290. g->magic = MAGIC2;
  291. preg->re_nsub = g->nsub;
  292. preg->re_g = g;
  293. preg->re_magic = MAGIC1;
  294. #ifndef REDEBUG
  295. /* not debugging, so can't rely on the assert() in regexec() */
  296. if (g->iflags&BAD)
  297. SETERROR(REG_ASSERT);
  298. #endif
  299. /* win or lose, we're done */
  300. if (p->error != 0) /* lose */
  301. regfree(preg);
  302. return(p->error);
  303. }
  304. /*
  305. - p_ere - ERE parser top level, concatenation and alternation
  306. == static void p_ere(struct parse *p, int stop);
  307. */
  308. static void
  309. p_ere(
  310. struct parse *p,
  311. int stop) /* character this ERE should end at */
  312. {
  313. char c;
  314. sopno prevback = 0; /* pacify gcc */
  315. sopno prevfwd = 0; /* pacify gcc */
  316. sopno conc;
  317. int first = 1; /* is this the first alternative? */
  318. _DIAGASSERT(p != NULL);
  319. for (;;) {
  320. /* do a bunch of concatenated expressions */
  321. conc = HERE();
  322. while (MORE() && (c = PEEK()) != '|' && c != stop)
  323. p_ere_exp(p);
  324. REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
  325. if (!EAT('|'))
  326. break; /* NOTE BREAK OUT */
  327. if (first) {
  328. INSERT(OCH_, conc); /* offset is wrong */
  329. prevfwd = conc;
  330. prevback = conc;
  331. first = 0;
  332. }
  333. ASTERN(OOR1, prevback);
  334. prevback = THERE();
  335. AHEAD(prevfwd); /* fix previous offset */
  336. prevfwd = HERE();
  337. EMIT(OOR2, 0); /* offset is very wrong */
  338. }
  339. if (!first) { /* tail-end fixups */
  340. AHEAD(prevfwd);
  341. ASTERN(O_CH, prevback);
  342. }
  343. assert(!MORE() || SEE(stop));
  344. }
  345. /*
  346. - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
  347. == static void p_ere_exp(struct parse *p);
  348. */
  349. static void
  350. p_ere_exp(
  351. struct parse *p)
  352. {
  353. char c;
  354. sopno pos;
  355. int count;
  356. int count2;
  357. sopno subno;
  358. int wascaret = 0;
  359. _DIAGASSERT(p != NULL);
  360. assert(MORE()); /* caller should have ensured this */
  361. c = GETNEXT();
  362. pos = HERE();
  363. switch (c) {
  364. case '(':
  365. REQUIRE(MORE(), REG_EPAREN);
  366. p->g->nsub++;
  367. subno = p->g->nsub;
  368. if (subno < NPAREN)
  369. p->pbegin[subno] = HERE();
  370. EMIT(OLPAREN, subno);
  371. if (!SEE(')'))
  372. p_ere(p, ')');
  373. if (subno < NPAREN) {
  374. p->pend[subno] = HERE();
  375. assert(p->pend[subno] != 0);
  376. }
  377. EMIT(ORPAREN, subno);
  378. MUSTEAT(')', REG_EPAREN);
  379. break;
  380. #ifndef POSIX_MISTAKE
  381. case ')': /* happens only if no current unmatched ( */
  382. /*
  383. * You may ask, why the ifndef? Because I didn't notice
  384. * this until slightly too late for 1003.2, and none of the
  385. * other 1003.2 regular-expression reviewers noticed it at
  386. * all. So an unmatched ) is legal POSIX, at least until
  387. * we can get it fixed.
  388. */
  389. SETERROR(REG_EPAREN);
  390. break;
  391. #endif
  392. case '^':
  393. EMIT(OBOL, 0);
  394. p->g->iflags |= USEBOL;
  395. p->g->nbol++;
  396. wascaret = 1;
  397. break;
  398. case '$':
  399. EMIT(OEOL, 0);
  400. p->g->iflags |= USEEOL;
  401. p->g->neol++;
  402. break;
  403. case '|':
  404. SETERROR(REG_EMPTY);
  405. break;
  406. case '*':
  407. case '+':
  408. case '?':
  409. SETERROR(REG_BADRPT);
  410. break;
  411. case '.':
  412. if (p->g->cflags&REG_NEWLINE)
  413. nonnewline(p);
  414. else
  415. EMIT(OANY, 0);
  416. break;
  417. case '[':
  418. p_bracket(p);
  419. break;
  420. case '\\':
  421. REQUIRE(MORE(), REG_EESCAPE);
  422. c = GETNEXT();
  423. ordinary(p, c);
  424. break;
  425. case '{': /* okay as ordinary except if digit follows */
  426. REQUIRE(!MORE() || !isdigit((unsigned char)PEEK()), REG_BADRPT);
  427. /* FALLTHROUGH */
  428. default:
  429. ordinary(p, c);
  430. break;
  431. }
  432. if (!MORE())
  433. return;
  434. c = PEEK();
  435. /* we call { a repetition if followed by a digit */
  436. if (!( c == '*' || c == '+' || c == '?' ||
  437. (c == '{' && MORE2() && isdigit((unsigned char)PEEK2())) ))
  438. return; /* no repetition, we're done */
  439. NEXT();
  440. REQUIRE(!wascaret, REG_BADRPT);
  441. switch (c) {
  442. case '*': /* implemented as +? */
  443. /* this case does not require the (y|) trick, noKLUDGE */
  444. INSERT(OPLUS_, pos);
  445. ASTERN(O_PLUS, pos);
  446. INSERT(OQUEST_, pos);
  447. ASTERN(O_QUEST, pos);
  448. break;
  449. case '+':
  450. INSERT(OPLUS_, pos);
  451. ASTERN(O_PLUS, pos);
  452. break;
  453. case '?':
  454. /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
  455. INSERT(OCH_, pos); /* offset slightly wrong */
  456. ASTERN(OOR1, pos); /* this one's right */
  457. AHEAD(pos); /* fix the OCH_ */
  458. EMIT(OOR2, 0); /* offset very wrong... */
  459. AHEAD(THERE()); /* ...so fix it */
  460. ASTERN(O_CH, THERETHERE());
  461. break;
  462. case '{':
  463. count = p_count(p);
  464. if (EAT(',')) {
  465. if (isdigit((unsigned char)PEEK())) {
  466. count2 = p_count(p);
  467. REQUIRE(count <= count2, REG_BADBR);
  468. } else /* single number with comma */
  469. count2 = INFINITY;
  470. } else /* just a single number */
  471. count2 = count;
  472. repeat(p, pos, count, count2);
  473. if (!EAT('}')) { /* error heuristics */
  474. while (MORE() && PEEK() != '}')
  475. NEXT();
  476. REQUIRE(MORE(), REG_EBRACE);
  477. SETERROR(REG_BADBR);
  478. }
  479. break;
  480. }
  481. if (!MORE())
  482. return;
  483. c = PEEK();
  484. if (!( c == '*' || c == '+' || c == '?' ||
  485. (c == '{' && MORE2() && isdigit((unsigned char)PEEK2())) ) )
  486. return;
  487. SETERROR(REG_BADRPT);
  488. }
  489. /*
  490. - p_str - string (no metacharacters) "parser"
  491. == static void p_str(struct parse *p);
  492. */
  493. static void
  494. p_str(
  495. struct parse *p)
  496. {
  497. _DIAGASSERT(p != NULL);
  498. REQUIRE(MORE(), REG_EMPTY);
  499. while (MORE())
  500. ordinary(p, GETNEXT());
  501. }
  502. /*
  503. - p_bre - BRE parser top level, anchoring and concatenation
  504. == static void p_bre(struct parse *p, int end1, \
  505. == int end2);
  506. * Giving end1 as OUT essentially eliminates the end1/end2 check.
  507. *
  508. * This implementation is a bit of a kludge, in that a trailing $ is first
  509. * taken as an ordinary character and then revised to be an anchor. The
  510. * only undesirable side effect is that '$' gets included as a character
  511. * category in such cases. This is fairly harmless; not worth fixing.
  512. * The amount of lookahead needed to avoid this kludge is excessive.
  513. */
  514. static void
  515. p_bre(
  516. struct parse *p,
  517. int end1, /* first terminating character */
  518. int end2) /* second terminating character */
  519. {
  520. sopno start;
  521. int first = 1; /* first subexpression? */
  522. int wasdollar = 0;
  523. _DIAGASSERT(p != NULL);
  524. start = HERE();
  525. if (EAT('^')) {
  526. EMIT(OBOL, 0);
  527. p->g->iflags |= USEBOL;
  528. p->g->nbol++;
  529. }
  530. while (MORE() && !SEETWO(end1, end2)) {
  531. wasdollar = p_simp_re(p, first);
  532. first = 0;
  533. }
  534. if (wasdollar) { /* oops, that was a trailing anchor */
  535. DROP(1);
  536. EMIT(OEOL, 0);
  537. p->g->iflags |= USEEOL;
  538. p->g->neol++;
  539. }
  540. REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
  541. }
  542. /*
  543. - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
  544. == static int p_simp_re(struct parse *p, int starordinary);
  545. */
  546. static int /* was the simple RE an unbackslashed $? */
  547. p_simp_re(
  548. struct parse *p,
  549. int starordinary) /* is a leading * an ordinary character? */
  550. {
  551. int c;
  552. int count;
  553. int count2;
  554. sopno pos;
  555. int i;
  556. sopno subno;
  557. # define BACKSL (1<<CHAR_BIT)
  558. _DIAGASSERT(p != NULL);
  559. pos = HERE(); /* repetion op, if any, covers from here */
  560. assert(MORE()); /* caller should have ensured this */
  561. c = GETNEXT();
  562. if (c == '\\') {
  563. REQUIRE(MORE(), REG_EESCAPE);
  564. c = BACKSL | (unsigned char)GETNEXT();
  565. }
  566. switch (c) {
  567. case '.':
  568. if (p->g->cflags&REG_NEWLINE)
  569. nonnewline(p);
  570. else
  571. EMIT(OANY, 0);
  572. break;
  573. case '[':
  574. p_bracket(p);
  575. break;
  576. case BACKSL|'{':
  577. SETERROR(REG_BADRPT);
  578. break;
  579. case BACKSL|'(':
  580. p->g->nsub++;
  581. subno = p->g->nsub;
  582. if (subno < NPAREN)
  583. p->pbegin[subno] = HERE();
  584. EMIT(OLPAREN, subno);
  585. /* the MORE here is an error heuristic */
  586. if (MORE() && !SEETWO('\\', ')'))
  587. p_bre(p, '\\', ')');
  588. if (subno < NPAREN) {
  589. p->pend[subno] = HERE();
  590. assert(p->pend[subno] != 0);
  591. }
  592. EMIT(ORPAREN, subno);
  593. REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
  594. break;
  595. case BACKSL|')': /* should not get here -- must be user */
  596. case BACKSL|'}':
  597. SETERROR(REG_EPAREN);
  598. break;
  599. case BACKSL|'1':
  600. case BACKSL|'2':
  601. case BACKSL|'3':
  602. case BACKSL|'4':
  603. case BACKSL|'5':
  604. case BACKSL|'6':
  605. case BACKSL|'7':
  606. case BACKSL|'8':
  607. case BACKSL|'9':
  608. i = (c&~BACKSL) - '0';
  609. assert(i < NPAREN);
  610. if (p->pend[i] != 0) {
  611. assert(i <= p->g->nsub);
  612. EMIT(OBACK_, i);
  613. assert(p->pbegin[i] != 0);
  614. assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
  615. assert(OP(p->strip[p->pend[i]]) == ORPAREN);
  616. (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
  617. EMIT(O_BACK, i);
  618. } else
  619. SETERROR(REG_ESUBREG);
  620. p->g->backrefs = 1;
  621. break;
  622. case '*':
  623. REQUIRE(starordinary, REG_BADRPT);
  624. /* FALLTHROUGH */
  625. default:
  626. ordinary(p, c &~ BACKSL);
  627. break;
  628. }
  629. if (EAT('*')) { /* implemented as +? */
  630. /* this case does not require the (y|) trick, noKLUDGE */
  631. INSERT(OPLUS_, pos);
  632. ASTERN(O_PLUS, pos);
  633. INSERT(OQUEST_, pos);
  634. ASTERN(O_QUEST, pos);
  635. } else if (EATTWO('\\', '{')) {
  636. count = p_count(p);
  637. if (EAT(',')) {
  638. if (MORE() && isdigit((unsigned char)PEEK())) {
  639. count2 = p_count(p);
  640. REQUIRE(count <= count2, REG_BADBR);
  641. } else /* single number with comma */
  642. count2 = INFINITY;
  643. } else /* just a single number */
  644. count2 = count;
  645. repeat(p, pos, count, count2);
  646. if (!EATTWO('\\', '}')) { /* error heuristics */
  647. while (MORE() && !SEETWO('\\', '}'))
  648. NEXT();
  649. REQUIRE(MORE(), REG_EBRACE);
  650. SETERROR(REG_BADBR);
  651. }
  652. } else if (c == (unsigned char)'$') /* $ (but not \$) ends it */
  653. return(1);
  654. return(0);
  655. }
  656. /*
  657. - p_count - parse a repetition count
  658. == static int p_count(struct parse *p);
  659. */
  660. static int /* the value */
  661. p_count(
  662. struct parse *p)
  663. {
  664. int count = 0;
  665. int ndigits = 0;
  666. _DIAGASSERT(p != NULL);
  667. while (MORE() && isdigit((unsigned char)PEEK()) && count <= DUPMAX) {
  668. count = count*10 + (GETNEXT() - '0');
  669. ndigits++;
  670. }
  671. REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
  672. return(count);
  673. }
  674. /*
  675. - p_bracket - parse a bracketed character list
  676. == static void p_bracket(struct parse *p);
  677. *
  678. * Note a significant property of this code: if the allocset() did SETERROR,
  679. * no set operations are done.
  680. */
  681. static void
  682. p_bracket(
  683. struct parse *p)
  684. {
  685. cset *cs;
  686. int invert = 0;
  687. _DIAGASSERT(p != NULL);
  688. cs = allocset(p);
  689. /* Dept of Truly Sickening Special-Case Kludges */
  690. if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]",
  691. (size_t)6) == 0) {
  692. EMIT(OBOW, 0);
  693. NEXTn(6);
  694. return;
  695. }
  696. if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]",
  697. (size_t)6) == 0) {
  698. EMIT(OEOW, 0);
  699. NEXTn(6);
  700. return;
  701. }
  702. if (EAT('^'))
  703. invert++; /* make note to invert set at end */
  704. if (EAT(']'))
  705. CHadd(cs, ']');
  706. else if (EAT('-'))
  707. CHadd(cs, '-');
  708. while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
  709. p_b_term(p, cs);
  710. if (EAT('-'))
  711. CHadd(cs, '-');
  712. MUSTEAT(']', REG_EBRACK);
  713. if (p->error != 0) /* don't mess things up further */
  714. return;
  715. if (p->g->cflags&REG_ICASE) {
  716. int i;
  717. int ci;
  718. for (i = p->g->csetsize - 1; i >= 0; i--)
  719. if (CHIN(cs, i) && isalpha(i)) {
  720. ci = othercase(i);
  721. if (ci != i)
  722. CHadd(cs, ci);
  723. }
  724. if (cs->multis != NULL)
  725. mccase(p, cs);
  726. }
  727. if (invert) {
  728. int i;
  729. for (i = p->g->csetsize - 1; i >= 0; i--)
  730. if (CHIN(cs, i))
  731. CHsub(cs, i);
  732. else
  733. CHadd(cs, i);
  734. if (p->g->cflags&REG_NEWLINE)
  735. CHsub(cs, '\n');
  736. if (cs->multis != NULL)
  737. mcinvert(p, cs);
  738. }
  739. assert(cs->multis == NULL); /* xxx */
  740. if (nch(p, cs) == 1) { /* optimize singleton sets */
  741. ordinary(p, firstch(p, cs));
  742. freeset(p, cs);
  743. } else
  744. EMIT(OANYOF, freezeset(p, cs));
  745. }
  746. /*
  747. - p_b_term - parse one term of a bracketed character list
  748. == static void p_b_term(struct parse *p, cset *cs);
  749. */
  750. static void
  751. p_b_term(
  752. struct parse *p,
  753. cset *cs)
  754. {
  755. char c;
  756. char start, finish;
  757. int i;
  758. _DIAGASSERT(p != NULL);
  759. _DIAGASSERT(cs != NULL);
  760. /* classify what we've got */
  761. switch ((MORE()) ? PEEK() : '\0') {
  762. case '[':
  763. c = (MORE2()) ? PEEK2() : '\0';
  764. break;
  765. case '-':
  766. SETERROR(REG_ERANGE);
  767. return; /* NOTE RETURN */
  768. default:
  769. c = '\0';
  770. break;
  771. }
  772. switch (c) {
  773. case ':': /* character class */
  774. NEXT2();
  775. REQUIRE(MORE(), REG_EBRACK);
  776. c = PEEK();
  777. REQUIRE(c != '-' && c != ']', REG_ECTYPE);
  778. p_b_cclass(p, cs);
  779. REQUIRE(MORE(), REG_EBRACK);
  780. REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
  781. break;
  782. case '=': /* equivalence class */
  783. NEXT2();
  784. REQUIRE(MORE(), REG_EBRACK);
  785. c = PEEK();
  786. REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
  787. p_b_eclass(p, cs);
  788. REQUIRE(MORE(), REG_EBRACK);
  789. REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
  790. break;
  791. default: /* symbol, ordinary character, or range */
  792. /* xxx revision needed for multichar stuff */
  793. start = p_b_symbol(p);
  794. if (SEE('-') && MORE2() && PEEK2() != ']') {
  795. /* range */
  796. NEXT();
  797. if (EAT('-'))
  798. finish = '-';
  799. else
  800. finish = p_b_symbol(p);
  801. } else
  802. finish = start;
  803. /* xxx what about signed chars here... */
  804. REQUIRE(start <= finish, REG_ERANGE);
  805. for (i = start; i <= finish; i++)
  806. CHadd(cs, i);
  807. break;
  808. }
  809. }
  810. /*
  811. - p_b_cclass - parse a character-class name and deal with it
  812. == static void p_b_cclass(struct parse *p, cset *cs);
  813. */
  814. static void
  815. p_b_cclass(
  816. struct parse *p,
  817. cset *cs)
  818. {
  819. const char *sp;
  820. const struct cclass *cp;
  821. size_t len;
  822. const char *u;
  823. char c;
  824. _DIAGASSERT(p != NULL);
  825. _DIAGASSERT(cs != NULL);
  826. sp = p->next;
  827. while (MORE() && isalpha((unsigned char)PEEK()))
  828. NEXT();
  829. len = p->next - sp;
  830. for (cp = cclasses; cp->name != NULL; cp++)
  831. if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
  832. break;
  833. if (cp->name == NULL) {
  834. /* oops, didn't find it */
  835. SETERROR(REG_ECTYPE);
  836. return;
  837. }
  838. u = cp->chars;
  839. while ((c = *u++) != '\0')
  840. CHadd(cs, c);
  841. for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
  842. MCadd(p, cs, u);
  843. }
  844. /*
  845. - p_b_eclass - parse an equivalence-class name and deal with it
  846. == static void p_b_eclass(struct parse *p, cset *cs);
  847. *
  848. * This implementation is incomplete. xxx
  849. */
  850. static void
  851. p_b_eclass(
  852. struct parse *p,
  853. cset *cs)
  854. {
  855. char c;
  856. _DIAGASSERT(p != NULL);
  857. _DIAGASSERT(cs != NULL);
  858. c = p_b_coll_elem(p, '=');
  859. CHadd(cs, c);
  860. }
  861. /*
  862. - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
  863. == static char p_b_symbol(struct parse *p);
  864. */
  865. static char /* value of symbol */
  866. p_b_symbol(
  867. struct parse *p)
  868. {
  869. char value;
  870. _DIAGASSERT(p != NULL);
  871. REQUIRE(MORE(), REG_EBRACK);
  872. if (!EATTWO('[', '.'))
  873. return(GETNEXT());
  874. /* collating symbol */
  875. value = p_b_coll_elem(p, '.');
  876. REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
  877. return(value);
  878. }
  879. /*
  880. - p_b_coll_elem - parse a collating-element name and look it up
  881. == static char p_b_coll_elem(struct parse *p, int endc);
  882. */
  883. static char /* value of collating element */
  884. p_b_coll_elem(
  885. struct parse *p,
  886. int endc) /* name ended by endc,']' */
  887. {
  888. const char *sp;
  889. const struct cname *cp;
  890. size_t len;
  891. _DIAGASSERT(p != NULL);
  892. sp = p->next;
  893. while (MORE() && !SEETWO(endc, ']'))
  894. NEXT();
  895. if (!MORE()) {
  896. SETERROR(REG_EBRACK);
  897. return(0);
  898. }
  899. len = p->next - sp;
  900. for (cp = cnames; cp->name != NULL; cp++)
  901. if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
  902. return(cp->code); /* known name */
  903. if (len == 1)
  904. return(*sp); /* single character */
  905. SETERROR(REG_ECOLLATE); /* neither */
  906. return(0);
  907. }
  908. /*
  909. - othercase - return the case counterpart of an alphabetic
  910. == static int othercase(int ch);
  911. */
  912. static int /* if no counterpart, return ch */
  913. othercase(
  914. int ch)
  915. {
  916. assert(isalpha(ch));
  917. if (isupper(ch))
  918. return(tolower(ch));
  919. else if (islower(ch))
  920. return(toupper(ch));
  921. else /* peculiar, but could happen */
  922. return(ch);
  923. }
  924. /*
  925. - bothcases - emit a dualcase version of a two-case character
  926. == static void bothcases(struct parse *p, int ch);
  927. *
  928. * Boy, is this implementation ever a kludge...
  929. */
  930. static void
  931. bothcases(
  932. struct parse *p,
  933. int ch)
  934. {
  935. const char *oldnext;
  936. const char *oldend;
  937. char bracket[3];
  938. _DIAGASSERT(p != NULL);
  939. oldnext = p->next;
  940. oldend = p->end;
  941. assert(othercase(ch) != ch); /* p_bracket() would recurse */
  942. p->next = bracket;
  943. p->end = bracket+2;
  944. bracket[0] = ch;
  945. bracket[1] = ']';
  946. bracket[2] = '\0';
  947. p_bracket(p);
  948. assert(p->next == bracket+2);
  949. p->next = oldnext;
  950. p->end = oldend;
  951. }
  952. /*
  953. - ordinary - emit an ordinary character
  954. == static void ordinary(struct parse *p, int ch);
  955. */
  956. static void
  957. ordinary(
  958. struct parse *p,
  959. int ch)
  960. {
  961. cat_t *cap;
  962. _DIAGASSERT(p != NULL);
  963. cap = p->g->categories;
  964. if ((p->g->cflags&REG_ICASE) && isalpha((unsigned char) ch)
  965. && othercase((unsigned char) ch) != (unsigned char) ch)
  966. bothcases(p, (unsigned char) ch);
  967. else {
  968. EMIT(OCHAR, (unsigned char)ch);
  969. if (cap[ch] == 0)
  970. cap[ch] = p->g->ncategories++;
  971. }
  972. }
  973. /*
  974. - nonnewline - emit REG_NEWLINE version of OANY
  975. == static void nonnewline(struct parse *p);
  976. *
  977. * Boy, is this implementation ever a kludge...
  978. */
  979. static void
  980. nonnewline(
  981. struct parse *p)
  982. {
  983. const char *oldnext;
  984. const char *oldend;
  985. char bracket[4];
  986. _DIAGASSERT(p != NULL);
  987. oldnext = p->next;
  988. oldend = p->end;
  989. p->next = bracket;
  990. p->end = bracket+3;
  991. bracket[0] = '^';
  992. bracket[1] = '\n';
  993. bracket[2] = ']';
  994. bracket[3] = '\0';
  995. p_bracket(p);
  996. assert(p->next == bracket+3);
  997. p->next = oldnext;
  998. p->end = oldend;
  999. }
  1000. /*
  1001. - repeat - generate code for a bounded repetition, recursively if needed
  1002. == static void repeat(struct parse *p, sopno start, int from, int to);
  1003. */
  1004. static void
  1005. repeat(
  1006. struct parse *p,
  1007. sopno start, /* operand from here to end of strip */
  1008. int from, /* repeated from this number */
  1009. int to) /* to this number of times (maybe INFINITY) */
  1010. {
  1011. sopno finish;
  1012. # define N 2
  1013. # define INF 3
  1014. # define REP(f, t) ((f)*8 + (t))
  1015. # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
  1016. sopno copy;
  1017. _DIAGASSERT(p != NULL);
  1018. finish = HERE();
  1019. if (p->error != 0) /* head off possible runaway recursion */
  1020. return;
  1021. assert(from <= to);
  1022. switch (REP(MAP(from), MAP(to))) {
  1023. case REP(0, 0): /* must be user doing this */
  1024. DROP(finish-start); /* drop the operand */
  1025. break;
  1026. case REP(0, 1): /* as x{1,1}? */
  1027. case REP(0, N): /* as x{1,n}? */
  1028. case REP(0, INF): /* as x{1,}? */
  1029. /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
  1030. INSERT(OCH_, start); /* offset is wrong... */
  1031. repeat(p, start+1, 1, to);
  1032. ASTERN(OOR1, start);
  1033. AHEAD(start); /* ... fix it */
  1034. EMIT(OOR2, 0);
  1035. AHEAD(THERE());
  1036. ASTERN(O_CH, THERETHERE());
  1037. break;
  1038. case REP(1, 1): /* trivial case */
  1039. /* done */
  1040. break;
  1041. case REP(1, N): /* as x?x{1,n-1} */
  1042. /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
  1043. INSERT(OCH_, start);
  1044. ASTERN(OOR1, start);
  1045. AHEAD(start);
  1046. EMIT(OOR2, 0); /* offset very wrong... */
  1047. AHEAD(THERE()); /* ...so fix it */
  1048. ASTERN(O_CH, THERETHERE());
  1049. copy = dupl(p, start+1, finish+1);
  1050. assert(copy == finish+4);
  1051. repeat(p, copy, 1, to-1);
  1052. break;
  1053. case REP(1, INF): /* as x+ */
  1054. INSERT(OPLUS_, start);
  1055. ASTERN(O_PLUS, start);
  1056. break;
  1057. case REP(N, N): /* as xx{m-1,n-1} */
  1058. copy = dupl(p, start, finish);
  1059. repeat(p, copy, from-1, to-1);
  1060. break;
  1061. case REP(N, INF): /* as xx{n-1,INF} */
  1062. copy = dupl(p, start, finish);
  1063. repeat(p, copy, from-1, to);
  1064. break;
  1065. default: /* "can't happen" */
  1066. SETERROR(REG_ASSERT); /* just in case */
  1067. break;
  1068. }
  1069. }
  1070. /*
  1071. - seterr - set an error condition
  1072. == static int seterr(struct parse *p, int e);
  1073. */
  1074. static int /* useless but makes type checking happy */
  1075. seterr(
  1076. struct parse *p,
  1077. int e)
  1078. {
  1079. _DIAGASSERT(p != NULL);
  1080. if (p->error == 0) /* keep earliest error condition */
  1081. p->error = e;
  1082. p->next = nuls; /* try to bring things to a halt */
  1083. p->end = nuls;
  1084. return(0); /* make the return value well-defined */
  1085. }
  1086. /*
  1087. - allocset - allocate a set of characters for []
  1088. == static cset *allocset(struct parse *p);
  1089. */
  1090. static cset *
  1091. allocset(
  1092. struct parse *p)
  1093. {
  1094. int no;
  1095. size_t nc;
  1096. size_t nbytes;
  1097. cset *cs;
  1098. size_t css;
  1099. int i;
  1100. _DIAGASSERT(p != NULL);
  1101. no = p->g->ncsets++;
  1102. css = (size_t)p->g->csetsize;
  1103. if (no >= p->ncsalloc) { /* need another column of space */
  1104. p->ncsalloc += CHAR_BIT;
  1105. nc = p->ncsalloc;
  1106. assert(nc % CHAR_BIT == 0);
  1107. nbytes = nc / CHAR_BIT * css;
  1108. if (p->g->sets == NULL)
  1109. p->g->sets = malloc(nc * sizeof(cset));
  1110. else
  1111. p->g->sets = realloc(p->g->sets, nc * sizeof(cset));
  1112. if (p->g->setbits == NULL)
  1113. p->g->setbits = malloc(nbytes);
  1114. else {
  1115. p->g->setbits = realloc(p->g->setbits, nbytes);
  1116. /* xxx this isn't right if setbits is now NULL */
  1117. for (i = 0; i < no; i++)
  1118. p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
  1119. }
  1120. if (p->g->sets != NULL && p->g->setbits != NULL)
  1121. (void) memset((char *)p->g->setbits + (nbytes - css),
  1122. 0, css);
  1123. else {
  1124. no = 0;
  1125. SETERROR(REG_ESPACE);
  1126. /* caller's responsibility not to do set ops */
  1127. }
  1128. }
  1129. assert(p->g->sets != NULL); /* xxx */
  1130. cs = &p->g->sets[no];
  1131. cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
  1132. cs->mask = 1 << ((no) % CHAR_BIT);
  1133. cs->hash = 0;
  1134. cs->smultis = 0;
  1135. cs->multis = NULL;
  1136. return(cs);
  1137. }
  1138. /*
  1139. - freeset - free a now-unused set
  1140. == static void freeset(struct parse *p, cset *cs);
  1141. */
  1142. static void
  1143. freeset(
  1144. struct parse *p,
  1145. cset *cs)
  1146. {
  1147. size_t i;
  1148. cset *top;
  1149. size_t css;
  1150. _DIAGASSERT(p != NULL);
  1151. _DIAGASSERT(cs != NULL);
  1152. top = &p->g->sets[p->g->ncsets];
  1153. css = (size_t)p->g->csetsize;
  1154. for (i = 0; i < css; i++)
  1155. CHsub(cs, i);
  1156. if (cs == top-1) /* recover only the easy case */
  1157. p->g->ncsets--;
  1158. }
  1159. /*
  1160. - freezeset - final processing on a set of characters
  1161. == static int freezeset(struct parse *p, cset *cs);
  1162. *
  1163. * The main task here is merging identical sets. This is usually a waste
  1164. * of time (although the hash code minimizes the overhead), but can win
  1165. * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
  1166. * is done using addition rather than xor -- all ASCII [aA] sets xor to
  1167. * the same value!
  1168. */
  1169. static int /* set number */
  1170. freezeset(
  1171. struct parse *p,
  1172. cset *cs)
  1173. {
  1174. uch h;
  1175. size_t i;
  1176. cset *top;
  1177. cset *cs2;
  1178. size_t css;
  1179. _DIAGASSERT(p != NULL);
  1180. _DIAGASSERT(cs != NULL);
  1181. h = cs->hash;
  1182. top = &p->g->sets[p->g->ncsets];
  1183. css = (size_t)p->g->csetsize;
  1184. /* look for an earlier one which is the same */
  1185. for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
  1186. if (cs2->hash == h && cs2 != cs) {
  1187. /* maybe */
  1188. for (i = 0; i < css; i++)
  1189. if (!!CHIN(cs2, i) != !!CHIN(cs, i))
  1190. break; /* no */
  1191. if (i == css)
  1192. break; /* yes */
  1193. }
  1194. if (cs2 < top) { /* found one */
  1195. freeset(p, cs);
  1196. cs = cs2;
  1197. }
  1198. return((int)(cs - p->g->sets));
  1199. }
  1200. /*
  1201. - firstch - return first character in a set (which must have at least one)
  1202. == static int firstch(struct parse *p, cset *cs);
  1203. */
  1204. static int /* character; there is no "none" value */
  1205. firstch(
  1206. struct parse *p,
  1207. cset *cs)
  1208. {
  1209. size_t i;
  1210. size_t css;
  1211. _DIAGASSERT(p != NULL);
  1212. _DIAGASSERT(cs != NULL);
  1213. css = (size_t)p->g->csetsize;
  1214. for (i = 0; i < css; i++)
  1215. if (CHIN(cs, i))
  1216. return((char)i);
  1217. assert(never);
  1218. return(0); /* arbitrary */
  1219. }
  1220. /*
  1221. - nch - number of characters in a set
  1222. == static int nch(struct parse *p, cset *cs);
  1223. */
  1224. static int
  1225. nch(
  1226. struct parse *p,
  1227. cset *cs)
  1228. {
  1229. size_t i;
  1230. size_t css;
  1231. int n = 0;
  1232. _DIAGASSERT(p != NULL);
  1233. _DIAGASSERT(cs != NULL);
  1234. css = (size_t)p->g->csetsize;
  1235. for (i = 0; i < css; i++)
  1236. if (CHIN(cs, i))
  1237. n++;
  1238. return(n);
  1239. }
  1240. /*
  1241. - mcadd - add a collating element to a cset
  1242. == static void mcadd(struct parse *p, cset *cs, \
  1243. == char *cp);
  1244. */
  1245. static void
  1246. mcadd(
  1247. struct parse *p,
  1248. cset *cs,
  1249. const char *cp)
  1250. {
  1251. size_t oldend;
  1252. _DIAGASSERT(p != NULL);
  1253. _DIAGASSERT(cs != NULL);
  1254. _DIAGASSERT(cp != NULL);
  1255. oldend = cs->smultis;
  1256. cs->smultis += strlen(cp) + 1;
  1257. if (cs->multis == NULL)
  1258. cs->multis = malloc(cs->smultis);
  1259. else
  1260. cs->multis = realloc(cs->multis, cs->smultis);
  1261. if (cs->multis == NULL) {
  1262. SETERROR(REG_ESPACE);
  1263. return;
  1264. }
  1265. (void) strcpy(cs->multis + oldend - 1, cp);
  1266. cs->multis[cs->smultis - 1] = '\0';
  1267. }
  1268. #if 0
  1269. /*
  1270. - mcsub - subtract a collating element from a cset
  1271. == static void mcsub(cset *cs, char *cp);
  1272. */
  1273. static void
  1274. mcsub(
  1275. cset *cs,
  1276. char *cp)
  1277. {
  1278. char *fp;
  1279. size_t len;
  1280. _DIAGASSERT(cs != NULL);
  1281. _DIAGASSERT(cp != NULL);
  1282. fp = mcfind(cs, cp);
  1283. len = strlen(fp);
  1284. assert(fp != NULL);
  1285. (void) memmove(fp, fp + len + 1,
  1286. cs->smultis - (fp + len + 1 - cs->multis));
  1287. cs->smultis -= len;
  1288. if (cs->smultis == 0) {
  1289. free(cs->multis);
  1290. cs->multis = NULL;
  1291. return;
  1292. }
  1293. cs->multis = realloc(cs->multis, cs->smultis);
  1294. assert(cs->multis != NULL);
  1295. }
  1296. /*
  1297. - mcin - is a collating element in a cset?
  1298. == static int mcin(cset *cs, char *cp);
  1299. */
  1300. static int
  1301. mcin(
  1302. cset *cs,
  1303. char *cp)
  1304. {
  1305. _DIAGASSERT(cs != NULL);
  1306. _DIAGASSERT(cp != NULL);
  1307. return(mcfind(cs, cp) != NULL);
  1308. }
  1309. /*
  1310. - mcfind - find a collating element in a cset
  1311. == static char *mcfind(cset *cs, char *cp);
  1312. */
  1313. static char *
  1314. mcfind(
  1315. cset *cs,
  1316. char *cp)
  1317. {
  1318. char *p;
  1319. _DIAGASSERT(cs != NULL);
  1320. _DIAGASSERT(cp != NULL);
  1321. if (cs->multis == NULL)
  1322. return(NULL);
  1323. for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
  1324. if (strcmp(cp, p) == 0)
  1325. return(p);
  1326. return(NULL);
  1327. }
  1328. #endif
  1329. /*
  1330. - mcinvert - invert the list of collating elements in a cset
  1331. == static void mcinvert(struct parse *p, cset *cs);
  1332. *
  1333. * This would have to know the set of possibilities. Implementation
  1334. * is deferred.
  1335. */
  1336. /* ARGSUSED */
  1337. static void
  1338. mcinvert(
  1339. struct parse *p,
  1340. cset *cs)
  1341. {
  1342. _DIAGASSERT(p != NULL);
  1343. _DIAGASSERT(cs != NULL);
  1344. assert(cs->multis == NULL); /* xxx */
  1345. }
  1346. /*
  1347. - mccase - add case counterparts of the list of collating elements in a cset
  1348. == static void mccase(struct parse *p, cset *cs);
  1349. *
  1350. * This would have to know the set of possibilities. Implementation
  1351. * is deferred.
  1352. */
  1353. /* ARGSUSED */
  1354. static void
  1355. mccase(
  1356. struct parse *p,
  1357. cset *cs)
  1358. {
  1359. _DIAGASSERT(p != NULL);
  1360. _DIAGASSERT(cs != NULL);
  1361. assert(cs->multis == NULL); /* xxx */
  1362. }
  1363. /*
  1364. - isinsets - is this character in any sets?
  1365. == static int isinsets(struct re_guts *g, int c);
  1366. */
  1367. static int /* predicate */
  1368. isinsets(
  1369. struct re_guts *g,
  1370. int c)
  1371. {
  1372. uch *col;
  1373. int i;
  1374. int ncols;
  1375. unsigned uc = (unsigned char)c;
  1376. _DIAGASSERT(g != NULL);
  1377. ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
  1378. for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
  1379. if (col[uc] != 0)
  1380. return(1);
  1381. return(0);
  1382. }
  1383. /*
  1384. - samesets - are these two characters in exactly the same sets?
  1385. == static int samesets(struct re_guts *g, int c1, int c2);
  1386. */
  1387. static int /* predicate */
  1388. samesets(
  1389. struct re_guts *g,
  1390. int c1,
  1391. int c2)
  1392. {
  1393. uch *col;
  1394. int i;
  1395. int ncols;
  1396. unsigned uc1 = (unsigned char)c1;
  1397. unsigned uc2 = (unsigned char)c2;
  1398. _DIAGASSERT(g != NULL);
  1399. ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
  1400. for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
  1401. if (col[uc1] != col[uc2])
  1402. return(0);
  1403. return(1);
  1404. }
  1405. /*
  1406. - categorize - sort out character categories
  1407. == static void categorize(struct parse *p, struct re_guts *g);
  1408. */
  1409. static void
  1410. categorize(
  1411. struct parse *p,
  1412. struct re_guts *g)
  1413. {
  1414. cat_t *cats;
  1415. int c;
  1416. int c2;
  1417. cat_t cat;
  1418. _DIAGASSERT(p != NULL);
  1419. _DIAGASSERT(g != NULL);
  1420. cats = g->categories;
  1421. /* avoid making error situations worse */
  1422. if (p->error != 0)
  1423. return;
  1424. for (c = CHAR_MIN; c <= CHAR_MAX; c++)
  1425. if (cats[c] == 0 && isinsets(g, c)) {
  1426. cat = g->ncategories++;
  1427. cats[c] = cat;
  1428. for (c2 = c+1; c2 <= CHAR_MAX; c2++)
  1429. if (cats[c2] == 0 && samesets(g, c, c2))
  1430. cats[c2] = cat;
  1431. }
  1432. }
  1433. /*
  1434. - dupl - emit a duplicate of a bunch of sops
  1435. == static sopno dupl(struct parse *p, sopno start, sopno finish);
  1436. */
  1437. static sopno /* start of duplicate */
  1438. dupl(
  1439. struct parse *p,
  1440. sopno start, /* from here */
  1441. sopno finish) /* to this less one */
  1442. {
  1443. sopno ret;
  1444. sopno len = finish - start;
  1445. _DIAGASSERT(p != NULL);
  1446. ret = HERE();
  1447. assert(finish >= start);
  1448. if (len == 0)
  1449. return(ret);
  1450. enlarge(p, p->ssize + len); /* this many unexpected additions */
  1451. assert(p->ssize >= p->slen + len);
  1452. (void)memcpy(p->strip + p->slen, p->strip + start,
  1453. (size_t)len * sizeof(sop));
  1454. p->slen += len;
  1455. return(ret);
  1456. }
  1457. /*
  1458. - doemit - emit a strip operator
  1459. == static void doemit(struct parse *p, sop op, size_t opnd);
  1460. *
  1461. * It might seem better to implement this as a macro with a function as
  1462. * hard-case backup, but it's just too big and messy unless there are
  1463. * some changes to the data structures. Maybe later.
  1464. */
  1465. static void
  1466. doemit(
  1467. struct parse *p,
  1468. sop op,
  1469. sopno opnd)
  1470. {
  1471. _DIAGASSERT(p != NULL);
  1472. /* avoid making error situations worse */
  1473. if (p->error != 0)
  1474. return;
  1475. /* deal with oversize operands ("can't happen", more or less) */
  1476. assert(opnd < 1<<OPSHIFT);
  1477. /* deal with undersized strip */
  1478. if (p->slen >= p->ssize)
  1479. enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
  1480. assert(p->slen < p->ssize);
  1481. /* finally, it's all reduced to the easy case */
  1482. p->strip[p->slen++] = SOP(op, opnd);
  1483. }
  1484. /*
  1485. - doinsert - insert a sop into the strip
  1486. == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
  1487. */
  1488. static void
  1489. doinsert(
  1490. struct parse *p,
  1491. sop op,
  1492. sopno opnd,
  1493. sopno pos)
  1494. {
  1495. sopno sn;
  1496. sop s;
  1497. int i;
  1498. _DIAGASSERT(p != NULL);
  1499. /* avoid making error situations worse */
  1500. if (p->error != 0)
  1501. return;
  1502. sn = HERE();
  1503. EMIT(op, opnd); /* do checks, ensure space */
  1504. assert(HERE() == sn+1);
  1505. s = p->strip[sn];
  1506. /* adjust paren pointers */
  1507. assert(pos > 0);
  1508. for (i = 1; i < NPAREN; i++) {
  1509. if (p->pbegin[i] >= pos) {
  1510. p->pbegin[i]++;
  1511. }
  1512. if (p->pend[i] >= pos) {
  1513. p->pend[i]++;
  1514. }
  1515. }
  1516. memmove(&p->strip[pos+1], &p->strip[pos], (HERE()-pos-1)*sizeof(sop));
  1517. p->strip[pos] = s;
  1518. }
  1519. /*
  1520. - dofwd - complete a forward reference
  1521. == static void dofwd(struct parse *p, sopno pos, sop value);
  1522. */
  1523. static void
  1524. dofwd(
  1525. struct parse *p,
  1526. sopno pos,
  1527. sopno value)
  1528. {
  1529. _DIAGASSERT(p != NULL);
  1530. /* avoid making error situations worse */
  1531. if (p->error != 0)
  1532. return;
  1533. assert(value < 1<<OPSHIFT);
  1534. p->strip[pos] = OP(p->strip[pos]) | value;
  1535. }
  1536. /*
  1537. - enlarge - enlarge the strip
  1538. == static void enlarge(struct parse *p, sopno size);
  1539. */
  1540. static void
  1541. enlarge(
  1542. struct parse *p,
  1543. sopno size)
  1544. {
  1545. sop *sp;
  1546. _DIAGASSERT(p != NULL);
  1547. if (p->ssize >= size)
  1548. return;
  1549. sp = (sop *)realloc(p->strip, size*sizeof(sop));
  1550. if (sp == NULL) {
  1551. SETERROR(REG_ESPACE);
  1552. return;
  1553. }
  1554. p->strip = sp;
  1555. p->ssize = size;
  1556. }
  1557. /*
  1558. - stripsnug - compact the strip
  1559. == static void stripsnug(struct parse *p, struct re_guts *g);
  1560. */
  1561. static void
  1562. stripsnug(
  1563. struct parse *p,
  1564. struct re_guts *g)
  1565. {
  1566. _DIAGASSERT(p != NULL);
  1567. _DIAGASSERT(g != NULL);
  1568. g->nstates = p->slen;
  1569. g->strip = realloc(p->strip, p->slen * sizeof(sop));
  1570. if (g->strip == NULL) {
  1571. SETERROR(REG_ESPACE);
  1572. g->strip = p->strip;
  1573. }
  1574. }
  1575. /*
  1576. - findmust - fill in must and mlen with longest mandatory literal string
  1577. == static void findmust(struct parse *p, struct re_guts *g);
  1578. *
  1579. * This algorithm could do fancy things like analyzing the operands of |
  1580. * for common subsequences. Someday. This code is simple and finds most
  1581. * of the interesting cases.
  1582. *
  1583. * Note that must and mlen got initialized during setup.
  1584. */
  1585. static void
  1586. findmust(
  1587. struct parse *p,
  1588. struct re_guts *g)
  1589. {
  1590. sop *scan;
  1591. sop *start = NULL;
  1592. sop *newstart = NULL;
  1593. sopno newlen;
  1594. sop s;
  1595. char *cp;
  1596. sopno i;
  1597. _DIAGASSERT(p != NULL);
  1598. _DIAGASSERT(g != NULL);
  1599. /* avoid making error situations worse */
  1600. if (p->error != 0)
  1601. return;
  1602. /* find the longest OCHAR sequence in strip */
  1603. newlen = 0;
  1604. scan = g->strip + 1;
  1605. do {
  1606. s = *scan++;
  1607. switch (OP(s)) {
  1608. case OCHAR: /* sequence member */
  1609. if (newlen == 0) /* new sequence */
  1610. newstart = scan - 1;
  1611. newlen++;
  1612. break;
  1613. case OPLUS_: /* things that don't break one */
  1614. case OLPAREN:
  1615. case ORPAREN:
  1616. break;
  1617. case OQUEST_: /* things that must be skipped */
  1618. case OCH_:
  1619. scan--;
  1620. do {
  1621. scan += OPND(s);
  1622. s = *scan;
  1623. /* assert() interferes w debug printouts */
  1624. if (OP(s) != O_QUEST && OP(s) != O_CH &&
  1625. OP(s) != OOR2) {
  1626. g->iflags |= BAD;
  1627. return;
  1628. }
  1629. } while (OP(s) != O_QUEST && OP(s) != O_CH);
  1630. /* FALLTHROUGH */
  1631. default: /* things that break a sequence */
  1632. if (newlen > g->mlen) { /* ends one */
  1633. start = newstart;
  1634. g->mlen = newlen;
  1635. }
  1636. newlen = 0;
  1637. break;
  1638. }
  1639. } while (OP(s) != OEND);
  1640. if (start == NULL)
  1641. g->mlen = 0;
  1642. if (g->mlen == 0) /* there isn't one */
  1643. return;
  1644. /* turn it into a character string */
  1645. g->must = malloc((size_t)g->mlen + 1);
  1646. if (g->must == NULL) { /* argh; just forget it */
  1647. g->mlen = 0;
  1648. return;
  1649. }
  1650. cp = g->must;
  1651. scan = start;
  1652. for (i = g->mlen; i > 0; i--) {
  1653. while (OP(s = *scan++) != OCHAR)
  1654. continue;
  1655. assert(cp < g->must + g->mlen);
  1656. *cp++ = (char)OPND(s);
  1657. }
  1658. assert(cp == g->must + g->mlen);
  1659. *cp++ = '\0'; /* just on general principles */
  1660. }
  1661. /*
  1662. - pluscount - count + nesting
  1663. == static sopno pluscount(struct parse *p, struct re_guts *g);
  1664. */
  1665. static sopno /* nesting depth */
  1666. pluscount(
  1667. struct parse *p,
  1668. struct re_guts *g)
  1669. {
  1670. sop *scan;
  1671. sop s;
  1672. sopno plusnest = 0;
  1673. sopno maxnest = 0;
  1674. _DIAGASSERT(p != NULL);
  1675. _DIAGASSERT(g != NULL);
  1676. if (p->error != 0)
  1677. return(0); /* there may not be an OEND */
  1678. scan = g->strip + 1;
  1679. do {
  1680. s = *scan++;
  1681. switch (OP(s)) {
  1682. case OPLUS_:
  1683. plusnest++;
  1684. break;
  1685. case O_PLUS:
  1686. if (plusnest > maxnest)
  1687. maxnest = plusnest;
  1688. plusnest--;
  1689. break;
  1690. }
  1691. } while (OP(s) != OEND);
  1692. if (plusnest != 0)
  1693. g->iflags |= BAD;
  1694. return(maxnest);
  1695. }