PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/quakeforge/trunk/libs/gib/regex.c

#
C | 2003 lines | 1200 code | 375 blank | 428 comment | 320 complexity | efadfcf393f2444084f238984ade1afc MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, AGPL-3.0, AGPL-1.0, Unlicense
  1. /* Extended regular expression matching and search library,
  2. version 0.12.
  3. (Implements POSIX draft P10003.2/D11.2, except for
  4. internationalization features.)
  5. Copyright (C) 1993 Free Software Foundation, Inc.
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
  17. /* AIX requires this to be the first thing in the file. */
  18. #if defined (_AIX) && !defined (REGEX_MALLOC)
  19. #pragma alloca
  20. #endif
  21. #define _GNU_SOURCE
  22. /* We need this for `regex.h', and perhaps for the Emacs include files. */
  23. #include <sys/types.h>
  24. #ifdef HAVE_CONFIG_H
  25. #include "config.h"
  26. #endif
  27. /* The `emacs' switch turns on certain matching commands
  28. that make sense only in Emacs. */
  29. #ifdef emacs
  30. #include "lisp.h"
  31. #include "buffer.h"
  32. #include "syntax.h"
  33. /* Emacs uses `NULL' as a predicate. */
  34. #undef NULL
  35. #else /* not emacs */
  36. /* We used to test for `BSTRING' here, but only GCC and Emacs define
  37. `BSTRING', as far as I know, and neither of them use this code. */
  38. #if HAVE_STRING_H || STDC_HEADERS
  39. #include <string.h>
  40. #ifndef bcmp
  41. #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
  42. #endif
  43. #ifndef bcopy
  44. #define bcopy(s, d, n) memcpy ((d), (s), (n))
  45. #endif
  46. #ifndef bzero
  47. #define bzero(s, n) memset ((s), 0, (n))
  48. #endif
  49. #else
  50. #include <strings.h>
  51. #endif
  52. #ifdef STDC_HEADERS
  53. #include <stdlib.h>
  54. #ifdef HAVE_MALLOC_H
  55. #include <malloc.h>
  56. #endif
  57. #else
  58. char *malloc ();
  59. char *realloc ();
  60. #endif
  61. /* Define the syntax stuff for \<, \>, etc. */
  62. /* This must be nonzero for the wordchar and notwordchar pattern
  63. commands in re_match_2. */
  64. #ifndef Sword
  65. #define Sword 1
  66. #endif
  67. #ifdef SYNTAX_TABLE
  68. extern char *re_syntax_table;
  69. #else /* not SYNTAX_TABLE */
  70. /* How many characters in the character set. */
  71. #define CHAR_SET_SIZE 256
  72. static char re_syntax_table[CHAR_SET_SIZE];
  73. static void
  74. init_syntax_once (void)
  75. {
  76. register int c;
  77. static int done = 0;
  78. if (done)
  79. return;
  80. bzero (re_syntax_table, sizeof re_syntax_table);
  81. for (c = 'a'; c <= 'z'; c++)
  82. re_syntax_table[c] = Sword;
  83. for (c = 'A'; c <= 'Z'; c++)
  84. re_syntax_table[c] = Sword;
  85. for (c = '0'; c <= '9'; c++)
  86. re_syntax_table[c] = Sword;
  87. re_syntax_table['_'] = Sword;
  88. done = 1;
  89. }
  90. #endif /* not SYNTAX_TABLE */
  91. #define SYNTAX(c) re_syntax_table[c]
  92. #endif /* not emacs */
  93. /* Get the interface, including the syntax bits. */
  94. #include "regex.h"
  95. /* isalpha etc. are used for the character classes. */
  96. #include <ctype.h>
  97. #ifndef isascii
  98. #define isascii(c) 1
  99. #endif
  100. #ifdef isblank
  101. #define ISBLANK(c) (isascii (c) && isblank (c))
  102. #else
  103. #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
  104. #endif
  105. #ifdef isgraph
  106. #define ISGRAPH(c) (isascii (c) && isgraph (c))
  107. #else
  108. #define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
  109. #endif
  110. #define ISPRINT(c) (isascii (c) && isprint (c))
  111. #define ISDIGIT(c) (isascii (c) && isdigit (c))
  112. #define ISALNUM(c) (isascii (c) && isalnum (c))
  113. #define ISALPHA(c) (isascii (c) && isalpha (c))
  114. #define ISCNTRL(c) (isascii (c) && iscntrl (c))
  115. #define ISLOWER(c) (isascii (c) && islower (c))
  116. #define ISPUNCT(c) (isascii (c) && ispunct (c))
  117. #define ISSPACE(c) (isascii (c) && isspace (c))
  118. #define ISUPPER(c) (isascii (c) && isupper (c))
  119. #define ISXDIGIT(c) (isascii (c) && isxdigit (c))
  120. #ifndef NULL
  121. #define NULL 0
  122. #endif
  123. /* We remove any previous definition of `SIGN_EXTEND_CHAR',
  124. since ours (we hope) works properly with all combinations of
  125. machines, compilers, `char' and `unsigned char' argument types.
  126. (Per Bothner suggested the basic approach.) */
  127. #undef SIGN_EXTEND_CHAR
  128. #if __STDC__
  129. #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
  130. #else /* not __STDC__ */
  131. /* As in Harbison and Steele. */
  132. #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
  133. #endif
  134. /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
  135. use `alloca' instead of `malloc'. This is because using malloc in
  136. re_search* or re_match* could cause memory leaks when C-g is used in
  137. Emacs; also, malloc is slower and causes storage fragmentation. On
  138. the other hand, malloc is more portable, and easier to debug.
  139. Because we sometimes use alloca, some routines have to be macros,
  140. not functions -- `alloca'-allocated space disappears at the end of the
  141. function it is called in. */
  142. #ifdef REGEX_MALLOC
  143. #define REGEX_ALLOCATE malloc
  144. #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
  145. #else /* not REGEX_MALLOC */
  146. /* Emacs already defines alloca, sometimes. */
  147. #ifndef alloca
  148. /* Make alloca work the best possible way. */
  149. #ifdef __GNUC__
  150. #define alloca __builtin_alloca
  151. #else /* not __GNUC__ */
  152. #if HAVE_ALLOCA_H
  153. #include <alloca.h>
  154. #else /* not __GNUC__ or HAVE_ALLOCA_H */
  155. #ifndef _AIX /* Already did AIX, up at the top. */
  156. #ifndef _WIN32
  157. char *alloca ();
  158. #endif
  159. #endif /* not _AIX */
  160. #endif /* not HAVE_ALLOCA_H */
  161. #endif /* not __GNUC__ */
  162. #endif /* not alloca */
  163. #define REGEX_ALLOCATE alloca
  164. /* Assumes a `char *destination' variable. */
  165. #define REGEX_REALLOCATE(source, osize, nsize) \
  166. (destination = (char *) alloca (nsize), \
  167. bcopy (source, destination, osize), \
  168. destination)
  169. #endif /* not REGEX_MALLOC */
  170. /* True if `size1' is non-NULL and PTR is pointing anywhere inside
  171. `string1' or just past its end. This works if PTR is NULL, which is
  172. a good thing. */
  173. #define FIRST_STRING_P(ptr) \
  174. (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
  175. /* (Re)Allocate N items of type T using malloc, or fail. */
  176. #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
  177. #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
  178. #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
  179. #define BYTEWIDTH 8 /* In bits. */
  180. #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
  181. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  182. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  183. typedef char boolean;
  184. #define false 0
  185. #define true 1
  186. /* These are the command codes that appear in compiled regular
  187. expressions. Some opcodes are followed by argument bytes. A
  188. command code can specify any interpretation whatsoever for its
  189. arguments. Zero bytes may appear in the compiled regular expression.
  190. The value of `exactn' is needed in search.c (search_buffer) in Emacs.
  191. So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
  192. `exactn' we use here must also be 1. */
  193. typedef enum
  194. {
  195. no_op = 0,
  196. /* Followed by one byte giving n, then by n literal bytes. */
  197. exactn = 1,
  198. /* Matches any (more or less) character. */
  199. anychar,
  200. /* Matches any one char belonging to specified set. First
  201. following byte is number of bitmap bytes. Then come bytes
  202. for a bitmap saying which chars are in. Bits in each byte
  203. are ordered low-bit-first. A character is in the set if its
  204. bit is 1. A character too large to have a bit in the map is
  205. automatically not in the set. */
  206. charset,
  207. /* Same parameters as charset, but match any character that is
  208. not one of those specified. */
  209. charset_not,
  210. /* Start remembering the text that is matched, for storing in a
  211. register. Followed by one byte with the register number, in
  212. the range 0 to one less than the pattern buffer's re_nsub
  213. field. Then followed by one byte with the number of groups
  214. inner to this one. (This last has to be part of the
  215. start_memory only because we need it in the on_failure_jump
  216. of re_match_2.) */
  217. start_memory,
  218. /* Stop remembering the text that is matched and store it in a
  219. memory register. Followed by one byte with the register
  220. number, in the range 0 to one less than `re_nsub' in the
  221. pattern buffer, and one byte with the number of inner groups,
  222. just like `start_memory'. (We need the number of inner
  223. groups here because we don't have any easy way of finding the
  224. corresponding start_memory when we're at a stop_memory.) */
  225. stop_memory,
  226. /* Match a duplicate of something remembered. Followed by one
  227. byte containing the register number. */
  228. duplicate,
  229. /* Fail unless at beginning of line. */
  230. begline,
  231. /* Fail unless at end of line. */
  232. endline,
  233. /* Succeeds if at beginning of buffer (if emacs) or at beginning
  234. of string to be matched (if not). */
  235. begbuf,
  236. /* Analogously, for end of buffer/string. */
  237. endbuf,
  238. /* Followed by two byte relative address to which to jump. */
  239. jump,
  240. /* Same as jump, but marks the end of an alternative. */
  241. jump_past_alt,
  242. /* Followed by two-byte relative address of place to resume at
  243. in case of failure. */
  244. on_failure_jump,
  245. /* Like on_failure_jump, but pushes a placeholder instead of the
  246. current string position when executed. */
  247. on_failure_keep_string_jump,
  248. /* Throw away latest failure point and then jump to following
  249. two-byte relative address. */
  250. pop_failure_jump,
  251. /* Change to pop_failure_jump if know won't have to backtrack to
  252. match; otherwise change to jump. This is used to jump
  253. back to the beginning of a repeat. If what follows this jump
  254. clearly won't match what the repeat does, such that we can be
  255. sure that there is no use backtracking out of repetitions
  256. already matched, then we change it to a pop_failure_jump.
  257. Followed by two-byte address. */
  258. maybe_pop_jump,
  259. /* Jump to following two-byte address, and push a dummy failure
  260. point. This failure point will be thrown away if an attempt
  261. is made to use it for a failure. A `+' construct makes this
  262. before the first repeat. Also used as an intermediary kind
  263. of jump when compiling an alternative. */
  264. dummy_failure_jump,
  265. /* Push a dummy failure point and continue. Used at the end of
  266. alternatives. */
  267. push_dummy_failure,
  268. /* Followed by two-byte relative address and two-byte number n.
  269. After matching N times, jump to the address upon failure. */
  270. succeed_n,
  271. /* Followed by two-byte relative address, and two-byte number n.
  272. Jump to the address N times, then fail. */
  273. jump_n,
  274. /* Set the following two-byte relative address to the
  275. subsequent two-byte number. The address *includes* the two
  276. bytes of number. */
  277. set_number_at,
  278. wordchar, /* Matches any word-constituent character. */
  279. notwordchar, /* Matches any char that is not a word-constituent. */
  280. wordbeg, /* Succeeds if at word beginning. */
  281. wordend, /* Succeeds if at word end. */
  282. wordbound, /* Succeeds if at a word boundary. */
  283. notwordbound /* Succeeds if not at a word boundary. */
  284. #ifdef emacs
  285. ,before_dot, /* Succeeds if before point. */
  286. at_dot, /* Succeeds if at point. */
  287. after_dot, /* Succeeds if after point. */
  288. /* Matches any character whose syntax is specified. Followed by
  289. a byte which contains a syntax code, e.g., Sword. */
  290. syntaxspec,
  291. /* Matches any character whose syntax is not that specified. */
  292. notsyntaxspec
  293. #endif /* emacs */
  294. } re_opcode_t;
  295. /* Common operations on the compiled pattern. */
  296. /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
  297. #define STORE_NUMBER(destination, number) \
  298. do { \
  299. (destination)[0] = (number) & 0377; \
  300. (destination)[1] = (number) >> 8; \
  301. } while (0)
  302. /* Same as STORE_NUMBER, except increment DESTINATION to
  303. the byte after where the number is stored. Therefore, DESTINATION
  304. must be an lvalue. */
  305. #define STORE_NUMBER_AND_INCR(destination, number) \
  306. do { \
  307. STORE_NUMBER (destination, number); \
  308. (destination) += 2; \
  309. } while (0)
  310. /* Put into DESTINATION a number stored in two contiguous bytes starting
  311. at SOURCE. */
  312. #define EXTRACT_NUMBER(destination, source) \
  313. do { \
  314. (destination) = *(source) & 0377; \
  315. (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
  316. } while (0)
  317. #ifdef DEBUG
  318. static void
  319. extract_number (dest, source)
  320. int *dest;
  321. unsigned char *source;
  322. {
  323. int temp = SIGN_EXTEND_CHAR (*(source + 1));
  324. *dest = *source & 0377;
  325. *dest += temp << 8;
  326. }
  327. #ifndef EXTRACT_MACROS /* To debug the macros. */
  328. #undef EXTRACT_NUMBER
  329. #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
  330. #endif /* not EXTRACT_MACROS */
  331. #endif /* DEBUG */
  332. /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
  333. SOURCE must be an lvalue. */
  334. #define EXTRACT_NUMBER_AND_INCR(destination, source) \
  335. do { \
  336. EXTRACT_NUMBER (destination, source); \
  337. (source) += 2; \
  338. } while (0)
  339. #ifdef DEBUG
  340. static void
  341. extract_number_and_incr (destination, source)
  342. int *destination;
  343. unsigned char **source;
  344. {
  345. extract_number (destination, *source);
  346. *source += 2;
  347. }
  348. #ifndef EXTRACT_MACROS
  349. #undef EXTRACT_NUMBER_AND_INCR
  350. #define EXTRACT_NUMBER_AND_INCR(dest, src) \
  351. extract_number_and_incr (&dest, &src)
  352. #endif /* not EXTRACT_MACROS */
  353. #endif /* DEBUG */
  354. /* If DEBUG is defined, Regex prints many voluminous messages about what
  355. it is doing (if the variable `debug' is nonzero). If linked with the
  356. main program in `iregex.c', you can enter patterns and strings
  357. interactively. And if linked with the main program in `main.c' and
  358. the other test files, you can run the already-written tests. */
  359. #ifdef DEBUG
  360. /* We use standard I/O for debugging. */
  361. #include <stdio.h>
  362. /* It is useful to test things that ``must'' be true when debugging. */
  363. #include <assert.h>
  364. static int debug = 0;
  365. #define DEBUG_STATEMENT(e) e
  366. #define DEBUG_PRINT1(x) if (debug) printf (x)
  367. #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
  368. #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
  369. #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
  370. #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
  371. if (debug) print_partial_compiled_pattern (s, e)
  372. #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
  373. if (debug) print_double_string (w, s1, sz1, s2, sz2)
  374. extern void printchar ();
  375. /* Print the fastmap in human-readable form. */
  376. void
  377. print_fastmap (fastmap)
  378. char *fastmap;
  379. {
  380. unsigned was_a_range = 0;
  381. unsigned i = 0;
  382. while (i < (1 << BYTEWIDTH))
  383. {
  384. if (fastmap[i++])
  385. {
  386. was_a_range = 0;
  387. printchar (i - 1);
  388. while (i < (1 << BYTEWIDTH) && fastmap[i])
  389. {
  390. was_a_range = 1;
  391. i++;
  392. }
  393. if (was_a_range)
  394. {
  395. printf ("-");
  396. printchar (i - 1);
  397. }
  398. }
  399. }
  400. putchar ('\n');
  401. }
  402. /* Print a compiled pattern string in human-readable form, starting at
  403. the START pointer into it and ending just before the pointer END. */
  404. void
  405. print_partial_compiled_pattern (start, end)
  406. unsigned char *start;
  407. unsigned char *end;
  408. {
  409. int mcnt, mcnt2;
  410. unsigned char *p = start;
  411. unsigned char *pend = end;
  412. if (start == NULL)
  413. {
  414. printf ("(null)\n");
  415. return;
  416. }
  417. /* Loop over pattern commands. */
  418. while (p < pend)
  419. {
  420. switch ((re_opcode_t) *p++)
  421. {
  422. case no_op:
  423. printf ("/no_op");
  424. break;
  425. case exactn:
  426. mcnt = *p++;
  427. printf ("/exactn/%d", mcnt);
  428. do
  429. {
  430. putchar ('/');
  431. printchar (*p++);
  432. }
  433. while (--mcnt);
  434. break;
  435. case start_memory:
  436. mcnt = *p++;
  437. printf ("/start_memory/%d/%d", mcnt, *p++);
  438. break;
  439. case stop_memory:
  440. mcnt = *p++;
  441. printf ("/stop_memory/%d/%d", mcnt, *p++);
  442. break;
  443. case duplicate:
  444. printf ("/duplicate/%d", *p++);
  445. break;
  446. case anychar:
  447. printf ("/anychar");
  448. break;
  449. case charset:
  450. case charset_not:
  451. {
  452. register int c;
  453. printf ("/charset%s",
  454. (re_opcode_t) *(p - 1) == charset_not ? "_not" : "");
  455. assert (p + *p < pend);
  456. for (c = 0; c < *p; c++)
  457. {
  458. unsigned bit;
  459. unsigned char map_byte = p[1 + c];
  460. putchar ('/');
  461. for (bit = 0; bit < BYTEWIDTH; bit++)
  462. if (map_byte & (1 << bit))
  463. printchar (c * BYTEWIDTH + bit);
  464. }
  465. p += 1 + *p;
  466. break;
  467. }
  468. case begline:
  469. printf ("/begline");
  470. break;
  471. case endline:
  472. printf ("/endline");
  473. break;
  474. case on_failure_jump:
  475. extract_number_and_incr (&mcnt, &p);
  476. printf ("/on_failure_jump/0/%d", mcnt);
  477. break;
  478. case on_failure_keep_string_jump:
  479. extract_number_and_incr (&mcnt, &p);
  480. printf ("/on_failure_keep_string_jump/0/%d", mcnt);
  481. break;
  482. case dummy_failure_jump:
  483. extract_number_and_incr (&mcnt, &p);
  484. printf ("/dummy_failure_jump/0/%d", mcnt);
  485. break;
  486. case push_dummy_failure:
  487. printf ("/push_dummy_failure");
  488. break;
  489. case maybe_pop_jump:
  490. extract_number_and_incr (&mcnt, &p);
  491. printf ("/maybe_pop_jump/0/%d", mcnt);
  492. break;
  493. case pop_failure_jump:
  494. extract_number_and_incr (&mcnt, &p);
  495. printf ("/pop_failure_jump/0/%d", mcnt);
  496. break;
  497. case jump_past_alt:
  498. extract_number_and_incr (&mcnt, &p);
  499. printf ("/jump_past_alt/0/%d", mcnt);
  500. break;
  501. case jump:
  502. extract_number_and_incr (&mcnt, &p);
  503. printf ("/jump/0/%d", mcnt);
  504. break;
  505. case succeed_n:
  506. extract_number_and_incr (&mcnt, &p);
  507. extract_number_and_incr (&mcnt2, &p);
  508. printf ("/succeed_n/0/%d/0/%d", mcnt, mcnt2);
  509. break;
  510. case jump_n:
  511. extract_number_and_incr (&mcnt, &p);
  512. extract_number_and_incr (&mcnt2, &p);
  513. printf ("/jump_n/0/%d/0/%d", mcnt, mcnt2);
  514. break;
  515. case set_number_at:
  516. extract_number_and_incr (&mcnt, &p);
  517. extract_number_and_incr (&mcnt2, &p);
  518. printf ("/set_number_at/0/%d/0/%d", mcnt, mcnt2);
  519. break;
  520. case wordbound:
  521. printf ("/wordbound");
  522. break;
  523. case notwordbound:
  524. printf ("/notwordbound");
  525. break;
  526. case wordbeg:
  527. printf ("/wordbeg");
  528. break;
  529. case wordend:
  530. printf ("/wordend");
  531. #ifdef emacs
  532. case before_dot:
  533. printf ("/before_dot");
  534. break;
  535. case at_dot:
  536. printf ("/at_dot");
  537. break;
  538. case after_dot:
  539. printf ("/after_dot");
  540. break;
  541. case syntaxspec:
  542. printf ("/syntaxspec");
  543. mcnt = *p++;
  544. printf ("/%d", mcnt);
  545. break;
  546. case notsyntaxspec:
  547. printf ("/notsyntaxspec");
  548. mcnt = *p++;
  549. printf ("/%d", mcnt);
  550. break;
  551. #endif /* emacs */
  552. case wordchar:
  553. printf ("/wordchar");
  554. break;
  555. case notwordchar:
  556. printf ("/notwordchar");
  557. break;
  558. case begbuf:
  559. printf ("/begbuf");
  560. break;
  561. case endbuf:
  562. printf ("/endbuf");
  563. break;
  564. default:
  565. printf ("?%d", *(p-1));
  566. }
  567. }
  568. printf ("/\n");
  569. }
  570. void
  571. print_compiled_pattern (bufp)
  572. struct re_pattern_buffer *bufp;
  573. {
  574. unsigned char *buffer = bufp->buffer;
  575. print_partial_compiled_pattern (buffer, buffer + bufp->used);
  576. printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
  577. if (bufp->fastmap_accurate && bufp->fastmap)
  578. {
  579. printf ("fastmap: ");
  580. print_fastmap (bufp->fastmap);
  581. }
  582. printf ("re_nsub: %d\t", bufp->re_nsub);
  583. printf ("regs_alloc: %d\t", bufp->regs_allocated);
  584. printf ("can_be_null: %d\t", bufp->can_be_null);
  585. printf ("newline_anchor: %d\n", bufp->newline_anchor);
  586. printf ("no_sub: %d\t", bufp->no_sub);
  587. printf ("not_bol: %d\t", bufp->not_bol);
  588. printf ("not_eol: %d\t", bufp->not_eol);
  589. printf ("syntax: %d\n", bufp->syntax);
  590. /* Perhaps we should print the translate table? */
  591. }
  592. void
  593. print_double_string (where, string1, size1, string2, size2)
  594. const char *where;
  595. const char *string1;
  596. const char *string2;
  597. int size1;
  598. int size2;
  599. {
  600. unsigned this_char;
  601. if (where == NULL)
  602. printf ("(null)");
  603. else
  604. {
  605. if (FIRST_STRING_P (where))
  606. {
  607. for (this_char = where - string1; this_char < size1; this_char++)
  608. printchar (string1[this_char]);
  609. where = string2;
  610. }
  611. for (this_char = where - string2; this_char < size2; this_char++)
  612. printchar (string2[this_char]);
  613. }
  614. }
  615. #else /* not DEBUG */
  616. #undef assert
  617. #define assert(e)
  618. #define DEBUG_STATEMENT(e)
  619. #define DEBUG_PRINT1(x)
  620. #define DEBUG_PRINT2(x1, x2)
  621. #define DEBUG_PRINT3(x1, x2, x3)
  622. #define DEBUG_PRINT4(x1, x2, x3, x4)
  623. #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
  624. #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
  625. #endif /* not DEBUG */
  626. /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
  627. also be assigned to arbitrarily: each pattern buffer stores its own
  628. syntax, so it can be changed between regex compilations. */
  629. reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
  630. /* Specify the precise syntax of regexps for compilation. This provides
  631. for compatibility for various utilities which historically have
  632. different, incompatible syntaxes.
  633. The argument SYNTAX is a bit mask comprised of the various bits
  634. defined in regex.h. We return the old syntax. */
  635. reg_syntax_t
  636. re_set_syntax (syntax)
  637. reg_syntax_t syntax;
  638. {
  639. reg_syntax_t ret = re_syntax_options;
  640. re_syntax_options = syntax;
  641. return ret;
  642. }
  643. /* This table gives an error message for each of the error codes listed
  644. in regex.h. Obviously the order here has to be same as there. */
  645. static const char *re_error_msg[] =
  646. { NULL, /* REG_NOERROR */
  647. "No match", /* REG_NOMATCH */
  648. "Invalid regular expression", /* REG_BADPAT */
  649. "Invalid collation character", /* REG_ECOLLATE */
  650. "Invalid character class name", /* REG_ECTYPE */
  651. "Trailing backslash", /* REG_EESCAPE */
  652. "Invalid back reference", /* REG_ESUBREG */
  653. "Unmatched [ or [^", /* REG_EBRACK */
  654. "Unmatched ( or \\(", /* REG_EPAREN */
  655. "Unmatched \\{", /* REG_EBRACE */
  656. "Invalid content of \\{\\}", /* REG_BADBR */
  657. "Invalid range end", /* REG_ERANGE */
  658. "Memory exhausted", /* REG_ESPACE */
  659. "Invalid preceding regular expression", /* REG_BADRPT */
  660. "Premature end of regular expression", /* REG_EEND */
  661. "Regular expression too big", /* REG_ESIZE */
  662. "Unmatched ) or \\)", /* REG_ERPAREN */
  663. };
  664. /* Subroutine declarations and macros for regex_compile. */
  665. typedef struct
  666. {
  667. struct compile_stack_elt_t *stack;
  668. unsigned size;
  669. unsigned avail; /* Offset of next open position. */
  670. } compile_stack_type;
  671. /* But patterns can have more than `MAX_REGNUM' registers. We just
  672. ignore the excess. */
  673. typedef unsigned regnum_t;
  674. static void store_op1 (re_opcode_t op, unsigned char *loc, int arg), store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2);
  675. static void insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end), insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end);
  676. static boolean at_begline_loc_p (const char *pattern, const char *p, reg_syntax_t syntax), at_endline_loc_p (const char *pattern, const char *p, int syntax);
  677. static boolean group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum);
  678. static reg_errcode_t compile_range (const char **p_ptr, const char *pend, char *translate, reg_syntax_t syntax, unsigned char *b);
  679. /* Fetch the next character in the uncompiled pattern---translating it
  680. if necessary. Also cast from a signed character in the constant
  681. string passed to us by the user to an unsigned char that we can use
  682. as an array index (in, e.g., `translate'). */
  683. #define PATFETCH(c) \
  684. do {if (p == pend) return REG_EEND; \
  685. c = (unsigned char) *p++; \
  686. if (translate) c = translate[c]; \
  687. } while (0)
  688. /* Fetch the next character in the uncompiled pattern, with no
  689. translation. */
  690. #define PATFETCH_RAW(c) \
  691. do {if (p == pend) return REG_EEND; \
  692. c = (unsigned char) *p++; \
  693. } while (0)
  694. /* Go backwards one character in the pattern. */
  695. #define PATUNFETCH p--
  696. /* If `translate' is non-null, return translate[D], else just D. We
  697. cast the subscript to translate because some data is declared as
  698. `char *', to avoid warnings when a string constant is passed. But
  699. when we use a character as a subscript we must make it unsigned. */
  700. #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (unsigned char)(d))
  701. /* Macros for outputting the compiled pattern into `buffer'. */
  702. /* If the buffer isn't allocated when it comes in, use this. */
  703. #define INIT_BUF_SIZE 32
  704. /* Make sure we have at least N more bytes of space in buffer. */
  705. #define GET_BUFFER_SPACE(n) \
  706. while ((unsigned long)(b - bufp->buffer + (n)) > bufp->allocated) \
  707. EXTEND_BUFFER ()
  708. /* Make sure we have one more byte of buffer space and then add C to it. */
  709. #define BUF_PUSH(c) \
  710. do { \
  711. GET_BUFFER_SPACE (1); \
  712. *b++ = (unsigned char) (c); \
  713. } while (0)
  714. /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
  715. #define BUF_PUSH_2(c1, c2) \
  716. do { \
  717. GET_BUFFER_SPACE (2); \
  718. *b++ = (unsigned char) (c1); \
  719. *b++ = (unsigned char) (c2); \
  720. } while (0)
  721. /* As with BUF_PUSH_2, except for three bytes. */
  722. #define BUF_PUSH_3(c1, c2, c3) \
  723. do { \
  724. GET_BUFFER_SPACE (3); \
  725. *b++ = (unsigned char) (c1); \
  726. *b++ = (unsigned char) (c2); \
  727. *b++ = (unsigned char) (c3); \
  728. } while (0)
  729. /* Store a jump with opcode OP at LOC to location TO. We store a
  730. relative address offset by the three bytes the jump itself occupies. */
  731. #define STORE_JUMP(op, loc, to) \
  732. store_op1 (op, loc, (to) - (loc) - 3)
  733. /* Likewise, for a two-argument jump. */
  734. #define STORE_JUMP2(op, loc, to, arg) \
  735. store_op2 (op, loc, (to) - (loc) - 3, arg)
  736. /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
  737. #define INSERT_JUMP(op, loc, to) \
  738. insert_op1 (op, loc, (to) - (loc) - 3, b)
  739. /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
  740. #define INSERT_JUMP2(op, loc, to, arg) \
  741. insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
  742. /* This is not an arbitrary limit: the arguments which represent offsets
  743. into the pattern are two bytes long. So if 2^16 bytes turns out to
  744. be too small, many things would have to change. */
  745. #define MAX_BUF_SIZE (1L << 16)
  746. /* Extend the buffer by twice its current size via realloc and
  747. reset the pointers that pointed into the old block to point to the
  748. correct places in the new one. If extending the buffer results in it
  749. being larger than MAX_BUF_SIZE, then flag memory exhausted. */
  750. #define EXTEND_BUFFER() \
  751. do { \
  752. unsigned char *old_buffer = bufp->buffer; \
  753. if (bufp->allocated == MAX_BUF_SIZE) \
  754. return REG_ESIZE; \
  755. bufp->allocated <<= 1; \
  756. if (bufp->allocated > MAX_BUF_SIZE) \
  757. bufp->allocated = MAX_BUF_SIZE; \
  758. bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
  759. if (bufp->buffer == NULL) \
  760. return REG_ESPACE; \
  761. /* If the buffer moved, move all the pointers into it. */ \
  762. if (old_buffer != bufp->buffer) \
  763. { \
  764. b = (b - old_buffer) + bufp->buffer; \
  765. begalt = (begalt - old_buffer) + bufp->buffer; \
  766. if (fixup_alt_jump) \
  767. fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
  768. if (laststart) \
  769. laststart = (laststart - old_buffer) + bufp->buffer; \
  770. if (pending_exact) \
  771. pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
  772. } \
  773. } while (0)
  774. /* Since we have one byte reserved for the register number argument to
  775. {start,stop}_memory, the maximum number of groups we can report
  776. things about is what fits in that byte. */
  777. #define MAX_REGNUM 255
  778. /* Macros for the compile stack. */
  779. /* Since offsets can go either forwards or backwards, this type needs to
  780. be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
  781. typedef int pattern_offset_t;
  782. typedef struct compile_stack_elt_t
  783. {
  784. pattern_offset_t begalt_offset;
  785. pattern_offset_t fixup_alt_jump;
  786. pattern_offset_t inner_group_offset;
  787. pattern_offset_t laststart_offset;
  788. regnum_t regnum;
  789. } compile_stack_elt_t;
  790. #define INIT_COMPILE_STACK_SIZE 32
  791. #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
  792. #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
  793. /* The next available element. */
  794. #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
  795. /* Set the bit for character C in a list. */
  796. #define SET_LIST_BIT(c) \
  797. (b[((unsigned char) (c)) / BYTEWIDTH] \
  798. |= 1 << (((unsigned char) c) % BYTEWIDTH))
  799. /* Get the next unsigned number in the uncompiled pattern. */
  800. #define GET_UNSIGNED_NUMBER(num) \
  801. { if (p != pend) \
  802. { \
  803. PATFETCH (c); \
  804. while (ISDIGIT (c)) \
  805. { \
  806. if (num < 0) \
  807. num = 0; \
  808. num = num * 10 + c - '0'; \
  809. if (p == pend) \
  810. break; \
  811. PATFETCH (c); \
  812. } \
  813. } \
  814. }
  815. #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
  816. #define IS_CHAR_CLASS(string) \
  817. (STREQ (string, "alpha") || STREQ (string, "upper") \
  818. || STREQ (string, "lower") || STREQ (string, "digit") \
  819. || STREQ (string, "alnum") || STREQ (string, "xdigit") \
  820. || STREQ (string, "space") || STREQ (string, "print") \
  821. || STREQ (string, "punct") || STREQ (string, "graph") \
  822. || STREQ (string, "cntrl") || STREQ (string, "blank"))
  823. /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
  824. Returns one of error codes defined in `regex.h', or zero for success.
  825. Assumes the `allocated' (and perhaps `buffer') and `translate'
  826. fields are set in BUFP on entry.
  827. If it succeeds, results are put in BUFP (if it returns an error, the
  828. contents of BUFP are undefined):
  829. `buffer' is the compiled pattern;
  830. `syntax' is set to SYNTAX;
  831. `used' is set to the length of the compiled pattern;
  832. `fastmap_accurate' is zero;
  833. `re_nsub' is the number of subexpressions in PATTERN;
  834. `not_bol' and `not_eol' are zero;
  835. The `fastmap' and `newline_anchor' fields are neither
  836. examined nor set. */
  837. static reg_errcode_t regex_compile (const char *pattern, int size, reg_syntax_t syntax, struct re_pattern_buffer *bufp);
  838. static reg_errcode_t
  839. regex_compile (pattern, size, syntax, bufp)
  840. const char *pattern;
  841. int size;
  842. reg_syntax_t syntax;
  843. struct re_pattern_buffer *bufp;
  844. {
  845. /* We fetch characters from PATTERN here. Even though PATTERN is
  846. `char *' (i.e., signed), we declare these variables as unsigned, so
  847. they can be reliably used as array indices. */
  848. register unsigned char c, c1;
  849. /* A random tempory spot in PATTERN. */
  850. const char *p1;
  851. /* Points to the end of the buffer, where we should append. */
  852. register unsigned char *b;
  853. /* Keeps track of unclosed groups. */
  854. compile_stack_type compile_stack;
  855. /* Points to the current (ending) position in the pattern. */
  856. const char *p = pattern;
  857. const char *pend = pattern + size;
  858. /* How to translate the characters in the pattern. */
  859. char *translate = bufp->translate;
  860. /* Address of the count-byte of the most recently inserted `exactn'
  861. command. This makes it possible to tell if a new exact-match
  862. character can be added to that command or if the character requires
  863. a new `exactn' command. */
  864. unsigned char *pending_exact = 0;
  865. /* Address of start of the most recently finished expression.
  866. This tells, e.g., postfix * where to find the start of its
  867. operand. Reset at the beginning of groups and alternatives. */
  868. unsigned char *laststart = 0;
  869. /* Address of beginning of regexp, or inside of last group. */
  870. unsigned char *begalt;
  871. /* Place in the uncompiled pattern (i.e., the {) to
  872. which to go back if the interval is invalid. */
  873. const char *beg_interval;
  874. /* Address of the place where a forward jump should go to the end of
  875. the containing expression. Each alternative of an `or' -- except the
  876. last -- ends with a forward jump of this sort. */
  877. unsigned char *fixup_alt_jump = 0;
  878. /* Counts open-groups as they are encountered. Remembered for the
  879. matching close-group on the compile stack, so the same register
  880. number is put in the stop_memory as the start_memory. */
  881. regnum_t regnum = 0;
  882. #ifdef DEBUG
  883. DEBUG_PRINT1 ("\nCompiling pattern: ");
  884. if (debug)
  885. {
  886. unsigned debug_count;
  887. for (debug_count = 0; debug_count < size; debug_count++)
  888. printchar (pattern[debug_count]);
  889. putchar ('\n');
  890. }
  891. #endif /* DEBUG */
  892. /* Initialize the compile stack. */
  893. compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
  894. if (compile_stack.stack == NULL)
  895. return REG_ESPACE;
  896. compile_stack.size = INIT_COMPILE_STACK_SIZE;
  897. compile_stack.avail = 0;
  898. /* Initialize the pattern buffer. */
  899. bufp->syntax = syntax;
  900. bufp->fastmap_accurate = 0;
  901. bufp->not_bol = bufp->not_eol = 0;
  902. /* Set `used' to zero, so that if we return an error, the pattern
  903. printer (for debugging) will think there's no pattern. We reset it
  904. at the end. */
  905. bufp->used = 0;
  906. /* Always count groups, whether or not bufp->no_sub is set. */
  907. bufp->re_nsub = 0;
  908. #if !defined (emacs) && !defined (SYNTAX_TABLE)
  909. /* Initialize the syntax table. */
  910. init_syntax_once ();
  911. #endif
  912. if (bufp->allocated == 0)
  913. {
  914. if (bufp->buffer)
  915. { /* If zero allocated, but buffer is non-null, try to realloc
  916. enough space. This loses if buffer's address is bogus, but
  917. that is the user's responsibility. */
  918. RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
  919. }
  920. else
  921. { /* Caller did not allocate a buffer. Do it for them. */
  922. bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
  923. }
  924. if (!bufp->buffer) return REG_ESPACE;
  925. bufp->allocated = INIT_BUF_SIZE;
  926. }
  927. begalt = b = bufp->buffer;
  928. /* Loop through the uncompiled pattern until we're at the end. */
  929. while (p != pend)
  930. {
  931. PATFETCH (c);
  932. switch (c)
  933. {
  934. case '^':
  935. {
  936. if ( /* If at start of pattern, it's an operator. */
  937. p == pattern + 1
  938. /* If context independent, it's an operator. */
  939. || syntax & RE_CONTEXT_INDEP_ANCHORS
  940. /* Otherwise, depends on what's come before. */
  941. || at_begline_loc_p (pattern, p, syntax))
  942. BUF_PUSH (begline);
  943. else
  944. goto normal_char;
  945. }
  946. break;
  947. case '$':
  948. {
  949. if ( /* If at end of pattern, it's an operator. */
  950. p == pend
  951. /* If context independent, it's an operator. */
  952. || syntax & RE_CONTEXT_INDEP_ANCHORS
  953. /* Otherwise, depends on what's next. */
  954. || at_endline_loc_p (p, pend, syntax))
  955. BUF_PUSH (endline);
  956. else
  957. goto normal_char;
  958. }
  959. break;
  960. case '+':
  961. case '?':
  962. if ((syntax & RE_BK_PLUS_QM)
  963. || (syntax & RE_LIMITED_OPS))
  964. goto normal_char;
  965. handle_plus:
  966. case '*':
  967. /* If there is no previous pattern... */
  968. if (!laststart)
  969. {
  970. if (syntax & RE_CONTEXT_INVALID_OPS)
  971. return REG_BADRPT;
  972. else if (!(syntax & RE_CONTEXT_INDEP_OPS))
  973. goto normal_char;
  974. }
  975. {
  976. /* Are we optimizing this jump? */
  977. boolean keep_string_p = false;
  978. /* 1 means zero (many) matches is allowed. */
  979. char zero_times_ok = 0, many_times_ok = 0;
  980. /* If there is a sequence of repetition chars, collapse it
  981. down to just one (the right one). We can't combine
  982. interval operators with these because of, e.g., `a{2}*',
  983. which should only match an even number of `a's. */
  984. for (;;)
  985. {
  986. zero_times_ok |= c != '+';
  987. many_times_ok |= c != '?';
  988. if (p == pend)
  989. break;
  990. PATFETCH (c);
  991. if (c == '*'
  992. || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
  993. ;
  994. else if (syntax & RE_BK_PLUS_QM && c == '\\')
  995. {
  996. if (p == pend) return REG_EESCAPE;
  997. PATFETCH (c1);
  998. if (!(c1 == '+' || c1 == '?'))
  999. {
  1000. PATUNFETCH;
  1001. PATUNFETCH;
  1002. break;
  1003. }
  1004. c = c1;
  1005. }
  1006. else
  1007. {
  1008. PATUNFETCH;
  1009. break;
  1010. }
  1011. /* If we get here, we found another repeat character. */
  1012. }
  1013. /* Star, etc. applied to an empty pattern is equivalent
  1014. to an empty pattern. */
  1015. if (!laststart)
  1016. break;
  1017. /* Now we know whether or not zero matches is allowed
  1018. and also whether or not two or more matches is allowed. */
  1019. if (many_times_ok)
  1020. { /* More than one repetition is allowed, so put in at the
  1021. end a backward relative jump from `b' to before the next
  1022. jump we're going to put in below (which jumps from
  1023. laststart to after this jump).
  1024. But if we are at the `*' in the exact sequence `.*\n',
  1025. insert an unconditional jump backwards to the .,
  1026. instead of the beginning of the loop. This way we only
  1027. push a failure point once, instead of every time
  1028. through the loop. */
  1029. assert (p - 1 > pattern);
  1030. /* Allocate the space for the jump. */
  1031. GET_BUFFER_SPACE (3);
  1032. /* We know we are not at the first character of the pattern,
  1033. because laststart was nonzero. And we've already
  1034. incremented `p', by the way, to be the character after
  1035. the `*'. Do we have to do something analogous here
  1036. for null bytes, because of RE_DOT_NOT_NULL? */
  1037. if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
  1038. && zero_times_ok
  1039. && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
  1040. && !(syntax & RE_DOT_NEWLINE))
  1041. { /* We have .*\n. */
  1042. STORE_JUMP (jump, b, laststart);
  1043. keep_string_p = true;
  1044. }
  1045. else
  1046. /* Anything else. */
  1047. STORE_JUMP (maybe_pop_jump, b, laststart - 3);
  1048. /* We've added more stuff to the buffer. */
  1049. b += 3;
  1050. }
  1051. /* On failure, jump from laststart to b + 3, which will be the
  1052. end of the buffer after this jump is inserted. */
  1053. GET_BUFFER_SPACE (3);
  1054. INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
  1055. : on_failure_jump,
  1056. laststart, b + 3);
  1057. pending_exact = 0;
  1058. b += 3;
  1059. if (!zero_times_ok)
  1060. {
  1061. /* At least one repetition is required, so insert a
  1062. `dummy_failure_jump' before the initial
  1063. `on_failure_jump' instruction of the loop. This
  1064. effects a skip over that instruction the first time
  1065. we hit that loop. */
  1066. GET_BUFFER_SPACE (3);
  1067. INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
  1068. b += 3;
  1069. }
  1070. }
  1071. break;
  1072. case '.':
  1073. laststart = b;
  1074. BUF_PUSH (anychar);
  1075. break;
  1076. case '[':
  1077. {
  1078. boolean had_char_class = false;
  1079. if (p == pend) return REG_EBRACK;
  1080. /* Ensure that we have enough space to push a charset: the
  1081. opcode, the length count, and the bitset; 34 bytes in all. */
  1082. GET_BUFFER_SPACE (34);
  1083. laststart = b;
  1084. /* We test `*p == '^' twice, instead of using an if
  1085. statement, so we only need one BUF_PUSH. */
  1086. BUF_PUSH (*p == '^' ? charset_not : charset);
  1087. if (*p == '^')
  1088. p++;
  1089. /* Remember the first position in the bracket expression. */
  1090. p1 = p;
  1091. /* Push the number of bytes in the bitmap. */
  1092. BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
  1093. /* Clear the whole map. */
  1094. bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
  1095. /* charset_not matches newline according to a syntax bit. */
  1096. if ((re_opcode_t) b[-2] == charset_not
  1097. && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
  1098. SET_LIST_BIT ('\n');
  1099. /* Read in characters and ranges, setting map bits. */
  1100. for (;;)
  1101. {
  1102. if (p == pend) return REG_EBRACK;
  1103. PATFETCH (c);
  1104. /* \ might escape characters inside [...] and [^...]. */
  1105. if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
  1106. {
  1107. if (p == pend) return REG_EESCAPE;
  1108. PATFETCH (c1);
  1109. SET_LIST_BIT (c1);
  1110. continue;
  1111. }
  1112. /* Could be the end of the bracket expression. If it's
  1113. not (i.e., when the bracket expression is `[]' so
  1114. far), the ']' character bit gets set way below. */
  1115. if (c == ']' && p != p1 + 1)
  1116. break;
  1117. /* Look ahead to see if it's a range when the last thing
  1118. was a character class. */
  1119. if (had_char_class && c == '-' && *p != ']')
  1120. return REG_ERANGE;
  1121. /* Look ahead to see if it's a range when the last thing
  1122. was a character: if this is a hyphen not at the
  1123. beginning or the end of a list, then it's the range
  1124. operator. */
  1125. if (c == '-'
  1126. && !(p - 2 >= pattern && p[-2] == '[')
  1127. && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
  1128. && *p != ']')
  1129. {
  1130. reg_errcode_t ret
  1131. = compile_range (&p, pend, translate, syntax, b);
  1132. if (ret != REG_NOERROR) return ret;
  1133. }
  1134. else if (p[0] == '-' && p[1] != ']')
  1135. { /* This handles ranges made up of characters only. */
  1136. reg_errcode_t ret;
  1137. /* Move past the `-'. */
  1138. PATFETCH (c1);
  1139. ret = compile_range (&p, pend, translate, syntax, b);
  1140. if (ret != REG_NOERROR) return ret;
  1141. }
  1142. /* See if we're at the beginning of a possible character
  1143. class. */
  1144. else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
  1145. { /* Leave room for the null. */
  1146. char str[CHAR_CLASS_MAX_LENGTH + 1];
  1147. PATFETCH (c);
  1148. c1 = 0;
  1149. /* If pattern is `[[:'. */
  1150. if (p == pend) return REG_EBRACK;
  1151. for (;;)
  1152. {
  1153. PATFETCH (c);
  1154. if (c == ':' || c == ']' || p == pend
  1155. || c1 == CHAR_CLASS_MAX_LENGTH)
  1156. break;
  1157. str[c1++] = c;
  1158. }
  1159. str[c1] = '\0';
  1160. /* If isn't a word bracketed by `[:' and:`]':
  1161. undo the ending character, the letters, and leave
  1162. the leading `:' and `[' (but set bits for them). */
  1163. if (c == ':' && *p == ']')
  1164. {
  1165. int ch;
  1166. boolean is_alnum = STREQ (str, "alnum");
  1167. boolean is_alpha = STREQ (str, "alpha");
  1168. boolean is_blank = STREQ (str, "blank");
  1169. boolean is_cntrl = STREQ (str, "cntrl");
  1170. boolean is_digit = STREQ (str, "digit");
  1171. boolean is_graph = STREQ (str, "graph");
  1172. boolean is_lower = STREQ (str, "lower");
  1173. boolean is_print = STREQ (str, "print");
  1174. boolean is_punct = STREQ (str, "punct");
  1175. boolean is_space = STREQ (str, "space");
  1176. boolean is_upper = STREQ (str, "upper");
  1177. boolean is_xdigit = STREQ (str, "xdigit");
  1178. if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
  1179. /* Throw away the ] at the end of the character
  1180. class. */
  1181. PATFETCH (c);
  1182. if (p == pend) return REG_EBRACK;
  1183. for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
  1184. {
  1185. if ( (is_alnum && ISALNUM (ch))
  1186. || (is_alpha && ISALPHA (ch))
  1187. || (is_blank && ISBLANK (ch))
  1188. || (is_cntrl && ISCNTRL (ch))
  1189. || (is_digit && ISDIGIT (ch))
  1190. || (is_graph && ISGRAPH (ch))
  1191. || (is_lower && ISLOWER (ch))
  1192. || (is_print && ISPRINT (ch))
  1193. || (is_punct && ISPUNCT (ch))
  1194. || (is_space && ISSPACE (ch))
  1195. || (is_upper && ISUPPER (ch))
  1196. || (is_xdigit && ISXDIGIT (ch)))
  1197. SET_LIST_BIT (ch);
  1198. }
  1199. had_char_class = true;
  1200. }
  1201. else
  1202. {
  1203. c1++;
  1204. while (c1--)
  1205. PATUNFETCH;
  1206. SET_LIST_BIT ('[');
  1207. SET_LIST_BIT (':');
  1208. had_char_class = false;
  1209. }
  1210. }
  1211. else
  1212. {
  1213. had_char_class = false;
  1214. SET_LIST_BIT (c);
  1215. }
  1216. }
  1217. /* Discard any (non)matching list bytes that are all 0 at the
  1218. end of the map. Decrease the map-length byte too. */
  1219. while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
  1220. b[-1]--;
  1221. b += b[-1];
  1222. }
  1223. break;
  1224. case '(':
  1225. if (syntax & RE_NO_BK_PARENS)
  1226. goto handle_open;
  1227. else
  1228. goto normal_char;
  1229. case ')':
  1230. if (syntax & RE_NO_BK_PARENS)
  1231. goto handle_close;
  1232. else
  1233. goto normal_char;
  1234. case '\n':
  1235. if (syntax & RE_NEWLINE_ALT)
  1236. goto handle_alt;
  1237. else
  1238. goto normal_char;
  1239. case '|':
  1240. if (syntax & RE_NO_BK_VBAR)
  1241. goto handle_alt;
  1242. else
  1243. goto normal_char;
  1244. case '{':
  1245. if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
  1246. goto handle_interval;
  1247. else
  1248. goto normal_char;
  1249. case '\\':
  1250. if (p == pend) return REG_EESCAPE;
  1251. /* Do not translate the character after the \, so that we can
  1252. distinguish, e.g., \B from \b, even if we normally would
  1253. translate, e.g., B to b. */
  1254. PATFETCH_RAW (c);
  1255. switch (c)
  1256. {
  1257. case '(':
  1258. if (syntax & RE_NO_BK_PARENS)
  1259. goto normal_backslash;
  1260. handle_open:
  1261. bufp->re_nsub++;
  1262. regnum++;
  1263. if (COMPILE_STACK_FULL)
  1264. {
  1265. RETALLOC (compile_stack.stack, compile_stack.size << 1,
  1266. compile_stack_elt_t);
  1267. if (compile_stack.stack == NULL) return REG_ESPACE;
  1268. compile_stack.size <<= 1;
  1269. }
  1270. /* These are the values to restore when we hit end of this
  1271. group. They are all relative offsets, so that if the
  1272. whole pattern moves because of realloc, they will still
  1273. be valid. */
  1274. COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
  1275. COMPILE_STACK_TOP.fixup_alt_jump
  1276. = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
  1277. COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
  1278. COMPILE_STACK_TOP.regnum = regnum;
  1279. /* We will eventually replace the 0 with the number of
  1280. groups inner to this one. But do not push a
  1281. start_memory for groups beyond the last one we can
  1282. represent in the compiled pattern. */
  1283. if (regnum <= MAX_REGNUM)
  1284. {
  1285. COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
  1286. BUF_PUSH_3 (start_memory, regnum, 0);
  1287. }
  1288. compile_stack.avail++;
  1289. fixup_alt_jump = 0;
  1290. laststart = 0;
  1291. begalt = b;
  1292. /* If we've reached MAX_REGNUM groups, then this open
  1293. won't actually generate any code, so we'll have to
  1294. clear pending_exact explicitly. */
  1295. pending_exact = 0;
  1296. break;
  1297. case ')':
  1298. if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
  1299. /* snax: added braces here to elimnate gcc warning */
  1300. if (COMPILE_STACK_EMPTY)
  1301. {
  1302. if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  1303. goto normal_backslash;
  1304. else
  1305. return REG_ERPAREN;
  1306. }
  1307. handle_close:
  1308. if (fixup_alt_jump)
  1309. { /* Push a dummy failure point at the end of the
  1310. alternative for a possible future
  1311. `pop_failure_jump' to pop. See comments at
  1312. `push_dummy_failure' in `re_match_2'. */
  1313. BUF_PUSH (push_dummy_failure);
  1314. /* We allocated space for this jump when we assigned
  1315. to `fixup_alt_jump', in the `handle_alt' case below. */
  1316. STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
  1317. }
  1318. /* snax: added braces here too */
  1319. /* See similar code for backslashed left paren above. */
  1320. if (COMPILE_STACK_EMPTY)
  1321. {
  1322. if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  1323. goto normal_char;
  1324. else
  1325. return REG_ERPAREN;
  1326. }
  1327. /* Since we just checked for an empty stack above, this
  1328. ``can't happen''. */
  1329. assert (compile_stack.avail != 0);
  1330. {
  1331. /* We don't just want to restore into `regnum', because
  1332. later groups should continue to be numbered higher,
  1333. as in `(ab)c(de)' -- the second group is #2. */
  1334. regnum_t this_group_regnum;
  1335. compile_stack.avail--;
  1336. begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
  1337. fixup_alt_jump
  1338. = COMPILE_STACK_TOP.fixup_alt_jump
  1339. ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
  1340. : 0;
  1341. laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
  1342. this_group_regnum = COMPILE_STACK_TOP.regnum;
  1343. /* If we've reached MAX_REGNUM groups, then this open
  1344. won't actually generate any code, so we'll have to
  1345. clear pending_exact explicitly. */
  1346. pending_exact = 0;
  1347. /* We're at the end of the group, so now we know how many
  1348. groups were inside this one. */
  1349. if (this_group_regnum <= MAX_REGNUM)
  1350. {
  1351. unsigned char *inner_group_loc
  1352. = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
  1353. *inner_group_loc = regnum - this_group_regnum;
  1354. BUF_PUSH_3 (stop_memory, this_group_regnum,
  1355. regnum - this_group_regnum);
  1356. }
  1357. }
  1358. break;
  1359. case '|': /* `\|'. */
  1360. if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
  1361. goto normal_backslash;
  1362. handle_alt:
  1363. if (syntax & RE_LIMITED_OPS)
  1364. goto normal_char;
  1365. /* Insert before the previous alternative a jump which
  1366. jumps to this alternative if the former fails. */
  1367. GET_BUFFER_SPACE (3);
  1368. INSERT_JUMP (on_failure_jump, begalt, b + 6);
  1369. pending_exact = 0;
  1370. b += 3;
  1371. /* The alternative before this one has a jump after it
  1372. which gets executed if it gets matched. Adjust that
  1373. jump so it will jump to this alternative's analogous
  1374. jump (put in below, which in turn will jump to the next
  1375. (if any) alternative's such jump, etc.). The last such
  1376. jump jumps to the correct final destination. A picture:
  1377. _____ _____
  1378. | | | |
  1379. | v | v
  1380. a | b | c
  1381. If we are at `b', then fixup_alt_jump right now points to a
  1382. three-byte space after `a'. We'll put in the jump, set
  1383. fixup_alt_jump to right after `b', and leave behind three
  1384. bytes which we'll fill in when we get to after `c'. */
  1385. if (fixup_alt_jump)
  1386. STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
  1387. /* Mark and leave space for a jump after this alternative,
  1388. to be filled in later either by next alternative or
  1389. when know we're at the end of a series of alternatives. */
  1390. fixup_alt_jump = b;
  1391. GET_BUFFER_SPACE (3);
  1392. b += 3;
  1393. laststart = 0;
  1394. begalt = b;
  1395. break;
  1396. case '{':
  1397. /* If \{ is a literal. */
  1398. if (!(syntax & RE_INTERVALS)
  1399. /* If we're at `\{' and it's not the open-interval
  1400. operator. */
  1401. || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  1402. || (p - 2 == pattern && p == pend))
  1403. goto normal_backslash;
  1404. handle_interval:
  1405. {
  1406. /* If got here, then the syntax allows intervals. */
  1407. /* At least (most) this many matches must be made. */
  1408. int lower_bound = -1, upper_bound = -1;
  1409. beg_interval = p - 1;
  1410. if (p == pend)
  1411. {
  1412. if (syntax & RE_NO_BK_BRACES)
  1413. goto unfetch_interval;
  1414. else
  1415. return REG_EBRACE;
  1416. }
  1417. GET_UNSIGNED_NUMBER (lower_bound);
  1418. if (c == ',')
  1419. {
  1420. GET_UNSIGNED_NUMBER (upper_bound);
  1421. if (upper_bound < 0) upper_bound = RE_DUP_MAX;
  1422. }
  1423. else
  1424. /* Interval such as `{1}' => match exactly once. */
  1425. upper_bound = lower_bound;
  1426. if (lower_bound < 0 || upper_bound > RE_DUP_MAX
  1427. || lower_bound > upper_bound)
  1428. {
  1429. if (syntax & RE_NO_BK_BRACES)
  1430. goto unfetch_interval;
  1431. else
  1432. return REG_BADBR;
  1433. }
  1434. if (!(syntax & RE_NO_BK_BRACES))
  1435. {
  1436. if (c != '\\') return REG_EBRACE;
  1437. PATFETCH (c);
  1438. }
  1439. if (c != '}')
  1440. {
  1441. if (syntax & RE_NO_BK_BRACES)
  1442. goto unfetch_interval;
  1443. else
  1444. return REG_BADBR;
  1445. }
  1446. /* We just parsed a valid interval. */
  1447. /* If it's invalid to have no preceding re. */
  1448. if (!laststart)
  1449. {
  1450. if (syntax & RE_CONTEXT_INVALID_OPS)
  1451. return REG_BADRPT;
  1452. else if (syntax & RE_CONTEXT_INDEP_OPS)
  1453. laststart = b;
  1454. else
  1455. goto unfetch_interval;
  1456. }
  1457. /* If the upper bound is zero, don't want to succeed at
  1458. all; jump from `laststart' to `b + 3', which will be
  1459. the end of the buffer after we insert the jump. */
  1460. if (upper_bound == 0)
  1461. {
  1462. GET_BUFFER_SPACE (3);
  1463. INSERT_JUMP (jump, laststart, b + 3);
  1464. b += 3;
  1465. }
  1466. /* Otherwise, we have a nontrivial interval. When
  1467. we're all done, the pattern will look like:
  1468. set_number_at <jump count> <upper bound>
  1469. set_number_at <succeed_n count> <lower bound>
  1470. succeed_n <after jump addr> <succed_n count>
  1471. <body of loop>
  1472. jump_n <succeed_n addr> <jump count>
  1473. (The upper bound and `jump_n' are omitted if
  1474. `upper_bound' is 1, though.) */
  1475. else
  1476. { /* If the upper bound is > 1, we need to insert
  1477. more at the end of the loop. */
  1478. unsigned nbytes = 10 + (upper_bound > 1) * 10;
  1479. GET_BUFFER_SPACE (nbytes);
  1480. /* Initialize lower bound of the `succeed_n', even
  1481. though it will be set during matching by its
  1482. attendant `set_number_at' (inserted next),
  1483. because `re_compile_fastmap' needs to know.
  1484. Jump to the `jump_n' we might insert below. */
  1485. INSERT_JUMP2 (succeed_n, laststart,
  1486. b + 5 + (upper_bound > 1) * 5,
  1487. lower_bound);
  1488. b += 5;
  1489. /* Code to initialize the lower bound. Insert
  1490. before the `succeed_n'. The `5' is the last two
  1491. bytes of this `set_number_at', plus 3 bytes of
  1492. the following `succeed_n'. */
  1493. insert_op2 (set_number_at, laststart, 5, lower_bound, b);
  1494. b += 5;
  1495. if (upper_bound > 1)
  1496. { /* More than one repetition is allowed, so
  1497. append a backward jump to the `succeed_n'
  1498. that starts this interval.
  1499. When we've reached this during matching,
  1500. we'll have matched the interval once, so
  1501. jump back only `upper_bound - 1' times. */
  1502. STORE_JUMP2 (jump_n, b, laststart + 5,
  1503. upper_bound - 1);
  1504. b += 5;
  1505. /* The location we want to set is the second
  1506. parameter of the `jump_n'; that is `b-2' as
  1507. an absolute address. `laststart' will be
  1508. the `set_number_at' we're about to insert;
  1509. `laststart+3' the number to set, the source
  1510. for the relative address. But we are
  1511. inserting into the middle of the pattern --
  1512. so everything is getting moved up by 5.
  1513. Conclusion: (b - 2) - (laststart + 3) + 5,
  1514. i.e., b - laststart.
  1515. We insert this at the beginning of the loop
  1516. so that if we fail during matching, we'll
  1517. reinitialize the bounds. */
  1518. insert_op2 (set_number_at, laststart, b - laststart,
  1519. upper_bound - 1, b);
  1520. b += 5;
  1521. }
  1522. }
  1523. pending_exact = 0;
  1524. beg_interval = NULL;
  1525. }
  1526. break;
  1527. unfetch_interval:
  1528. /* If an invalid interval, match the characters as literals. */
  1529. assert (beg_interval);
  1530. p = beg_interval;
  1531. beg_interval = NULL;
  1532. /* normal_char and normal_backslash need `c'. */
  1533. PATFETCH (c);
  1534. if (!(syntax & RE_NO_BK_BRACES))
  1535. {
  1536. if (p > pattern && p[-1] == '\\')
  1537. goto normal_backslash;
  1538. }
  1539. goto normal_char;
  1540. #ifdef emacs
  1541. /* There is no way to specify the before_dot and after_dot
  1542. operators. rms says this is ok. --karl */
  1543. case '=':
  1544. BUF_PUSH (at_dot);
  1545. break;
  1546. case 's':
  1547. laststart = b;
  1548. PATFETCH (c);
  1549. BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
  1550. break;
  1551. case 'S':
  1552. laststart = b;
  1553. PATFETCH (c);
  1554. BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
  1555. break;
  1556. #endif /* emacs */
  1557. case 'w':
  1558. laststart = b;
  1559. BUF_PUSH (wordchar);
  1560. break;
  1561. case 'W':
  1562. laststart = b;
  1563. BUF_PUSH (notwordchar);
  1564. break;
  1565. case '<':
  1566. BUF_PUSH (wordbeg);
  1567. break;
  1568. case '>':
  1569. BUF_PUSH (wordend);
  1570. break;
  1571. case 'b':
  1572. BUF_PUSH (wordbound);
  1573. break;
  1574. case 'B':
  1575. BUF_PUSH (notwordbound);
  1576. break;
  1577. case '`':
  1578. BUF_PUSH (begbuf);
  1579. break;
  1580. case '\'':
  1581. BUF_PUSH (endbuf);
  1582. break;
  1583. case '1': case '2': case '3': case '4': case '5':
  1584. case '6': case '7': case '8': case '9':
  1585. if (syntax & RE_NO_BK_REFS)
  1586. goto normal_char;
  1587. c1 = c - '0';
  1588. if (c1 > regnum)
  1589. return REG_ESUBREG;
  1590. /* Can't back reference to a subexpression if inside of it. */
  1591. if (group_in_compile_stack (compile_stack, c1))
  1592. goto normal_char;
  1593. laststart = b;
  1594. BUF_PUSH_2 (duplicate, c1);
  1595. break;
  1596. case '+':
  1597. case '?':
  1598. if (syntax & RE_BK_PLUS_QM)
  1599. goto handle_plus;
  1600. else
  1601. goto normal_backslash;
  1602. default:
  1603. normal_backslash:
  1604. /* You might think it would be useful for \ to mean
  1605. not to translate; but if we don't translate