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 6 Copyright (C) 1993 Free Software Foundation, Inc. 7 8 This program is free software; you can redistribute it and/or modify 9 it under the terms of the GNU General Public License as published by 10 the Free Software Foundation; either version 2, or (at your option) 11 any later version. 12 13 This program is distributed in the hope that it will be useful, 14 but WITHOUT ANY WARRANTY; without even the implied warranty of 15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 GNU General Public License for more details. 17 18 You should have received a copy of the GNU General Public License 19 along with this program; if not, write to the Free Software 20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ 21 22/* AIX requires this to be the first thing in the file. */ 23#if defined (_AIX) && !defined (REGEX_MALLOC) 24#pragma alloca 25#endif 26 27#define _GNU_SOURCE 28 29/* We need this for `regex.h', and perhaps for the Emacs include files. */ 30#include <sys/types.h> 31 32/* We used to test for `BSTRING' here, but only GCC and Emacs define 33 `BSTRING', as far as I know, and neither of them use this code. */ 34#include <string.h> 35#ifndef bcmp 36#define bcmp(s1, s2, n) memcmp ((s1), (s2), (n)) 37#endif 38#ifndef bcopy 39#define bcopy(s, d, n) memcpy ((d), (s), (n)) 40#endif 41#ifndef bzero 42#define bzero(s, n) memset ((s), 0, (n)) 43#endif 44 45#include <stdlib.h> 46 47 48/* Define the syntax stuff for \<, \>, etc. */ 49 50/* This must be nonzero for the wordchar and notwordchar pattern 51 commands in re_match_2. */ 52#ifndef Sword 53#define Sword 1 54#endif 55 56#ifdef SYNTAX_TABLE 57 58externchar*re_syntax_table; 59 60#else/* not SYNTAX_TABLE */ 61 62/* How many characters in the character set. */ 63#define CHAR_SET_SIZE 256 64 65static char re_syntax_table[CHAR_SET_SIZE]; 66 67static void 68init_syntax_once() 69{ 70registerint c; 71static int done =0; 72 73if(done) 74return; 75 76bzero(re_syntax_table,sizeof re_syntax_table); 77 78for(c ='a'; c <='z'; c++) 79 re_syntax_table[c] = Sword; 80 81for(c ='A'; c <='Z'; c++) 82 re_syntax_table[c] = Sword; 83 84for(c ='0'; c <='9'; c++) 85 re_syntax_table[c] = Sword; 86 87 re_syntax_table['_'] = Sword; 88 89 done =1; 90} 91 92#endif/* not SYNTAX_TABLE */ 93 94#define SYNTAX(c) re_syntax_table[c] 95 96\f 97/* Get the interface, including the syntax bits. */ 98#include"regex.h" 99 100/* isalpha etc. are used for the character classes. */ 101#include <ctype.h> 102 103#ifndef isascii 104#define isascii(c) 1 105#endif 106 107#ifdef isblank 108#define ISBLANK(c) (isascii (c) && isblank (c)) 109#else 110#define ISBLANK(c) ((c) ==' ' || (c) =='\t') 111#endif 112#ifdef isgraph 113#define ISGRAPH(c) (isascii (c) && isgraph (c)) 114#else 115#define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c)) 116#endif 117 118#define ISPRINT(c) (isascii (c) && isprint (c)) 119#define ISDIGIT(c) (isascii (c) && isdigit (c)) 120#define ISALNUM(c) (isascii (c) && isalnum (c)) 121#define ISALPHA(c) (isascii (c) && isalpha (c)) 122#define ISCNTRL(c) (isascii (c) && iscntrl (c)) 123#define ISLOWER(c) (isascii (c) && islower (c)) 124#define ISPUNCT(c) (isascii (c) && ispunct (c)) 125#define ISSPACE(c) (isascii (c) && isspace (c)) 126#define ISUPPER(c) (isascii (c) && isupper (c)) 127#define ISXDIGIT(c) (isascii (c) && isxdigit (c)) 128 129#ifndef NULL 130#define NULL 0 131#endif 132 133/* We remove any previous definition of `SIGN_EXTEND_CHAR', 134 since ours (we hope) works properly with all combinations of 135 machines, compilers, `char' and `unsigned char' argument types. 136 (Per Bothner suggested the basic approach.) */ 137#undef SIGN_EXTEND_CHAR 138#if __STDC__ 139#define SIGN_EXTEND_CHAR(c) ((signed char) (c)) 140#else/* not __STDC__ */ 141/* As in Harbison and Steele. */ 142#define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128) 143#endif 144\f 145/* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we 146 use `alloca' instead of `malloc'. This is because using malloc in 147 re_search* or re_match* could cause memory leaks when C-g is used in 148 Emacs; also, malloc is slower and causes storage fragmentation. On 149 the other hand, malloc is more portable, and easier to debug. 150 151 Because we sometimes use alloca, some routines have to be macros, 152 not functions -- `alloca'-allocated space disappears at the end of the 153 function it is called in. */ 154 155#ifdef REGEX_MALLOC 156 157#define REGEX_ALLOCATE malloc 158#define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize) 159 160#else/* not REGEX_MALLOC */ 161 162/* Emacs already defines alloca, sometimes. */ 163#ifndef alloca 164 165/* Make alloca work the best possible way. */ 166#ifdef __GNUC__ 167#define alloca __builtin_alloca 168#else/* not __GNUC__ */ 169#if HAVE_ALLOCA_H 170#include <alloca.h> 171#else/* not __GNUC__ or HAVE_ALLOCA_H */ 172#ifndef _AIX/* Already did AIX, up at the top. */ 173char*alloca(); 174#endif/* not _AIX */ 175#endif/* not HAVE_ALLOCA_H */ 176#endif/* not __GNUC__ */ 177 178#endif/* not alloca */ 179 180#define REGEX_ALLOCATE alloca 181 182/* Assumes a `char *destination' variable. */ 183#define REGEX_REALLOCATE(source, osize, nsize) \ 184 (destination = (char *) alloca (nsize), \ 185 bcopy (source, destination, osize), \ 186 destination) 187 188#endif/* not REGEX_MALLOC */ 189 190 191/* True if `size1' is non-NULL and PTR is pointing anywhere inside 192 `string1' or just past its end. This works if PTR is NULL, which is 193 a good thing. */ 194#define FIRST_STRING_P(ptr) \ 195 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1) 196 197/* (Re)Allocate N items of type T using malloc, or fail. */ 198#define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t))) 199#define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t))) 200#define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t))) 201 202#define BYTEWIDTH 8/* In bits. */ 203 204#define STREQ(s1, s2) ((strcmp (s1, s2) == 0)) 205 206#define MAX(a, b) ((a) > (b) ? (a) : (b)) 207#define MIN(a, b) ((a) < (b) ? (a) : (b)) 208 209typedefchar boolean; 210#define false 0 211#define true 1 212\f 213/* These are the command codes that appear in compiled regular 214 expressions. Some opcodes are followed by argument bytes. A 215 command code can specify any interpretation whatsoever for its 216 arguments. Zero bytes may appear in the compiled regular expression. 217 218 The value of `exactn' is needed in search.c (search_buffer) in Emacs. 219 So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of 220 `exactn' we use here must also be 1. */ 221 222typedefenum 223{ 224 no_op =0, 225 226/* Followed by one byte giving n, then by n literal bytes. */ 227 exactn =1, 228 229/* Matches any (more or less) character. */ 230 anychar, 231 232/* Matches any one char belonging to specified set. First 233 following byte is number of bitmap bytes. Then come bytes 234 for a bitmap saying which chars are in. Bits in each byte 235 are ordered low-bit-first. A character is in the set if its 236 bit is 1. A character too large to have a bit in the map is 237 automatically not in the set. */ 238 charset, 239 240/* Same parameters as charset, but match any character that is 241 not one of those specified. */ 242 charset_not, 243 244/* Start remembering the text that is matched, for storing in a 245 register. Followed by one byte with the register number, in 246 the range 0 to one less than the pattern buffer's re_nsub 247 field. Then followed by one byte with the number of groups 248 inner to this one. (This last has to be part of the 249 start_memory only because we need it in the on_failure_jump 250 of re_match_2.) */ 251 start_memory, 252 253/* Stop remembering the text that is matched and store it in a 254 memory register. Followed by one byte with the register 255 number, in the range 0 to one less than `re_nsub' in the 256 pattern buffer, and one byte with the number of inner groups, 257 just like `start_memory'. (We need the number of inner 258 groups here because we don't have any easy way of finding the 259 corresponding start_memory when we're at a stop_memory.) */ 260 stop_memory, 261 262/* Match a duplicate of something remembered. Followed by one 263 byte containing the register number. */ 264 duplicate, 265 266/* Fail unless at beginning of line. */ 267 begline, 268 269/* Fail unless at end of line. */ 270 endline, 271 272/* Succeeds if at beginning of buffer (if emacs) or at beginning 273 of string to be matched (if not). */ 274 begbuf, 275 276/* Analogously, for end of buffer/string. */ 277 endbuf, 278 279/* Followed by two byte relative address to which to jump. */ 280 jump, 281 282/* Same as jump, but marks the end of an alternative. */ 283 jump_past_alt, 284 285/* Followed by two-byte relative address of place to resume at 286 in case of failure. */ 287 on_failure_jump, 288 289/* Like on_failure_jump, but pushes a placeholder instead of the 290 current string position when executed. */ 291 on_failure_keep_string_jump, 292 293/* Throw away latest failure point and then jump to following 294 two-byte relative address. */ 295 pop_failure_jump, 296 297/* Change to pop_failure_jump if know won't have to backtrack to 298 match; otherwise change to jump. This is used to jump 299 back to the beginning of a repeat. If what follows this jump 300 clearly won't match what the repeat does, such that we can be 301 sure that there is no use backtracking out of repetitions 302 already matched, then we change it to a pop_failure_jump. 303 Followed by two-byte address. */ 304 maybe_pop_jump, 305 306/* Jump to following two-byte address, and push a dummy failure 307 point. This failure point will be thrown away if an attempt 308 is made to use it for a failure. A `+' construct makes this 309 before the first repeat. Also used as an intermediary kind 310 of jump when compiling an alternative. */ 311 dummy_failure_jump, 312 313/* Push a dummy failure point and continue. Used at the end of 314 alternatives. */ 315 push_dummy_failure, 316 317/* Followed by two-byte relative address and two-byte number n. 318 After matching N times, jump to the address upon failure. */ 319 succeed_n, 320 321/* Followed by two-byte relative address, and two-byte number n. 322 Jump to the address N times, then fail. */ 323 jump_n, 324 325/* Set the following two-byte relative address to the 326 subsequent two-byte number. The address *includes* the two 327 bytes of number. */ 328 set_number_at, 329 330 wordchar,/* Matches any word-constituent character. */ 331 notwordchar,/* Matches any char that is not a word-constituent. */ 332 333 wordbeg,/* Succeeds if at word beginning. */ 334 wordend,/* Succeeds if at word end. */ 335 336 wordbound,/* Succeeds if at a word boundary. */ 337 notwordbound /* Succeeds if not at a word boundary. */ 338 339#ifdef emacs 340,before_dot,/* Succeeds if before point. */ 341 at_dot,/* Succeeds if at point. */ 342 after_dot,/* Succeeds if after point. */ 343 344/* Matches any character whose syntax is specified. Followed by 345 a byte which contains a syntax code, e.g., Sword. */ 346 syntaxspec, 347 348/* Matches any character whose syntax is not that specified. */ 349 notsyntaxspec 350#endif/* emacs */ 351} re_opcode_t; 352\f 353/* Common operations on the compiled pattern. */ 354 355/* Store NUMBER in two contiguous bytes starting at DESTINATION. */ 356 357#define STORE_NUMBER(destination, number) \ 358 do { \ 359 (destination)[0] = (number) & 0377; \ 360 (destination)[1] = (number) >> 8; \ 361 } while (0) 362 363/* Same as STORE_NUMBER, except increment DESTINATION to 364 the byte after where the number is stored. Therefore, DESTINATION 365 must be an lvalue. */ 366 367#define STORE_NUMBER_AND_INCR(destination, number) \ 368 do { \ 369 STORE_NUMBER (destination, number); \ 370 (destination) += 2; \ 371 } while (0) 372 373/* Put into DESTINATION a number stored in two contiguous bytes starting 374 at SOURCE. */ 375 376#define EXTRACT_NUMBER(destination, source) \ 377 do { \ 378 (destination) = *(source) & 0377; \ 379 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \ 380 } while (0) 381 382#ifdef DEBUG 383static void 384extract_number(dest, source) 385int*dest; 386unsigned char*source; 387{ 388int temp =SIGN_EXTEND_CHAR(*(source +1)); 389*dest = *source &0377; 390*dest += temp <<8; 391} 392 393#ifndef EXTRACT_MACROS/* To debug the macros. */ 394#undef EXTRACT_NUMBER 395#define EXTRACT_NUMBER(dest, src) extract_number (&dest, src) 396#endif/* not EXTRACT_MACROS */ 397 398#endif/* DEBUG */ 399 400/* Same as EXTRACT_NUMBER, except increment SOURCE to after the number. 401 SOURCE must be an lvalue. */ 402 403#define EXTRACT_NUMBER_AND_INCR(destination, source) \ 404 do { \ 405 EXTRACT_NUMBER (destination, source); \ 406 (source) += 2; \ 407 } while (0) 408 409#ifdef DEBUG 410static void 411extract_number_and_incr(destination, source) 412int*destination; 413unsigned char**source; 414{ 415extract_number(destination, *source); 416*source +=2; 417} 418 419#ifndef EXTRACT_MACROS 420#undef EXTRACT_NUMBER_AND_INCR 421#define EXTRACT_NUMBER_AND_INCR(dest, src) \ 422 extract_number_and_incr (&dest, &src) 423#endif/* not EXTRACT_MACROS */ 424 425#endif/* DEBUG */ 426\f 427/* If DEBUG is defined, Regex prints many voluminous messages about what 428 it is doing (if the variable `debug' is nonzero). If linked with the 429 main program in `iregex.c', you can enter patterns and strings 430 interactively. And if linked with the main program in `main.c' and 431 the other test files, you can run the already-written tests. */ 432 433#ifdef DEBUG 434 435/* We use standard I/O for debugging. */ 436#include <stdio.h> 437 438/* It is useful to test things that ``must'' be true when debugging. */ 439#include <assert.h> 440 441static int debug =0; 442 443#define DEBUG_STATEMENT(e) e 444#define DEBUG_PRINT1(x) if (debug) printf (x) 445#define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2) 446#define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3) 447#define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4) 448#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \ 449 if (debug) print_partial_compiled_pattern (s, e) 450#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \ 451 if (debug) print_double_string (w, s1, sz1, s2, sz2) 452 453 454externvoidprintchar(); 455 456/* Print the fastmap in human-readable form. */ 457 458void 459print_fastmap(fastmap) 460char*fastmap; 461{ 462unsigned was_a_range =0; 463unsigned i =0; 464 465while(i < (1<< BYTEWIDTH)) 466{ 467if(fastmap[i++]) 468{ 469 was_a_range =0; 470printchar(i -1); 471while(i < (1<< BYTEWIDTH) && fastmap[i]) 472{ 473 was_a_range =1; 474 i++; 475} 476if(was_a_range) 477{ 478printf("-"); 479printchar(i -1); 480} 481} 482} 483putchar('\n'); 484} 485 486 487/* Print a compiled pattern string in human-readable form, starting at 488 the START pointer into it and ending just before the pointer END. */ 489 490void 491print_partial_compiled_pattern(start, end) 492unsigned char*start; 493unsigned char*end; 494{ 495int mcnt, mcnt2; 496unsigned char*p = start; 497unsigned char*pend = end; 498 499if(start == NULL) 500{ 501printf("(null)\n"); 502return; 503} 504 505/* Loop over pattern commands. */ 506while(p < pend) 507{ 508switch((re_opcode_t) *p++) 509{ 510case no_op: 511printf("/no_op"); 512break; 513 514case exactn: 515 mcnt = *p++; 516printf("/exactn/%d", mcnt); 517do 518{ 519putchar('/'); 520printchar(*p++); 521} 522while(--mcnt); 523break; 524 525case start_memory: 526 mcnt = *p++; 527printf("/start_memory/%d/%d", mcnt, *p++); 528break; 529 530case stop_memory: 531 mcnt = *p++; 532printf("/stop_memory/%d/%d", mcnt, *p++); 533break; 534 535case duplicate: 536printf("/duplicate/%d", *p++); 537break; 538 539case anychar: 540printf("/anychar"); 541break; 542 543case charset: 544case charset_not: 545{ 546registerint c; 547 548printf("/charset%s", 549(re_opcode_t) *(p -1) == charset_not ?"_not":""); 550 551assert(p + *p < pend); 552 553for(c =0; c < *p; c++) 554{ 555unsigned bit; 556unsigned char map_byte = p[1+ c]; 557 558putchar('/'); 559 560for(bit =0; bit < BYTEWIDTH; bit++) 561if(map_byte & (1<< bit)) 562printchar(c * BYTEWIDTH + bit); 563} 564 p +=1+ *p; 565break; 566} 567 568case begline: 569printf("/begline"); 570break; 571 572case endline: 573printf("/endline"); 574break; 575 576case on_failure_jump: 577extract_number_and_incr(&mcnt, &p); 578printf("/on_failure_jump/0/%d", mcnt); 579break; 580 581case on_failure_keep_string_jump: 582extract_number_and_incr(&mcnt, &p); 583printf("/on_failure_keep_string_jump/0/%d", mcnt); 584break; 585 586case dummy_failure_jump: 587extract_number_and_incr(&mcnt, &p); 588printf("/dummy_failure_jump/0/%d", mcnt); 589break; 590 591case push_dummy_failure: 592printf("/push_dummy_failure"); 593break; 594 595case maybe_pop_jump: 596extract_number_and_incr(&mcnt, &p); 597printf("/maybe_pop_jump/0/%d", mcnt); 598break; 599 600case pop_failure_jump: 601extract_number_and_incr(&mcnt, &p); 602printf("/pop_failure_jump/0/%d", mcnt); 603break; 604 605case jump_past_alt: 606extract_number_and_incr(&mcnt, &p); 607printf("/jump_past_alt/0/%d", mcnt); 608break; 609 610case jump: 611extract_number_and_incr(&mcnt, &p); 612printf("/jump/0/%d", mcnt); 613break; 614 615case succeed_n: 616extract_number_and_incr(&mcnt, &p); 617extract_number_and_incr(&mcnt2, &p); 618printf("/succeed_n/0/%d/0/%d", mcnt, mcnt2); 619break; 620 621case jump_n: 622extract_number_and_incr(&mcnt, &p); 623extract_number_and_incr(&mcnt2, &p); 624printf("/jump_n/0/%d/0/%d", mcnt, mcnt2); 625break; 626 627case set_number_at: 628extract_number_and_incr(&mcnt, &p); 629extract_number_and_incr(&mcnt2, &p); 630printf("/set_number_at/0/%d/0/%d", mcnt, mcnt2); 631break; 632 633case wordbound: 634printf("/wordbound"); 635break; 636 637case notwordbound: 638printf("/notwordbound"); 639break; 640 641case wordbeg: 642printf("/wordbeg"); 643break; 644 645case wordend: 646printf("/wordend"); 647 648#ifdef emacs 649case before_dot: 650printf("/before_dot"); 651break; 652 653case at_dot: 654printf("/at_dot"); 655break; 656 657case after_dot: 658printf("/after_dot"); 659break; 660 661case syntaxspec: 662printf("/syntaxspec"); 663 mcnt = *p++; 664printf("/%d", mcnt); 665break; 666 667case notsyntaxspec: 668printf("/notsyntaxspec"); 669 mcnt = *p++; 670printf("/%d", mcnt); 671break; 672#endif/* emacs */ 673 674case wordchar: 675printf("/wordchar"); 676break; 677 678case notwordchar: 679printf("/notwordchar"); 680break; 681 682case begbuf: 683printf("/begbuf"); 684break; 685 686case endbuf: 687printf("/endbuf"); 688break; 689 690default: 691printf("?%d", *(p-1)); 692} 693} 694printf("/\n"); 695} 696 697 698void 699print_compiled_pattern(bufp) 700struct re_pattern_buffer *bufp; 701{ 702unsigned char*buffer = bufp->buffer; 703 704print_partial_compiled_pattern(buffer, buffer + bufp->used); 705printf("%dbytes used/%dbytes allocated.\n", bufp->used, bufp->allocated); 706 707if(bufp->fastmap_accurate && bufp->fastmap) 708{ 709printf("fastmap: "); 710print_fastmap(bufp->fastmap); 711} 712 713printf("re_nsub:%d\t", bufp->re_nsub); 714printf("regs_alloc:%d\t", bufp->regs_allocated); 715printf("can_be_null:%d\t", bufp->can_be_null); 716printf("newline_anchor:%d\n", bufp->newline_anchor); 717printf("no_sub:%d\t", bufp->no_sub); 718printf("not_bol:%d\t", bufp->not_bol); 719printf("not_eol:%d\t", bufp->not_eol); 720printf("syntax:%d\n", bufp->syntax); 721/* Perhaps we should print the translate table? */ 722} 723 724 725void 726print_double_string(where, string1, size1, string2, size2) 727const char*where; 728const char*string1; 729const char*string2; 730int size1; 731int size2; 732{ 733unsigned this_char; 734 735if(where == NULL) 736printf("(null)"); 737else 738{ 739if(FIRST_STRING_P(where)) 740{ 741for(this_char = where - string1; this_char < size1; this_char++) 742printchar(string1[this_char]); 743 744 where = string2; 745} 746 747for(this_char = where - string2; this_char < size2; this_char++) 748printchar(string2[this_char]); 749} 750} 751 752#else/* not DEBUG */ 753 754#undef assert 755#define assert(e) 756 757#define DEBUG_STATEMENT(e) 758#define DEBUG_PRINT1(x) 759#define DEBUG_PRINT2(x1, x2) 760#define DEBUG_PRINT3(x1, x2, x3) 761#define DEBUG_PRINT4(x1, x2, x3, x4) 762#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) 763#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) 764 765#endif/* not DEBUG */ 766\f 767/* Set by `re_set_syntax' to the current regexp syntax to recognize. Can 768 also be assigned to arbitrarily: each pattern buffer stores its own 769 syntax, so it can be changed between regex compilations. */ 770reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS; 771 772 773/* Specify the precise syntax of regexps for compilation. This provides 774 for compatibility for various utilities which historically have 775 different, incompatible syntaxes. 776 777 The argument SYNTAX is a bit mask comprised of the various bits 778 defined in regex.h. We return the old syntax. */ 779 780reg_syntax_t 781re_set_syntax(syntax) 782 reg_syntax_t syntax; 783{ 784 reg_syntax_t ret = re_syntax_options; 785 786 re_syntax_options = syntax; 787return ret; 788} 789\f 790/* This table gives an error message for each of the error codes listed 791 in regex.h. Obviously the order here has to be same as there. */ 792 793static const char*re_error_msg[] = 794{ NULL,/* REG_NOERROR */ 795"No match",/* REG_NOMATCH */ 796"Invalid regular expression",/* REG_BADPAT */ 797"Invalid collation character",/* REG_ECOLLATE */ 798"Invalid character class name",/* REG_ECTYPE */ 799"Trailing backslash",/* REG_EESCAPE */ 800"Invalid back reference",/* REG_ESUBREG */ 801"Unmatched [ or [^",/* REG_EBRACK */ 802"Unmatched ( or\\(",/* REG_EPAREN */ 803"Unmatched\\{",/* REG_EBRACE */ 804"Invalid content of\\{\\}",/* REG_BADBR */ 805"Invalid range end",/* REG_ERANGE */ 806"Memory exhausted",/* REG_ESPACE */ 807"Invalid preceding regular expression",/* REG_BADRPT */ 808"Premature end of regular expression",/* REG_EEND */ 809"Regular expression too big",/* REG_ESIZE */ 810"Unmatched ) or\\)",/* REG_ERPAREN */ 811}; 812\f 813/* Subroutine declarations and macros for regex_compile. */ 814 815static voidstore_op1(),store_op2(); 816static voidinsert_op1(),insert_op2(); 817static boolean at_begline_loc_p(),at_endline_loc_p(); 818static boolean group_in_compile_stack(); 819static reg_errcode_t compile_range(); 820 821/* Fetch the next character in the uncompiled pattern---translating it 822 if necessary. Also cast from a signed character in the constant 823 string passed to us by the user to an unsigned char that we can use 824 as an array index (in, e.g., `translate'). */ 825#define PATFETCH(c) \ 826 do {if (p == pend) return REG_EEND; \ 827 c = (unsigned char) *p++; \ 828 if (translate) c = translate[c]; \ 829 } while (0) 830 831/* Fetch the next character in the uncompiled pattern, with no 832 translation. */ 833#define PATFETCH_RAW(c) \ 834 do {if (p == pend) return REG_EEND; \ 835 c = (unsigned char) *p++; \ 836 } while (0) 837 838/* Go backwards one character in the pattern. */ 839#define PATUNFETCH p-- 840 841 842/* If `translate' is non-null, return translate[D], else just D. We 843 cast the subscript to translate because some data is declared as 844 `char *', to avoid warnings when a string constant is passed. But 845 when we use a character as a subscript we must make it unsigned. */ 846#define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d)) 847 848 849/* Macros for outputting the compiled pattern into `buffer'. */ 850 851/* If the buffer isn't allocated when it comes in, use this. */ 852#define INIT_BUF_SIZE 32 853 854/* Make sure we have at least N more bytes of space in buffer. */ 855#define GET_BUFFER_SPACE(n) \ 856 while (b - bufp->buffer + (n) > bufp->allocated) \ 857 EXTEND_BUFFER () 858 859/* Make sure we have one more byte of buffer space and then add C to it. */ 860#define BUF_PUSH(c) \ 861 do { \ 862 GET_BUFFER_SPACE (1); \ 863 *b++ = (unsigned char) (c); \ 864 } while (0) 865 866 867/* Ensure we have two more bytes of buffer space and then append C1 and C2. */ 868#define BUF_PUSH_2(c1, c2) \ 869 do { \ 870 GET_BUFFER_SPACE (2); \ 871 *b++ = (unsigned char) (c1); \ 872 *b++ = (unsigned char) (c2); \ 873 } while (0) 874 875 876/* As with BUF_PUSH_2, except for three bytes. */ 877#define BUF_PUSH_3(c1, c2, c3) \ 878 do { \ 879 GET_BUFFER_SPACE (3); \ 880 *b++ = (unsigned char) (c1); \ 881 *b++ = (unsigned char) (c2); \ 882 *b++ = (unsigned char) (c3); \ 883 } while (0) 884 885 886/* Store a jump with opcode OP at LOC to location TO. We store a 887 relative address offset by the three bytes the jump itself occupies. */ 888#define STORE_JUMP(op, loc, to) \ 889 store_op1 (op, loc, (to) - (loc) - 3) 890 891/* Likewise, for a two-argument jump. */ 892#define STORE_JUMP2(op, loc, to, arg) \ 893 store_op2 (op, loc, (to) - (loc) - 3, arg) 894 895/* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */ 896#define INSERT_JUMP(op, loc, to) \ 897 insert_op1 (op, loc, (to) - (loc) - 3, b) 898 899/* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */ 900#define INSERT_JUMP2(op, loc, to, arg) \ 901 insert_op2 (op, loc, (to) - (loc) - 3, arg, b) 902 903 904/* This is not an arbitrary limit: the arguments which represent offsets 905 into the pattern are two bytes long. So if 2^16 bytes turns out to 906 be too small, many things would have to change. */ 907#define MAX_BUF_SIZE (1L << 16) 908 909 910/* Extend the buffer by twice its current size via realloc and 911 reset the pointers that pointed into the old block to point to the 912 correct places in the new one. If extending the buffer results in it 913 being larger than MAX_BUF_SIZE, then flag memory exhausted. */ 914#define EXTEND_BUFFER() \ 915 do { \ 916 unsigned char *old_buffer = bufp->buffer; \ 917 if (bufp->allocated == MAX_BUF_SIZE) \ 918 return REG_ESIZE; \ 919 bufp->allocated <<= 1; \ 920 if (bufp->allocated > MAX_BUF_SIZE) \ 921 bufp->allocated = MAX_BUF_SIZE; \ 922 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\ 923 if (bufp->buffer == NULL) \ 924 return REG_ESPACE; \ 925/* If the buffer moved, move all the pointers into it. */ \ 926 if (old_buffer != bufp->buffer) \ 927 { \ 928 b = (b - old_buffer) + bufp->buffer; \ 929 begalt = (begalt - old_buffer) + bufp->buffer; \ 930 if (fixup_alt_jump) \ 931 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\ 932 if (laststart) \ 933 laststart = (laststart - old_buffer) + bufp->buffer; \ 934 if (pending_exact) \ 935 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \ 936 } \ 937 } while (0) 938 939 940/* Since we have one byte reserved for the register number argument to 941 {start,stop}_memory, the maximum number of groups we can report 942 things about is what fits in that byte. */ 943#define MAX_REGNUM 255 944 945/* But patterns can have more than `MAX_REGNUM' registers. We just 946 ignore the excess. */ 947typedefunsigned regnum_t; 948 949 950/* Macros for the compile stack. */ 951 952/* Since offsets can go either forwards or backwards, this type needs to 953 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */ 954typedefint pattern_offset_t; 955 956typedefstruct 957{ 958 pattern_offset_t begalt_offset; 959 pattern_offset_t fixup_alt_jump; 960 pattern_offset_t inner_group_offset; 961 pattern_offset_t laststart_offset; 962 regnum_t regnum; 963} compile_stack_elt_t; 964 965 966typedefstruct 967{ 968 compile_stack_elt_t *stack; 969unsigned size; 970unsigned avail;/* Offset of next open position. */ 971} compile_stack_type; 972 973 974#define INIT_COMPILE_STACK_SIZE 32 975 976#define COMPILE_STACK_EMPTY (compile_stack.avail == 0) 977#define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size) 978 979/* The next available element. */ 980#define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail]) 981 982 983/* Set the bit for character C in a list. */ 984#define SET_LIST_BIT(c) \ 985 (b[((unsigned char) (c)) / BYTEWIDTH] \ 986 |= 1 << (((unsigned char) c) % BYTEWIDTH)) 987 988 989/* Get the next unsigned number in the uncompiled pattern. */ 990#define GET_UNSIGNED_NUMBER(num) \ 991 { if (p != pend) \ 992 { \ 993 PATFETCH (c); \ 994 while (ISDIGIT (c)) \ 995 { \ 996 if (num < 0) \ 997 num = 0; \ 998 num = num * 10 + c -'0'; \ 999 if (p == pend) \1000 break; \1001 PATFETCH (c); \1002 } \1003 } \1004 }10051006#define CHAR_CLASS_MAX_LENGTH 6/* Namely, `xdigit'. */10071008#define IS_CHAR_CLASS(string) \1009 (STREQ (string,"alpha") || STREQ (string,"upper") \1010 || STREQ (string,"lower") || STREQ (string,"digit") \1011 || STREQ (string,"alnum") || STREQ (string,"xdigit") \1012 || STREQ (string,"space") || STREQ (string,"print") \1013 || STREQ (string,"punct") || STREQ (string,"graph") \1014 || STREQ (string,"cntrl") || STREQ (string,"blank"))1015\f1016/* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.1017 Returns one of error codes defined in `regex.h', or zero for success.10181019 Assumes the `allocated' (and perhaps `buffer') and `translate'1020 fields are set in BUFP on entry.10211022 If it succeeds, results are put in BUFP (if it returns an error, the1023 contents of BUFP are undefined):1024 `buffer' is the compiled pattern;1025 `syntax' is set to SYNTAX;1026 `used' is set to the length of the compiled pattern;1027 `fastmap_accurate' is zero;1028 `re_nsub' is the number of subexpressions in PATTERN;1029 `not_bol' and `not_eol' are zero;10301031 The `fastmap' and `newline_anchor' fields are neither1032 examined nor set. */10331034static reg_errcode_t1035regex_compile(pattern, size, syntax, bufp)1036const char*pattern;1037int size;1038 reg_syntax_t syntax;1039struct re_pattern_buffer *bufp;1040{1041/* We fetch characters from PATTERN here. Even though PATTERN is1042 `char *' (i.e., signed), we declare these variables as unsigned, so1043 they can be reliably used as array indices. */1044registerunsigned char c, c1;10451046/* A random temporary spot in PATTERN. */1047const char*p1;10481049/* Points to the end of the buffer, where we should append. */1050registerunsigned char*b;10511052/* Keeps track of unclosed groups. */1053 compile_stack_type compile_stack;10541055/* Points to the current (ending) position in the pattern. */1056const char*p = pattern;1057const char*pend = pattern + size;10581059/* How to translate the characters in the pattern. */1060char*translate = bufp->translate;10611062/* Address of the count-byte of the most recently inserted `exactn'1063 command. This makes it possible to tell if a new exact-match1064 character can be added to that command or if the character requires1065 a new `exactn' command. */1066unsigned char*pending_exact =0;10671068/* Address of start of the most recently finished expression.1069 This tells, e.g., postfix * where to find the start of its1070 operand. Reset at the beginning of groups and alternatives. */1071unsigned char*laststart =0;10721073/* Address of beginning of regexp, or inside of last group. */1074unsigned char*begalt;10751076/* Place in the uncompiled pattern (i.e., the {) to1077 which to go back if the interval is invalid. */1078const char*beg_interval;10791080/* Address of the place where a forward jump should go to the end of1081 the containing expression. Each alternative of an `or' -- except the1082 last -- ends with a forward jump of this sort. */1083unsigned char*fixup_alt_jump =0;10841085/* Counts open-groups as they are encountered. Remembered for the1086 matching close-group on the compile stack, so the same register1087 number is put in the stop_memory as the start_memory. */1088 regnum_t regnum =0;10891090#ifdef DEBUG1091DEBUG_PRINT1("\nCompiling pattern: ");1092if(debug)1093{1094unsigned debug_count;10951096for(debug_count =0; debug_count < size; debug_count++)1097printchar(pattern[debug_count]);1098putchar('\n');1099}1100#endif/* DEBUG */11011102/* Initialize the compile stack. */1103 compile_stack.stack =TALLOC(INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);1104if(compile_stack.stack == NULL)1105return REG_ESPACE;11061107 compile_stack.size = INIT_COMPILE_STACK_SIZE;1108 compile_stack.avail =0;11091110/* Initialize the pattern buffer. */1111 bufp->syntax = syntax;1112 bufp->fastmap_accurate =0;1113 bufp->not_bol = bufp->not_eol =0;11141115/* Set `used' to zero, so that if we return an error, the pattern1116 printer (for debugging) will think there's no pattern. We reset it1117 at the end. */1118 bufp->used =0;11191120/* Always count groups, whether or not bufp->no_sub is set. */1121 bufp->re_nsub =0;11221123#if !defined (emacs) && !defined (SYNTAX_TABLE)1124/* Initialize the syntax table. */1125init_syntax_once();1126#endif11271128if(bufp->allocated ==0)1129{1130if(bufp->buffer)1131{/* If zero allocated, but buffer is non-null, try to realloc1132 enough space. This loses if buffer's address is bogus, but1133 that is the user's responsibility. */1134RETALLOC(bufp->buffer, INIT_BUF_SIZE,unsigned char);1135}1136else1137{/* Caller did not allocate a buffer. Do it for them. */1138 bufp->buffer =TALLOC(INIT_BUF_SIZE,unsigned char);1139}1140if(!bufp->buffer)return REG_ESPACE;11411142 bufp->allocated = INIT_BUF_SIZE;1143}11441145 begalt = b = bufp->buffer;11461147/* Loop through the uncompiled pattern until we're at the end. */1148while(p != pend)1149{1150PATFETCH(c);11511152switch(c)1153{1154case'^':1155{1156if(/* If at start of pattern, it's an operator. */1157 p == pattern +11158/* If context independent, it's an operator. */1159|| syntax & RE_CONTEXT_INDEP_ANCHORS1160/* Otherwise, depends on what's come before. */1161||at_begline_loc_p(pattern, p, syntax))1162BUF_PUSH(begline);1163else1164goto normal_char;1165}1166break;116711681169case'$':1170{1171if(/* If at end of pattern, it's an operator. */1172 p == pend1173/* If context independent, it's an operator. */1174|| syntax & RE_CONTEXT_INDEP_ANCHORS1175/* Otherwise, depends on what's next. */1176||at_endline_loc_p(p, pend, syntax))1177BUF_PUSH(endline);1178else1179goto normal_char;1180}1181break;118211831184case'+':1185case'?':1186if((syntax & RE_BK_PLUS_QM)1187|| (syntax & RE_LIMITED_OPS))1188goto normal_char;1189 handle_plus:1190case'*':1191/* If there is no previous pattern... */1192if(!laststart)1193{1194if(syntax & RE_CONTEXT_INVALID_OPS)1195return REG_BADRPT;1196else if(!(syntax & RE_CONTEXT_INDEP_OPS))1197goto normal_char;1198}11991200{1201/* Are we optimizing this jump? */1202 boolean keep_string_p =false;12031204/* 1 means zero (many) matches is allowed. */1205char zero_times_ok =0, many_times_ok =0;12061207/* If there is a sequence of repetition chars, collapse it1208 down to just one (the right one). We can't combine1209 interval operators with these because of, e.g., `a{2}*',1210 which should only match an even number of `a's. */12111212for(;;)1213{1214 zero_times_ok |= c !='+';1215 many_times_ok |= c !='?';12161217if(p == pend)1218break;12191220PATFETCH(c);12211222if(c =='*'1223|| (!(syntax & RE_BK_PLUS_QM) && (c =='+'|| c =='?')))1224;12251226else if(syntax & RE_BK_PLUS_QM && c =='\\')1227{1228if(p == pend)return REG_EESCAPE;12291230PATFETCH(c1);1231if(!(c1 =='+'|| c1 =='?'))1232{1233 PATUNFETCH;1234 PATUNFETCH;1235break;1236}12371238 c = c1;1239}1240else1241{1242 PATUNFETCH;1243break;1244}12451246/* If we get here, we found another repeat character. */1247}12481249/* Star, etc. applied to an empty pattern is equivalent1250 to an empty pattern. */1251if(!laststart)1252break;12531254/* Now we know whether or not zero matches is allowed1255 and also whether or not two or more matches is allowed. */1256if(many_times_ok)1257{/* More than one repetition is allowed, so put in at the1258 end a backward relative jump from `b' to before the next1259 jump we're going to put in below (which jumps from1260 laststart to after this jump).12611262 But if we are at the `*' in the exact sequence `.*\n',1263 insert an unconditional jump backwards to the .,1264 instead of the beginning of the loop. This way we only1265 push a failure point once, instead of every time1266 through the loop. */1267assert(p -1> pattern);12681269/* Allocate the space for the jump. */1270GET_BUFFER_SPACE(3);12711272/* We know we are not at the first character of the pattern,1273 because laststart was nonzero. And we've already1274 incremented `p', by the way, to be the character after1275 the `*'. Do we have to do something analogous here1276 for null bytes, because of RE_DOT_NOT_NULL? */1277if(TRANSLATE(*(p -2)) ==TRANSLATE('.')1278&& zero_times_ok1279&& p < pend &&TRANSLATE(*p) ==TRANSLATE('\n')1280&& !(syntax & RE_DOT_NEWLINE))1281{/* We have .*\n. */1282STORE_JUMP(jump, b, laststart);1283 keep_string_p =true;1284}1285else1286/* Anything else. */1287STORE_JUMP(maybe_pop_jump, b, laststart -3);12881289/* We've added more stuff to the buffer. */1290 b +=3;1291}12921293/* On failure, jump from laststart to b + 3, which will be the1294 end of the buffer after this jump is inserted. */1295GET_BUFFER_SPACE(3);1296INSERT_JUMP(keep_string_p ? on_failure_keep_string_jump1297: on_failure_jump,1298 laststart, b +3);1299 pending_exact =0;1300 b +=3;13011302if(!zero_times_ok)1303{1304/* At least one repetition is required, so insert a1305 `dummy_failure_jump' before the initial1306 `on_failure_jump' instruction of the loop. This1307 effects a skip over that instruction the first time1308 we hit that loop. */1309GET_BUFFER_SPACE(3);1310INSERT_JUMP(dummy_failure_jump, laststart, laststart +6);1311 b +=3;1312}1313}1314break;131513161317case'.':1318 laststart = b;1319BUF_PUSH(anychar);1320break;132113221323case'[':1324{1325 boolean had_char_class =false;13261327if(p == pend)return REG_EBRACK;13281329/* Ensure that we have enough space to push a charset: the1330 opcode, the length count, and the bitset; 34 bytes in all. */1331GET_BUFFER_SPACE(34);13321333 laststart = b;13341335/* We test `*p == '^' twice, instead of using an if1336 statement, so we only need one BUF_PUSH. */1337BUF_PUSH(*p =='^'? charset_not : charset);1338if(*p =='^')1339 p++;13401341/* Remember the first position in the bracket expression. */1342 p1 = p;13431344/* Push the number of bytes in the bitmap. */1345BUF_PUSH((1<< BYTEWIDTH) / BYTEWIDTH);13461347/* Clear the whole map. */1348bzero(b, (1<< BYTEWIDTH) / BYTEWIDTH);13491350/* charset_not matches newline according to a syntax bit. */1351if((re_opcode_t) b[-2] == charset_not1352&& (syntax & RE_HAT_LISTS_NOT_NEWLINE))1353SET_LIST_BIT('\n');13541355/* Read in characters and ranges, setting map bits. */1356for(;;)1357{1358if(p == pend)return REG_EBRACK;13591360PATFETCH(c);13611362/* \ might escape characters inside [...] and [^...]. */1363if((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c =='\\')1364{1365if(p == pend)return REG_EESCAPE;13661367PATFETCH(c1);1368SET_LIST_BIT(c1);1369continue;1370}13711372/* Could be the end of the bracket expression. If it's1373 not (i.e., when the bracket expression is `[]' so1374 far), the ']' character bit gets set way below. */1375if(c ==']'&& p != p1 +1)1376break;13771378/* Look ahead to see if it's a range when the last thing1379 was a character class. */1380if(had_char_class && c =='-'&& *p !=']')1381return REG_ERANGE;13821383/* Look ahead to see if it's a range when the last thing1384 was a character: if this is a hyphen not at the1385 beginning or the end of a list, then it's the range1386 operator. */1387if(c =='-'1388&& !(p -2>= pattern && p[-2] =='[')1389&& !(p -3>= pattern && p[-3] =='['&& p[-2] =='^')1390&& *p !=']')1391{1392 reg_errcode_t ret1393=compile_range(&p, pend, translate, syntax, b);1394if(ret != REG_NOERROR)return ret;1395}13961397else if(p[0] =='-'&& p[1] !=']')1398{/* This handles ranges made up of characters only. */1399 reg_errcode_t ret;14001401/* Move past the `-'. */1402PATFETCH(c1);14031404 ret =compile_range(&p, pend, translate, syntax, b);1405if(ret != REG_NOERROR)return ret;1406}14071408/* See if we're at the beginning of a possible character1409 class. */14101411else if(syntax & RE_CHAR_CLASSES && c =='['&& *p ==':')1412{/* Leave room for the null. */1413char str[CHAR_CLASS_MAX_LENGTH +1];14141415PATFETCH(c);1416 c1 =0;14171418/* If pattern is `[[:'. */1419if(p == pend)return REG_EBRACK;14201421for(;;)1422{1423PATFETCH(c);1424if(c ==':'|| c ==']'|| p == pend1425|| c1 == CHAR_CLASS_MAX_LENGTH)1426break;1427 str[c1++] = c;1428}1429 str[c1] ='\0';14301431/* If isn't a word bracketed by `[:' and:`]':1432 undo the ending character, the letters, and leave1433 the leading `:' and `[' (but set bits for them). */1434if(c ==':'&& *p ==']')1435{1436int ch;1437 boolean is_alnum =STREQ(str,"alnum");1438 boolean is_alpha =STREQ(str,"alpha");1439 boolean is_blank =STREQ(str,"blank");1440 boolean is_cntrl =STREQ(str,"cntrl");1441 boolean is_digit =STREQ(str,"digit");1442 boolean is_graph =STREQ(str,"graph");1443 boolean is_lower =STREQ(str,"lower");1444 boolean is_print =STREQ(str,"print");1445 boolean is_punct =STREQ(str,"punct");1446 boolean is_space =STREQ(str,"space");1447 boolean is_upper =STREQ(str,"upper");1448 boolean is_xdigit =STREQ(str,"xdigit");14491450if(!IS_CHAR_CLASS(str))return REG_ECTYPE;14511452/* Throw away the ] at the end of the character1453 class. */1454PATFETCH(c);14551456if(p == pend)return REG_EBRACK;14571458for(ch =0; ch <1<< BYTEWIDTH; ch++)1459{1460if( (is_alnum &&ISALNUM(ch))1461|| (is_alpha &&ISALPHA(ch))1462|| (is_blank &&ISBLANK(ch))1463|| (is_cntrl &&ISCNTRL(ch))1464|| (is_digit &&ISDIGIT(ch))1465|| (is_graph &&ISGRAPH(ch))1466|| (is_lower &&ISLOWER(ch))1467|| (is_print &&ISPRINT(ch))1468|| (is_punct &&ISPUNCT(ch))1469|| (is_space &&ISSPACE(ch))1470|| (is_upper &&ISUPPER(ch))1471|| (is_xdigit &&ISXDIGIT(ch)))1472SET_LIST_BIT(ch);1473}1474 had_char_class =true;1475}1476else1477{1478 c1++;1479while(c1--)1480 PATUNFETCH;1481SET_LIST_BIT('[');1482SET_LIST_BIT(':');1483 had_char_class =false;1484}1485}1486else1487{1488 had_char_class =false;1489SET_LIST_BIT(c);1490}1491}14921493/* Discard any (non)matching list bytes that are all 0 at the1494 end of the map. Decrease the map-length byte too. */1495while((int) b[-1] >0&& b[b[-1] -1] ==0)1496 b[-1]--;1497 b += b[-1];1498}1499break;150015011502case'(':1503if(syntax & RE_NO_BK_PARENS)1504goto handle_open;1505else1506goto normal_char;150715081509case')':1510if(syntax & RE_NO_BK_PARENS)1511goto handle_close;1512else1513goto normal_char;151415151516case'\n':1517if(syntax & RE_NEWLINE_ALT)1518goto handle_alt;1519else1520goto normal_char;152115221523case'|':1524if(syntax & RE_NO_BK_VBAR)1525goto handle_alt;1526else1527goto normal_char;152815291530case'{':1531if(syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)1532goto handle_interval;1533else1534goto normal_char;153515361537case'\\':1538if(p == pend)return REG_EESCAPE;15391540/* Do not translate the character after the \, so that we can1541 distinguish, e.g., \B from \b, even if we normally would1542 translate, e.g., B to b. */1543PATFETCH_RAW(c);15441545switch(c)1546{1547case'(':1548if(syntax & RE_NO_BK_PARENS)1549goto normal_backslash;15501551 handle_open:1552 bufp->re_nsub++;1553 regnum++;15541555if(COMPILE_STACK_FULL)1556{1557RETALLOC(compile_stack.stack, compile_stack.size <<1,1558 compile_stack_elt_t);1559if(compile_stack.stack == NULL)return REG_ESPACE;15601561 compile_stack.size <<=1;1562}15631564/* These are the values to restore when we hit end of this1565 group. They are all relative offsets, so that if the1566 whole pattern moves because of realloc, they will still1567 be valid. */1568 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;1569 COMPILE_STACK_TOP.fixup_alt_jump1570= fixup_alt_jump ? fixup_alt_jump - bufp->buffer +1:0;1571 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;1572 COMPILE_STACK_TOP.regnum = regnum;15731574/* We will eventually replace the 0 with the number of1575 groups inner to this one. But do not push a1576 start_memory for groups beyond the last one we can1577 represent in the compiled pattern. */1578if(regnum <= MAX_REGNUM)1579{1580 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer +2;1581BUF_PUSH_3(start_memory, regnum,0);1582}15831584 compile_stack.avail++;15851586 fixup_alt_jump =0;1587 laststart =0;1588 begalt = b;1589/* If we've reached MAX_REGNUM groups, then this open1590 won't actually generate any code, so we'll have to1591 clear pending_exact explicitly. */1592 pending_exact =0;1593break;159415951596case')':1597if(syntax & RE_NO_BK_PARENS)goto normal_backslash;15981599if(COMPILE_STACK_EMPTY)1600{1601if(syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)1602goto normal_backslash;1603else1604return REG_ERPAREN;1605}16061607 handle_close:1608if(fixup_alt_jump)1609{/* Push a dummy failure point at the end of the1610 alternative for a possible future1611 `pop_failure_jump' to pop. See comments at1612 `push_dummy_failure' in `re_match_2'. */1613BUF_PUSH(push_dummy_failure);16141615/* We allocated space for this jump when we assigned1616 to `fixup_alt_jump', in the `handle_alt' case below. */1617STORE_JUMP(jump_past_alt, fixup_alt_jump, b -1);1618}16191620/* See similar code for backslashed left paren above. */1621if(COMPILE_STACK_EMPTY)1622{1623if(syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)1624goto normal_char;1625else1626return REG_ERPAREN;1627}16281629/* Since we just checked for an empty stack above, this1630 ``can't happen''. */1631assert(compile_stack.avail !=0);1632{1633/* We don't just want to restore into `regnum', because1634 later groups should continue to be numbered higher,1635 as in `(ab)c(de)' -- the second group is #2. */1636 regnum_t this_group_regnum;16371638 compile_stack.avail--;1639 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;1640 fixup_alt_jump1641= COMPILE_STACK_TOP.fixup_alt_jump1642? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump -11643:0;1644 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;1645 this_group_regnum = COMPILE_STACK_TOP.regnum;1646/* If we've reached MAX_REGNUM groups, then this open1647 won't actually generate any code, so we'll have to1648 clear pending_exact explicitly. */1649 pending_exact =0;16501651/* We're at the end of the group, so now we know how many1652 groups were inside this one. */1653if(this_group_regnum <= MAX_REGNUM)1654{1655unsigned char*inner_group_loc1656= bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;16571658*inner_group_loc = regnum - this_group_regnum;1659BUF_PUSH_3(stop_memory, this_group_regnum,1660 regnum - this_group_regnum);1661}1662}1663break;166416651666case'|':/* `\|'. */1667if(syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)1668goto normal_backslash;1669 handle_alt:1670if(syntax & RE_LIMITED_OPS)1671goto normal_char;16721673/* Insert before the previous alternative a jump which1674 jumps to this alternative if the former fails. */1675GET_BUFFER_SPACE(3);1676INSERT_JUMP(on_failure_jump, begalt, b +6);1677 pending_exact =0;1678 b +=3;16791680/* The alternative before this one has a jump after it1681 which gets executed if it gets matched. Adjust that1682 jump so it will jump to this alternative's analogous1683 jump (put in below, which in turn will jump to the next1684 (if any) alternative's such jump, etc.). The last such1685 jump jumps to the correct final destination. A picture:1686 _____ _____1687 | | | |1688 | v | v1689 a | b | c16901691 If we are at `b', then fixup_alt_jump right now points to a1692 three-byte space after `a'. We'll put in the jump, set1693 fixup_alt_jump to right after `b', and leave behind three1694 bytes which we'll fill in when we get to after `c'. */16951696if(fixup_alt_jump)1697STORE_JUMP(jump_past_alt, fixup_alt_jump, b);16981699/* Mark and leave space for a jump after this alternative,1700 to be filled in later either by next alternative or1701 when know we're at the end of a series of alternatives. */1702 fixup_alt_jump = b;1703GET_BUFFER_SPACE(3);1704 b +=3;17051706 laststart =0;1707 begalt = b;1708break;170917101711case'{':1712/* If \{ is a literal. */1713if(!(syntax & RE_INTERVALS)1714/* If we're at `\{' and it's not the open-interval1715 operator. */1716|| ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))1717|| (p -2== pattern && p == pend))1718goto normal_backslash;17191720 handle_interval:1721{1722/* If got here, then the syntax allows intervals. */17231724/* At least (most) this many matches must be made. */1725int lower_bound = -1, upper_bound = -1;17261727 beg_interval = p -1;17281729if(p == pend)1730{1731if(syntax & RE_NO_BK_BRACES)1732goto unfetch_interval;1733else1734return REG_EBRACE;1735}17361737GET_UNSIGNED_NUMBER(lower_bound);17381739if(c ==',')1740{1741GET_UNSIGNED_NUMBER(upper_bound);1742if(upper_bound <0) upper_bound = RE_DUP_MAX;1743}1744else1745/* Interval such as `{1}' => match exactly once. */1746 upper_bound = lower_bound;17471748if(lower_bound <0|| upper_bound > RE_DUP_MAX1749|| lower_bound > upper_bound)1750{1751if(syntax & RE_NO_BK_BRACES)1752goto unfetch_interval;1753else1754return REG_BADBR;1755}17561757if(!(syntax & RE_NO_BK_BRACES))1758{1759if(c !='\\')return REG_EBRACE;17601761PATFETCH(c);1762}17631764if(c !='}')1765{1766if(syntax & RE_NO_BK_BRACES)1767goto unfetch_interval;1768else1769return REG_BADBR;1770}17711772/* We just parsed a valid interval. */17731774/* If it's invalid to have no preceding re. */1775if(!laststart)1776{1777if(syntax & RE_CONTEXT_INVALID_OPS)1778return REG_BADRPT;1779else if(syntax & RE_CONTEXT_INDEP_OPS)1780 laststart = b;1781else1782goto unfetch_interval;1783}17841785/* If the upper bound is zero, don't want to succeed at1786 all; jump from `laststart' to `b + 3', which will be1787 the end of the buffer after we insert the jump. */1788if(upper_bound ==0)1789{1790GET_BUFFER_SPACE(3);1791INSERT_JUMP(jump, laststart, b +3);1792 b +=3;1793}17941795/* Otherwise, we have a nontrivial interval. When1796 we're all done, the pattern will look like:1797 set_number_at <jump count> <upper bound>1798 set_number_at <succeed_n count> <lower bound>1799 succeed_n <after jump addr> <succeed_n count>1800 <body of loop>1801 jump_n <succeed_n addr> <jump count>1802 (The upper bound and `jump_n' are omitted if1803 `upper_bound' is 1, though.) */1804else1805{/* If the upper bound is > 1, we need to insert1806 more at the end of the loop. */1807unsigned nbytes =10+ (upper_bound >1) *10;18081809GET_BUFFER_SPACE(nbytes);18101811/* Initialize lower bound of the `succeed_n', even1812 though it will be set during matching by its1813 attendant `set_number_at' (inserted next),1814 because `re_compile_fastmap' needs to know.1815 Jump to the `jump_n' we might insert below. */1816INSERT_JUMP2(succeed_n, laststart,1817 b +5+ (upper_bound >1) *5,1818 lower_bound);1819 b +=5;18201821/* Code to initialize the lower bound. Insert1822 before the `succeed_n'. The `5' is the last two1823 bytes of this `set_number_at', plus 3 bytes of1824 the following `succeed_n'. */1825insert_op2(set_number_at, laststart,5, lower_bound, b);1826 b +=5;18271828if(upper_bound >1)1829{/* More than one repetition is allowed, so1830 append a backward jump to the `succeed_n'1831 that starts this interval.18321833 When we've reached this during matching,1834 we'll have matched the interval once, so1835 jump back only `upper_bound - 1' times. */1836STORE_JUMP2(jump_n, b, laststart +5,1837 upper_bound -1);1838 b +=5;18391840/* The location we want to set is the second1841 parameter of the `jump_n'; that is `b-2' as1842 an absolute address. `laststart' will be1843 the `set_number_at' we're about to insert;1844 `laststart+3' the number to set, the source1845 for the relative address. But we are1846 inserting into the middle of the pattern --1847 so everything is getting moved up by 5.1848 Conclusion: (b - 2) - (laststart + 3) + 5,1849 i.e., b - laststart.18501851 We insert this at the beginning of the loop1852 so that if we fail during matching, we'll1853 reinitialize the bounds. */1854insert_op2(set_number_at, laststart, b - laststart,1855 upper_bound -1, b);1856 b +=5;1857}1858}1859 pending_exact =0;1860 beg_interval = NULL;1861}1862break;18631864 unfetch_interval:1865/* If an invalid interval, match the characters as literals. */1866assert(beg_interval);1867 p = beg_interval;1868 beg_interval = NULL;18691870/* normal_char and normal_backslash need `c'. */1871PATFETCH(c);18721873if(!(syntax & RE_NO_BK_BRACES))1874{1875if(p > pattern && p[-1] =='\\')1876goto normal_backslash;1877}1878goto normal_char;18791880#ifdef emacs1881/* There is no way to specify the before_dot and after_dot1882 operators. rms says this is ok. --karl */1883case'=':1884BUF_PUSH(at_dot);1885break;18861887case's':1888 laststart = b;1889PATFETCH(c);1890BUF_PUSH_2(syntaxspec, syntax_spec_code[c]);1891break;18921893case'S':1894 laststart = b;1895PATFETCH(c);1896BUF_PUSH_2(notsyntaxspec, syntax_spec_code[c]);1897break;1898#endif/* emacs */189919001901case'w':1902 laststart = b;1903BUF_PUSH(wordchar);1904break;190519061907case'W':1908 laststart = b;1909BUF_PUSH(notwordchar);1910break;191119121913case'<':1914BUF_PUSH(wordbeg);1915break;19161917case'>':1918BUF_PUSH(wordend);1919break;19201921case'b':1922BUF_PUSH(wordbound);1923break;19241925case'B':1926BUF_PUSH(notwordbound);1927break;19281929case'`':1930BUF_PUSH(begbuf);1931break;19321933case'\'':1934BUF_PUSH(endbuf);1935break;19361937case'1':case'2':case'3':case'4':case'5':1938case'6':case'7':case'8':case'9':1939if(syntax & RE_NO_BK_REFS)1940goto normal_char;19411942 c1 = c -'0';19431944if(c1 > regnum)1945return REG_ESUBREG;19461947/* Can't back reference to a subexpression if inside of it. */1948if(group_in_compile_stack(compile_stack, c1))1949goto normal_char;19501951 laststart = b;1952BUF_PUSH_2(duplicate, c1);1953break;195419551956case'+':1957case'?':1958if(syntax & RE_BK_PLUS_QM)1959goto handle_plus;1960else1961goto normal_backslash;19621963default:1964 normal_backslash:1965/* You might think it would be useful for \ to mean1966 not to translate; but if we don't translate it1967 it will never match anything. */1968 c =TRANSLATE(c);1969goto normal_char;1970}1971break;197219731974default:1975/* Expects the character in `c'. */1976 normal_char:1977/* If no exactn currently being built. */1978if(!pending_exact19791980/* If last exactn not at current position. */1981|| pending_exact + *pending_exact +1!= b19821983/* We have only one byte following the exactn for the count. */1984|| *pending_exact == (1<< BYTEWIDTH) -119851986/* If followed by a repetition operator. */1987|| *p =='*'|| *p =='^'1988|| ((syntax & RE_BK_PLUS_QM)1989? *p =='\\'&& (p[1] =='+'|| p[1] =='?')1990: (*p =='+'|| *p =='?'))1991|| ((syntax & RE_INTERVALS)1992&& ((syntax & RE_NO_BK_BRACES)1993? *p =='{'1994: (p[0] =='\\'&& p[1] =='{'))))1995{1996/* Start building a new exactn. */19971998 laststart = b;19992000BUF_PUSH_2(exactn,0);2001 pending_exact = b -1;2002}20032004BUF_PUSH(c);2005(*pending_exact)++;2006break;2007}/* switch (c) */2008}/* while p != pend */200920102011/* Through the pattern now. */20122013if(fixup_alt_jump)2014STORE_JUMP(jump_past_alt, fixup_alt_jump, b);20152016if(!COMPILE_STACK_EMPTY)2017return REG_EPAREN;20182019free(compile_stack.stack);20202021/* We have succeeded; set the length of the buffer. */2022 bufp->used = b - bufp->buffer;20232024#ifdef DEBUG2025if(debug)2026{2027DEBUG_PRINT1("\nCompiled pattern: ");2028print_compiled_pattern(bufp);2029}2030#endif/* DEBUG */20312032return REG_NOERROR;2033}/* regex_compile */2034\f2035/* Subroutines for `regex_compile'. */20362037/* Store OP at LOC followed by two-byte integer parameter ARG. */20382039static void2040store_op1(op, loc, arg)2041 re_opcode_t op;2042unsigned char*loc;2043int arg;2044{2045*loc = (unsigned char) op;2046STORE_NUMBER(loc +1, arg);2047}204820492050/* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */20512052static void2053store_op2(op, loc, arg1, arg2)2054 re_opcode_t op;2055unsigned char*loc;2056int arg1, arg2;2057{2058*loc = (unsigned char) op;2059STORE_NUMBER(loc +1, arg1);2060STORE_NUMBER(loc +3, arg2);2061}206220632064/* Copy the bytes from LOC to END to open up three bytes of space at LOC2065 for OP followed by two-byte integer parameter ARG. */20662067static void2068insert_op1(op, loc, arg, end)2069 re_opcode_t op;2070unsigned char*loc;2071int arg;2072unsigned char*end;2073{2074registerunsigned char*pfrom = end;2075registerunsigned char*pto = end +3;20762077while(pfrom != loc)2078*--pto = *--pfrom;20792080store_op1(op, loc, arg);2081}208220832084/* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */20852086static void2087insert_op2(op, loc, arg1, arg2, end)2088 re_opcode_t op;2089unsigned char*loc;2090int arg1, arg2;2091unsigned char*end;2092{2093registerunsigned char*pfrom = end;2094registerunsigned char*pto = end +5;20952096while(pfrom != loc)2097*--pto = *--pfrom;20982099store_op2(op, loc, arg1, arg2);2100}210121022103/* P points to just after a ^ in PATTERN. Return true if that ^ comes2104 after an alternative or a begin-subexpression. We assume there is at2105 least one character before the ^. */21062107static boolean2108at_begline_loc_p(pattern, p, syntax)2109const char*pattern, *p;2110 reg_syntax_t syntax;2111{2112const char*prev = p -2;2113 boolean prev_prev_backslash = prev > pattern && prev[-1] =='\\';21142115return2116/* After a subexpression? */2117(*prev =='('&& (syntax & RE_NO_BK_PARENS || prev_prev_backslash))2118/* After an alternative? */2119|| (*prev =='|'&& (syntax & RE_NO_BK_VBAR || prev_prev_backslash));2120}212121222123/* The dual of at_begline_loc_p. This one is for $. We assume there is2124 at least one character after the $, i.e., `P < PEND'. */21252126static boolean2127at_endline_loc_p(p, pend, syntax)2128const char*p, *pend;2129int syntax;2130{2131const char*next = p;2132 boolean next_backslash = *next =='\\';2133const char*next_next = p +1< pend ? p +1: NULL;21342135return2136/* Before a subexpression? */2137(syntax & RE_NO_BK_PARENS ? *next ==')'2138: next_backslash && next_next && *next_next ==')')2139/* Before an alternative? */2140|| (syntax & RE_NO_BK_VBAR ? *next =='|'2141: next_backslash && next_next && *next_next =='|');2142}214321442145/* Returns true if REGNUM is in one of COMPILE_STACK's elements and2146 false if it's not. */21472148static boolean2149group_in_compile_stack(compile_stack, regnum)2150 compile_stack_type compile_stack;2151 regnum_t regnum;2152{2153int this_element;21542155for(this_element = compile_stack.avail -1;2156 this_element >=0;2157 this_element--)2158if(compile_stack.stack[this_element].regnum == regnum)2159return true;21602161return false;2162}216321642165/* Read the ending character of a range (in a bracket expression) from the2166 uncompiled pattern *P_PTR (which ends at PEND). We assume the2167 starting character is in `P[-2]'. (`P[-1]' is the character `-'.)2168 Then we set the translation of all bits between the starting and2169 ending characters (inclusive) in the compiled pattern B.21702171 Return an error code.21722173 We use these short variable names so we can use the same macros as2174 `regex_compile' itself. */21752176static reg_errcode_t2177compile_range(p_ptr, pend, translate, syntax, b)2178const char**p_ptr, *pend;2179char*translate;2180 reg_syntax_t syntax;2181unsigned char*b;2182{2183unsigned this_char;21842185const char*p = *p_ptr;2186int range_start, range_end;21872188if(p == pend)2189return REG_ERANGE;21902191/* Even though the pattern is a signed `char *', we need to fetch2192 with unsigned char *'s; if the high bit of the pattern character2193 is set, the range endpoints will be negative if we fetch using a2194 signed char *.21952196 We also want to fetch the endpoints without translating them; the2197 appropriate translation is done in the bit-setting loop below. */2198 range_start = ((unsigned char*) p)[-2];2199 range_end = ((unsigned char*) p)[0];22002201/* Have to increment the pointer into the pattern string, so the2202 caller isn't still at the ending character. */2203(*p_ptr)++;22042205/* If the start is after the end, the range is empty. */2206if(range_start > range_end)2207return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;22082209/* Here we see why `this_char' has to be larger than an `unsigned2210 char' -- the range is inclusive, so if `range_end' == 0xff2211 (assuming 8-bit characters), we would otherwise go into an infinite2212 loop, since all characters <= 0xff. */2213for(this_char = range_start; this_char <= range_end; this_char++)2214{2215SET_LIST_BIT(TRANSLATE(this_char));2216}22172218return REG_NOERROR;2219}2220\f2221/* Failure stack declarations and macros; both re_compile_fastmap and2222 re_match_2 use a failure stack. These have to be macros because of2223 REGEX_ALLOCATE. */222422252226/* Number of failure points for which to initially allocate space2227 when matching. If this number is exceeded, we allocate more2228 space, so it is not a hard limit. */2229#ifndef INIT_FAILURE_ALLOC2230#define INIT_FAILURE_ALLOC 52231#endif22322233/* Roughly the maximum number of failure points on the stack. Would be2234 exactly that if always used MAX_FAILURE_SPACE each time we failed.2235 This is a variable only so users of regex can assign to it; we never2236 change it ourselves. */2237int re_max_failures =2000;22382239typedefconst unsigned char*fail_stack_elt_t;22402241typedefstruct2242{2243 fail_stack_elt_t *stack;2244unsigned size;2245unsigned avail;/* Offset of next open position. */2246} fail_stack_type;22472248#define FAIL_STACK_EMPTY() (fail_stack.avail == 0)2249#define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)2250#define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)2251#define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])225222532254/* Initialize `fail_stack'. Do `return -2' if the alloc fails. */22552256#define INIT_FAIL_STACK() \2257 do { \2258 fail_stack.stack = (fail_stack_elt_t *) \2259 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \2260 \2261 if (fail_stack.stack == NULL) \2262 return -2; \2263 \2264 fail_stack.size = INIT_FAILURE_ALLOC; \2265 fail_stack.avail = 0; \2266 } while (0)226722682269/* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.22702271 Return 1 if succeeds, and 0 if either ran out of memory2272 allocating space for it or it was already too large.22732274 REGEX_REALLOCATE requires `destination' be declared. */22752276#define DOUBLE_FAIL_STACK(fail_stack) \2277 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \2278 ? 0 \2279 : ((fail_stack).stack = (fail_stack_elt_t *) \2280 REGEX_REALLOCATE ((fail_stack).stack, \2281 (fail_stack).size * sizeof (fail_stack_elt_t), \2282 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \2283 \2284 (fail_stack).stack == NULL \2285 ? 0 \2286 : ((fail_stack).size <<= 1, \2287 1)))228822892290/* Push PATTERN_OP on FAIL_STACK.22912292 Return 1 if was able to do so and 0 if ran out of memory allocating2293 space to do so. */2294#define PUSH_PATTERN_OP(pattern_op, fail_stack) \2295 ((FAIL_STACK_FULL () \2296 && !DOUBLE_FAIL_STACK (fail_stack)) \2297 ? 0 \2298 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \2299 1))23002301/* This pushes an item onto the failure stack. Must be a four-byte2302 value. Assumes the variable `fail_stack'. Probably should only2303 be called from within `PUSH_FAILURE_POINT'. */2304#define PUSH_FAILURE_ITEM(item) \2305 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item23062307/* The complement operation. Assumes `fail_stack' is nonempty. */2308#define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]23092310/* Used to omit pushing failure point id's when we're not debugging. */2311#ifdef DEBUG2312#define DEBUG_PUSH PUSH_FAILURE_ITEM2313#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()2314#else2315#define DEBUG_PUSH(item)2316#define DEBUG_POP(item_addr)2317#endif231823192320/* Push the information about the state we will need2321 if we ever fail back to it.23222323 Requires variables fail_stack, regstart, regend, reg_info, and2324 num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be2325 declared.23262327 Does `return FAILURE_CODE' if runs out of memory. */23282329#define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \2330 do { \2331 char *destination; \2332/* Must be int, so when we don't save any registers, the arithmetic \2333 of 0 + -1 isn't done as unsigned. */ \2334 int this_reg; \2335 \2336 DEBUG_STATEMENT (failure_id++); \2337 DEBUG_STATEMENT (nfailure_points_pushed++); \2338 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \2339 DEBUG_PRINT2 (" Before push, next avail:%d\n", (fail_stack).avail);\2340 DEBUG_PRINT2 (" size:%d\n", (fail_stack).size);\2341 \2342 DEBUG_PRINT2 (" slots needed:%d\n", NUM_FAILURE_ITEMS); \2343 DEBUG_PRINT2 (" available:%d\n", REMAINING_AVAIL_SLOTS); \2344 \2345/* Ensure we have enough space allocated for what we will push. */ \2346 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \2347 { \2348 if (!DOUBLE_FAIL_STACK (fail_stack)) \2349 return failure_code; \2350 \2351 DEBUG_PRINT2 ("\nDoubled stack; size now:%d\n", \2352 (fail_stack).size); \2353 DEBUG_PRINT2 (" slots available:%d\n", REMAINING_AVAIL_SLOTS);\2354 } \2355 \2356/* Push the info, starting with the registers. */ \2357 DEBUG_PRINT1 ("\n"); \2358 \2359 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \2360 this_reg++) \2361 { \2362 DEBUG_PRINT2 (" Pushing reg:%d\n", this_reg); \2363 DEBUG_STATEMENT (num_regs_pushed++); \2364 \2365 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \2366 PUSH_FAILURE_ITEM (regstart[this_reg]); \2367 \2368 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \2369 PUSH_FAILURE_ITEM (regend[this_reg]); \2370 \2371 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \2372 DEBUG_PRINT2 (" match_null=%d", \2373 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \2374 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \2375 DEBUG_PRINT2 (" matched_something=%d", \2376 MATCHED_SOMETHING (reg_info[this_reg])); \2377 DEBUG_PRINT2 (" ever_matched=%d", \2378 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \2379 DEBUG_PRINT1 ("\n"); \2380 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \2381 } \2382 \2383 DEBUG_PRINT2 (" Pushing low active reg:%d\n", lowest_active_reg);\2384 PUSH_FAILURE_ITEM (lowest_active_reg); \2385 \2386 DEBUG_PRINT2 (" Pushing high active reg:%d\n", highest_active_reg);\2387 PUSH_FAILURE_ITEM (highest_active_reg); \2388 \2389 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \2390 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \2391 PUSH_FAILURE_ITEM (pattern_place); \2392 \2393 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \2394 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \2395 size2); \2396 DEBUG_PRINT1 ("'\n"); \2397 PUSH_FAILURE_ITEM (string_place); \2398 \2399 DEBUG_PRINT2 (" Pushing failure id:%u\n", failure_id); \2400 DEBUG_PUSH (failure_id); \2401 } while (0)24022403/* This is the number of items that are pushed and popped on the stack2404 for each register. */2405#define NUM_REG_ITEMS 324062407/* Individual items aside from the registers. */2408#ifdef DEBUG2409#define NUM_NONREG_ITEMS 5/* Includes failure point id. */2410#else2411#define NUM_NONREG_ITEMS 42412#endif24132414/* We push at most this many items on the stack. */2415#define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)24162417/* We actually push this many items. */2418#define NUM_FAILURE_ITEMS \2419 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \2420 + NUM_NONREG_ITEMS)24212422/* How many items can still be added to the stack without overflowing it. */2423#define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)242424252426/* Pops what PUSH_FAIL_STACK pushes.24272428 We restore into the parameters, all of which should be lvalues:2429 STR -- the saved data position.2430 PAT -- the saved pattern position.2431 LOW_REG, HIGH_REG -- the highest and lowest active registers.2432 REGSTART, REGEND -- arrays of string positions.2433 REG_INFO -- array of information about each subexpression.24342435 Also assumes the variables `fail_stack' and (if debugging), `bufp',2436 `pend', `string1', `size1', `string2', and `size2'. */24372438#define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\2439{ \2440 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \2441 int this_reg; \2442 const unsigned char *string_temp; \2443 \2444 assert (!FAIL_STACK_EMPTY ()); \2445 \2446/* Remove failure points and point to how many regs pushed. */ \2447 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \2448 DEBUG_PRINT2 (" Before pop, next avail:%d\n", fail_stack.avail); \2449 DEBUG_PRINT2 (" size:%d\n", fail_stack.size); \2450 \2451 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \2452 \2453 DEBUG_POP (&failure_id); \2454 DEBUG_PRINT2 (" Popping failure id:%u\n", failure_id); \2455 \2456/* If the saved string location is NULL, it came from an \2457 on_failure_keep_string_jump opcode, and we want to throw away the \2458 saved NULL, thus retaining our current position in the string. */ \2459 string_temp = POP_FAILURE_ITEM (); \2460 if (string_temp != NULL) \2461 str = (const char *) string_temp; \2462 \2463 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \2464 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \2465 DEBUG_PRINT1 ("'\n"); \2466 \2467 pat = (unsigned char *) POP_FAILURE_ITEM (); \2468 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \2469 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \2470 \2471/* Restore register info. */ \2472 high_reg = (unsigned) POP_FAILURE_ITEM (); \2473 DEBUG_PRINT2 (" Popping high active reg:%d\n", high_reg); \2474 \2475 low_reg = (unsigned) POP_FAILURE_ITEM (); \2476 DEBUG_PRINT2 (" Popping low active reg:%d\n", low_reg); \2477 \2478 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \2479 { \2480 DEBUG_PRINT2 (" Popping reg:%d\n", this_reg); \2481 \2482 reg_info[this_reg].word = POP_FAILURE_ITEM (); \2483 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \2484 \2485 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \2486 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \2487 \2488 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \2489 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \2490 } \2491 \2492 DEBUG_STATEMENT (nfailure_points_popped++); \2493}/* POP_FAILURE_POINT */2494\f2495/* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in2496 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible2497 characters can start a string that matches the pattern. This fastmap2498 is used by re_search to skip quickly over impossible starting points.24992500 The caller must supply the address of a (1 << BYTEWIDTH)-byte data2501 area as BUFP->fastmap.25022503 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in2504 the pattern buffer.25052506 Returns 0 if we succeed, -2 if an internal error. */25072508int2509re_compile_fastmap(bufp)2510struct re_pattern_buffer *bufp;2511{2512int j, k;2513 fail_stack_type fail_stack;2514#ifndef REGEX_MALLOC2515char*destination;2516#endif2517/* We don't push any register information onto the failure stack. */2518unsigned num_regs =0;25192520registerchar*fastmap = bufp->fastmap;2521unsigned char*pattern = bufp->buffer;2522unsigned long size = bufp->used;2523const unsigned char*p = pattern;2524registerunsigned char*pend = pattern + size;25252526/* Assume that each path through the pattern can be null until2527 proven otherwise. We set this false at the bottom of switch2528 statement, to which we get only if a particular path doesn't2529 match the empty string. */2530 boolean path_can_be_null =true;25312532/* We aren't doing a `succeed_n' to begin with. */2533 boolean succeed_n_p =false;25342535assert(fastmap != NULL && p != NULL);25362537INIT_FAIL_STACK();2538bzero(fastmap,1<< BYTEWIDTH);/* Assume nothing's valid. */2539 bufp->fastmap_accurate =1;/* It will be when we're done. */2540 bufp->can_be_null =0;25412542while(p != pend || !FAIL_STACK_EMPTY())2543{2544if(p == pend)2545{2546 bufp->can_be_null |= path_can_be_null;25472548/* Reset for next path. */2549 path_can_be_null =true;25502551 p = fail_stack.stack[--fail_stack.avail];2552}25532554/* We should never be about to go beyond the end of the pattern. */2555assert(p < pend);25562557#ifdef SWITCH_ENUM_BUG2558switch((int) ((re_opcode_t) *p++))2559#else2560switch((re_opcode_t) *p++)2561#endif2562{25632564/* I guess the idea here is to simply not bother with a fastmap2565 if a backreference is used, since it's too hard to figure out2566 the fastmap for the corresponding group. Setting2567 `can_be_null' stops `re_search_2' from using the fastmap, so2568 that is all we do. */2569case duplicate:2570 bufp->can_be_null =1;2571return0;257225732574/* Following are the cases which match a character. These end2575 with `break'. */25762577case exactn:2578 fastmap[p[1]] =1;2579break;258025812582case charset:2583for(j = *p++ * BYTEWIDTH -1; j >=0; j--)2584if(p[j / BYTEWIDTH] & (1<< (j % BYTEWIDTH)))2585 fastmap[j] =1;2586break;258725882589case charset_not:2590/* Chars beyond end of map must be allowed. */2591for(j = *p * BYTEWIDTH; j < (1<< BYTEWIDTH); j++)2592 fastmap[j] =1;25932594for(j = *p++ * BYTEWIDTH -1; j >=0; j--)2595if(!(p[j / BYTEWIDTH] & (1<< (j % BYTEWIDTH))))2596 fastmap[j] =1;2597break;259825992600case wordchar:2601for(j =0; j < (1<< BYTEWIDTH); j++)2602if(SYNTAX(j) == Sword)2603 fastmap[j] =1;2604break;260526062607case notwordchar:2608for(j =0; j < (1<< BYTEWIDTH); j++)2609if(SYNTAX(j) != Sword)2610 fastmap[j] =1;2611break;261226132614case anychar:2615/* `.' matches anything ... */2616for(j =0; j < (1<< BYTEWIDTH); j++)2617 fastmap[j] =1;26182619/* ... except perhaps newline. */2620if(!(bufp->syntax & RE_DOT_NEWLINE))2621 fastmap['\n'] =0;26222623/* Return if we have already set `can_be_null'; if we have,2624 then the fastmap is irrelevant. Something's wrong here. */2625else if(bufp->can_be_null)2626return0;26272628/* Otherwise, have to check alternative paths. */2629break;263026312632#ifdef emacs2633case syntaxspec:2634 k = *p++;2635for(j =0; j < (1<< BYTEWIDTH); j++)2636if(SYNTAX(j) == (enum syntaxcode) k)2637 fastmap[j] =1;2638break;263926402641case notsyntaxspec:2642 k = *p++;2643for(j =0; j < (1<< BYTEWIDTH); j++)2644if(SYNTAX(j) != (enum syntaxcode) k)2645 fastmap[j] =1;2646break;264726482649/* All cases after this match the empty string. These end with2650 `continue'. */265126522653case before_dot:2654case at_dot:2655case after_dot:2656continue;2657#endif/* not emacs */265826592660case no_op:2661case begline:2662case endline:2663case begbuf:2664case endbuf:2665case wordbound:2666case notwordbound:2667case wordbeg:2668case wordend:2669case push_dummy_failure:2670continue;267126722673case jump_n:2674case pop_failure_jump:2675case maybe_pop_jump:2676case jump:2677case jump_past_alt:2678case dummy_failure_jump:2679EXTRACT_NUMBER_AND_INCR(j, p);2680 p += j;2681if(j >0)2682continue;26832684/* Jump backward implies we just went through the body of a2685 loop and matched nothing. Opcode jumped to should be2686 `on_failure_jump' or `succeed_n'. Just treat it like an2687 ordinary jump. For a * loop, it has pushed its failure2688 point already; if so, discard that as redundant. */2689if((re_opcode_t) *p != on_failure_jump2690&& (re_opcode_t) *p != succeed_n)2691continue;26922693 p++;2694EXTRACT_NUMBER_AND_INCR(j, p);2695 p += j;26962697/* If what's on the stack is where we are now, pop it. */2698if(!FAIL_STACK_EMPTY()2699&& fail_stack.stack[fail_stack.avail -1] == p)2700 fail_stack.avail--;27012702continue;270327042705case on_failure_jump:2706case on_failure_keep_string_jump:2707 handle_on_failure_jump:2708EXTRACT_NUMBER_AND_INCR(j, p);27092710/* For some patterns, e.g., `(a?)?', `p+j' here points to the2711 end of the pattern. We don't want to push such a point,2712 since when we restore it above, entering the switch will2713 increment `p' past the end of the pattern. We don't need2714 to push such a point since we obviously won't find any more2715 fastmap entries beyond `pend'. Such a pattern can match2716 the null string, though. */2717if(p + j < pend)2718{2719if(!PUSH_PATTERN_OP(p + j, fail_stack))2720return-2;2721}2722else2723 bufp->can_be_null =1;27242725if(succeed_n_p)2726{2727EXTRACT_NUMBER_AND_INCR(k, p);/* Skip the n. */2728 succeed_n_p =false;2729}27302731continue;273227332734case succeed_n:2735/* Get to the number of times to succeed. */2736 p +=2;27372738/* Increment p past the n for when k != 0. */2739EXTRACT_NUMBER_AND_INCR(k, p);2740if(k ==0)2741{2742 p -=4;2743 succeed_n_p =true;/* Spaghetti code alert. */2744goto handle_on_failure_jump;2745}2746continue;274727482749case set_number_at:2750 p +=4;2751continue;275227532754case start_memory:2755case stop_memory:2756 p +=2;2757continue;275827592760default:2761abort();/* We have listed all the cases. */2762}/* switch *p++ */27632764/* Getting here means we have found the possible starting2765 characters for one path of the pattern -- and that the empty2766 string does not match. We need not follow this path further.2767 Instead, look at the next alternative (remembered on the2768 stack), or quit if no more. The test at the top of the loop2769 does these things. */2770 path_can_be_null =false;2771 p = pend;2772}/* while p */27732774/* Set `can_be_null' for the last path (also the first path, if the2775 pattern is empty). */2776 bufp->can_be_null |= path_can_be_null;2777return0;2778}/* re_compile_fastmap */2779\f2780/* Set REGS to hold NUM_REGS registers, storing them in STARTS and2781 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use2782 this memory for recording register information. STARTS and ENDS2783 must be allocated using the malloc library routine, and must each2784 be at least NUM_REGS * sizeof (regoff_t) bytes long.27852786 If NUM_REGS == 0, then subsequent matches should allocate their own2787 register data.27882789 Unless this function is called, the first search or match using2790 PATTERN_BUFFER will allocate its own register data, without2791 freeing the old data. */27922793void2794re_set_registers(bufp, regs, num_regs, starts, ends)2795struct re_pattern_buffer *bufp;2796struct re_registers *regs;2797unsigned num_regs;2798 regoff_t *starts, *ends;2799{2800if(num_regs)2801{2802 bufp->regs_allocated = REGS_REALLOCATE;2803 regs->num_regs = num_regs;2804 regs->start = starts;2805 regs->end = ends;2806}2807else2808{2809 bufp->regs_allocated = REGS_UNALLOCATED;2810 regs->num_regs =0;2811 regs->start = regs->end = (regoff_t *)0;2812}2813}2814\f2815/* Searching routines. */28162817/* Like re_search_2, below, but only one string is specified, and2818 doesn't let you say where to stop matching. */28192820int2821re_search(bufp, string, size, startpos, range, regs)2822struct re_pattern_buffer *bufp;2823const char*string;2824int size, startpos, range;2825struct re_registers *regs;2826{2827returnre_search_2(bufp, NULL,0, string, size, startpos, range,2828 regs, size);2829}283028312832/* Using the compiled pattern in BUFP->buffer, first tries to match the2833 virtual concatenation of STRING1 and STRING2, starting first at index2834 STARTPOS, then at STARTPOS + 1, and so on.28352836 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.28372838 RANGE is how far to scan while trying to match. RANGE = 0 means try2839 only at STARTPOS; in general, the last start tried is STARTPOS +2840 RANGE.28412842 In REGS, return the indices of the virtual concatenation of STRING12843 and STRING2 that matched the entire BUFP->buffer and its contained2844 subexpressions.28452846 Do not consider matching one past the index STOP in the virtual2847 concatenation of STRING1 and STRING2.28482849 We return either the position in the strings at which the match was2850 found, -1 if no match, or -2 if error (such as failure2851 stack overflow). */28522853int2854re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop)2855struct re_pattern_buffer *bufp;2856const char*string1, *string2;2857int size1, size2;2858int startpos;2859int range;2860struct re_registers *regs;2861int stop;2862{2863int val;2864registerchar*fastmap = bufp->fastmap;2865registerchar*translate = bufp->translate;2866int total_size = size1 + size2;2867int endpos = startpos + range;28682869/* Check for out-of-range STARTPOS. */2870if(startpos <0|| startpos > total_size)2871return-1;28722873/* Fix up RANGE if it might eventually take us outside2874 the virtual concatenation of STRING1 and STRING2. */2875if(endpos < -1)2876 range = -1- startpos;2877else if(endpos > total_size)2878 range = total_size - startpos;28792880/* If the search isn't to be a backwards one, don't waste time in a2881 search for a pattern that must be anchored. */2882if(bufp->used >0&& (re_opcode_t) bufp->buffer[0] == begbuf && range >0)2883{2884if(startpos >0)2885return-1;2886else2887 range =1;2888}28892890/* Update the fastmap now if not correct already. */2891if(fastmap && !bufp->fastmap_accurate)2892if(re_compile_fastmap(bufp) == -2)2893return-2;28942895/* Loop through the string, looking for a place to start matching. */2896for(;;)2897{2898/* If a fastmap is supplied, skip quickly over characters that2899 cannot be the start of a match. If the pattern can match the2900 null string, however, we don't need to skip characters; we want2901 the first null string. */2902if(fastmap && startpos < total_size && !bufp->can_be_null)2903{2904if(range >0)/* Searching forwards. */2905{2906registerconst char*d;2907registerint lim =0;2908int irange = range;29092910if(startpos < size1 && startpos + range >= size1)2911 lim = range - (size1 - startpos);29122913 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;29142915/* Written out as an if-else to avoid testing `translate'2916 inside the loop. */2917if(translate)2918while(range > lim2919&& !fastmap[(unsigned char)2920 translate[(unsigned char) *d++]])2921 range--;2922else2923while(range > lim && !fastmap[(unsigned char) *d++])2924 range--;29252926 startpos += irange - range;2927}2928else/* Searching backwards. */2929{2930registerchar c = (size1 ==0|| startpos >= size12931? string2[startpos - size1]2932: string1[startpos]);29332934if(!fastmap[(unsigned char)TRANSLATE(c)])2935goto advance;2936}2937}29382939/* If can't match the null string, and that's all we have left, fail. */2940if(range >=0&& startpos == total_size && fastmap2941&& !bufp->can_be_null)2942return-1;29432944 val =re_match_2(bufp, string1, size1, string2, size2,2945 startpos, regs, stop);2946if(val >=0)2947return startpos;29482949if(val == -2)2950return-2;29512952 advance:2953if(!range)2954break;2955else if(range >0)2956{2957 range--;2958 startpos++;2959}2960else2961{2962 range++;2963 startpos--;2964}2965}2966return-1;2967}/* re_search_2 */2968\f2969/* Declarations and macros for re_match_2. */29702971static intbcmp_translate();2972static boolean alt_match_null_string_p(),2973common_op_match_null_string_p(),2974group_match_null_string_p();29752976/* Structure for per-register (a.k.a. per-group) information.2977 This must not be longer than one word, because we push this value2978 onto the failure stack. Other register information, such as the2979 starting and ending positions (which are addresses), and the list of2980 inner groups (which is a bits list) are maintained in separate2981 variables.29822983 We are making a (strictly speaking) nonportable assumption here: that2984 the compiler will pack our bit fields into something that fits into2985 the type of `word', i.e., is something that fits into one item on the2986 failure stack. */2987typedefunion2988{2989 fail_stack_elt_t word;2990struct2991{2992/* This field is one if this group can match the empty string,2993 zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */2994#define MATCH_NULL_UNSET_VALUE 32995unsigned match_null_string_p :2;2996unsigned is_active :1;2997unsigned matched_something :1;2998unsigned ever_matched_something :1;2999} bits;3000} register_info_type;30013002#define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)3003#define IS_ACTIVE(R) ((R).bits.is_active)3004#define MATCHED_SOMETHING(R) ((R).bits.matched_something)3005#define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)300630073008/* Call this when have matched a real character; it sets `matched' flags3009 for the subexpressions which we are currently inside. Also records3010 that those subexprs have matched. */3011#define SET_REGS_MATCHED() \3012 do \3013 { \3014 unsigned r; \3015 for (r = lowest_active_reg; r <= highest_active_reg; r++) \3016 { \3017 MATCHED_SOMETHING (reg_info[r]) \3018 = EVER_MATCHED_SOMETHING (reg_info[r]) \3019 = 1; \3020 } \3021 } \3022 while (0)302330243025/* This converts PTR, a pointer into one of the search strings `string1'3026 and `string2' into an offset from the beginning of that string. */3027#define POINTER_TO_OFFSET(ptr) \3028 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)30293030/* Registers are set to a sentinel when they haven't yet matched. */3031#define REG_UNSET_VALUE ((char *) -1)3032#define REG_UNSET(e) ((e) == REG_UNSET_VALUE)303330343035/* Macros for dealing with the split strings in re_match_2. */30363037#define MATCHING_IN_FIRST_STRING (dend == end_match_1)30383039/* Call before fetching a character with *d. This switches over to3040 string2 if necessary. */3041#define PREFETCH() \3042 while (d == dend) \3043 { \3044/* End of string2 => fail. */ \3045 if (dend == end_match_2) \3046 goto fail; \3047/* End of string1 => advance to string2. */ \3048 d = string2; \3049 dend = end_match_2; \3050 }305130523053/* Test if at very beginning or at very end of the virtual concatenation3054 of `string1' and `string2'. If only one string, it's `string2'. */3055#define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)3056#define AT_STRINGS_END(d) ((d) == end2)305730583059/* Test if D points to a character which is word-constituent. We have3060 two special cases to check for: if past the end of string1, look at3061 the first character in string2; and if before the beginning of3062 string2, look at the last character in string1. */3063#define WORDCHAR_P(d) \3064 (SYNTAX ((d) == end1 ? *string2 \3065 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \3066 == Sword)30673068/* Test if the character before D and the one at D differ with respect3069 to being word-constituent. */3070#define AT_WORD_BOUNDARY(d) \3071 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \3072 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))307330743075/* Free everything we malloc. */3076#ifdef REGEX_MALLOC3077#define FREE_VAR(var) if (var) free (var); var = NULL3078#define FREE_VARIABLES() \3079 do { \3080 FREE_VAR (fail_stack.stack); \3081 FREE_VAR (regstart); \3082 FREE_VAR (regend); \3083 FREE_VAR (old_regstart); \3084 FREE_VAR (old_regend); \3085 FREE_VAR (best_regstart); \3086 FREE_VAR (best_regend); \3087 FREE_VAR (reg_info); \3088 FREE_VAR (reg_dummy); \3089 FREE_VAR (reg_info_dummy); \3090 } while (0)3091#else/* not REGEX_MALLOC */3092/* Some MIPS systems (at least) want this to free alloca'd storage. */3093#define FREE_VARIABLES() alloca (0)3094#endif/* not REGEX_MALLOC */309530963097/* These values must meet several constraints. They must not be valid3098 register values; since we have a limit of 255 registers (because3099 we use only one byte in the pattern for the register number), we can3100 use numbers larger than 255. They must differ by 1, because of3101 NUM_FAILURE_ITEMS above. And the value for the lowest register must3102 be larger than the value for the highest register, so we do not try3103 to actually save any registers when none are active. */3104#define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)3105#define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)3106\f3107/* Matching routines. */31083109#ifndef emacs/* Emacs never uses this. */3110/* re_match is like re_match_2 except it takes only a single string. */31113112int3113re_match(bufp, string, size, pos, regs)3114struct re_pattern_buffer *bufp;3115const char*string;3116int size, pos;3117struct re_registers *regs;3118{3119returnre_match_2(bufp, NULL,0, string, size, pos, regs, size);3120}3121#endif/* not emacs */312231233124/* re_match_2 matches the compiled pattern in BUFP against the3125 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE13126 and SIZE2, respectively). We start matching at POS, and stop3127 matching at STOP.31283129 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we3130 store offsets for the substring each group matched in REGS. See the3131 documentation for exactly how many groups we fill.31323133 We return -1 if no match, -2 if an internal error (such as the3134 failure stack overflowing). Otherwise, we return the length of the3135 matched substring. */31363137int3138re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop)3139struct re_pattern_buffer *bufp;3140const char*string1, *string2;3141int size1, size2;3142int pos;3143struct re_registers *regs;3144int stop;3145{3146/* General temporaries. */3147int mcnt;3148unsigned char*p1;31493150/* Just past the end of the corresponding string. */3151const char*end1, *end2;31523153/* Pointers into string1 and string2, just past the last characters in3154 each to consider matching. */3155const char*end_match_1, *end_match_2;31563157/* Where we are in the data, and the end of the current string. */3158const char*d, *dend;31593160/* Where we are in the pattern, and the end of the pattern. */3161unsigned char*p = bufp->buffer;3162registerunsigned char*pend = p + bufp->used;31633164/* We use this to map every character in the string. */3165char*translate = bufp->translate;31663167/* Failure point stack. Each place that can handle a failure further3168 down the line pushes a failure point on this stack. It consists of3169 restart, regend, and reg_info for all registers corresponding to3170 the subexpressions we're currently inside, plus the number of such3171 registers, and, finally, two char *'s. The first char * is where3172 to resume scanning the pattern; the second one is where to resume3173 scanning the strings. If the latter is zero, the failure point is3174 a ``dummy''; if a failure happens and the failure point is a dummy,3175 it gets discarded and the next next one is tried. */3176 fail_stack_type fail_stack;3177#ifdef DEBUG3178static unsigned failure_id =0;3179unsigned nfailure_points_pushed =0, nfailure_points_popped =0;3180#endif31813182/* We fill all the registers internally, independent of what we3183 return, for use in backreferences. The number here includes3184 an element for register zero. */3185unsigned num_regs = bufp->re_nsub +1;31863187/* The currently active registers. */3188unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;3189unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;31903191/* Information on the contents of registers. These are pointers into3192 the input strings; they record just what was matched (on this3193 attempt) by a subexpression part of the pattern, that is, the3194 regnum-th regstart pointer points to where in the pattern we began3195 matching and the regnum-th regend points to right after where we3196 stopped matching the regnum-th subexpression. (The zeroth register3197 keeps track of what the whole pattern matches.) */3198const char**regstart = NULL, **regend = NULL;31993200/* If a group that's operated upon by a repetition operator fails to3201 match anything, then the register for its start will need to be3202 restored because it will have been set to wherever in the string we3203 are when we last see its open-group operator. Similarly for a3204 register's end. */3205const char**old_regstart = NULL, **old_regend = NULL;32063207/* The is_active field of reg_info helps us keep track of which (possibly3208 nested) subexpressions we are currently in. The matched_something3209 field of reg_info[reg_num] helps us tell whether or not we have3210 matched any of the pattern so far this time through the reg_num-th3211 subexpression. These two fields get reset each time through any3212 loop their register is in. */3213 register_info_type *reg_info = NULL;32143215/* The following record the register info as found in the above3216 variables when we find a match better than any we've seen before.3217 This happens as we backtrack through the failure points, which in3218 turn happens only if we have not yet matched the entire string. */3219unsigned best_regs_set =false;3220const char**best_regstart = NULL, **best_regend = NULL;32213222/* Logically, this is `best_regend[0]'. But we don't want to have to3223 allocate space for that if we're not allocating space for anything3224 else (see below). Also, we never need info about register 0 for3225 any of the other register vectors, and it seems rather a kludge to3226 treat `best_regend' differently than the rest. So we keep track of3227 the end of the best match so far in a separate variable. We3228 initialize this to NULL so that when we backtrack the first time3229 and need to test it, it's not garbage. */3230const char*match_end = NULL;32313232/* Used when we pop values we don't care about. */3233const char**reg_dummy = NULL;3234 register_info_type *reg_info_dummy = NULL;32353236#ifdef DEBUG3237/* Counts the total number of registers pushed. */3238unsigned num_regs_pushed =0;3239#endif32403241DEBUG_PRINT1("\n\nEntering re_match_2.\n");32423243INIT_FAIL_STACK();32443245/* Do not bother to initialize all the register variables if there are3246 no groups in the pattern, as it takes a fair amount of time. If3247 there are groups, we include space for register 0 (the whole3248 pattern), even though we never use it, since it simplifies the3249 array indexing. We should fix this. */3250if(bufp->re_nsub)3251{3252 regstart =REGEX_TALLOC(num_regs,const char*);3253 regend =REGEX_TALLOC(num_regs,const char*);3254 old_regstart =REGEX_TALLOC(num_regs,const char*);3255 old_regend =REGEX_TALLOC(num_regs,const char*);3256 best_regstart =REGEX_TALLOC(num_regs,const char*);3257 best_regend =REGEX_TALLOC(num_regs,const char*);3258 reg_info =REGEX_TALLOC(num_regs, register_info_type);3259 reg_dummy =REGEX_TALLOC(num_regs,const char*);3260 reg_info_dummy =REGEX_TALLOC(num_regs, register_info_type);32613262if(!(regstart && regend && old_regstart && old_regend && reg_info3263&& best_regstart && best_regend && reg_dummy && reg_info_dummy))3264{3265FREE_VARIABLES();3266return-2;3267}3268}3269#ifdef REGEX_MALLOC3270else3271{3272/* We must initialize all our variables to NULL, so that3273 `FREE_VARIABLES' doesn't try to free them. */3274 regstart = regend = old_regstart = old_regend = best_regstart3275= best_regend = reg_dummy = NULL;3276 reg_info = reg_info_dummy = (register_info_type *) NULL;3277}3278#endif/* REGEX_MALLOC */32793280/* The starting position is bogus. */3281if(pos <0|| pos > size1 + size2)3282{3283FREE_VARIABLES();3284return-1;3285}32863287/* Initialize subexpression text positions to -1 to mark ones that no3288 start_memory/stop_memory has been seen for. Also initialize the3289 register information struct. */3290for(mcnt =1; mcnt < num_regs; mcnt++)3291{3292 regstart[mcnt] = regend[mcnt]3293= old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;32943295REG_MATCH_NULL_STRING_P(reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;3296IS_ACTIVE(reg_info[mcnt]) =0;3297MATCHED_SOMETHING(reg_info[mcnt]) =0;3298EVER_MATCHED_SOMETHING(reg_info[mcnt]) =0;3299}33003301/* We move `string1' into `string2' if the latter's empty -- but not if3302 `string1' is null. */3303if(size2 ==0&& string1 != NULL)3304{3305 string2 = string1;3306 size2 = size1;3307 string1 =0;3308 size1 =0;3309}3310 end1 = string1 + size1;3311 end2 = string2 + size2;33123313/* Compute where to stop matching, within the two strings. */3314if(stop <= size1)3315{3316 end_match_1 = string1 + stop;3317 end_match_2 = string2;3318}3319else3320{3321 end_match_1 = end1;3322 end_match_2 = string2 + stop - size1;3323}33243325/* `p' scans through the pattern as `d' scans through the data.3326 `dend' is the end of the input string that `d' points within. `d'3327 is advanced into the following input string whenever necessary, but3328 this happens before fetching; therefore, at the beginning of the3329 loop, `d' can be pointing at the end of a string, but it cannot3330 equal `string2'. */3331if(size1 >0&& pos <= size1)3332{3333 d = string1 + pos;3334 dend = end_match_1;3335}3336else3337{3338 d = string2 + pos - size1;3339 dend = end_match_2;3340}33413342DEBUG_PRINT1("The compiled pattern is: ");3343DEBUG_PRINT_COMPILED_PATTERN(bufp, p, pend);3344DEBUG_PRINT1("The string to match is: `");3345DEBUG_PRINT_DOUBLE_STRING(d, string1, size1, string2, size2);3346DEBUG_PRINT1("'\n");33473348/* This loops over pattern commands. It exits by returning from the3349 function if the match is complete, or it drops through if the match3350 fails at this starting point in the input data. */3351for(;;)3352{3353DEBUG_PRINT2("\n0x%x: ", p);33543355if(p == pend)3356{/* End of pattern means we might have succeeded. */3357DEBUG_PRINT1("end of pattern ... ");33583359/* If we haven't matched the entire string, and we want the3360 longest match, try backtracking. */3361if(d != end_match_2)3362{3363DEBUG_PRINT1("backtracking.\n");33643365if(!FAIL_STACK_EMPTY())3366{/* More failure points to try. */3367 boolean same_str_p = (FIRST_STRING_P(match_end)3368== MATCHING_IN_FIRST_STRING);33693370/* If exceeds best match so far, save it. */3371if(!best_regs_set3372|| (same_str_p && d > match_end)3373|| (!same_str_p && !MATCHING_IN_FIRST_STRING))3374{3375 best_regs_set =true;3376 match_end = d;33773378DEBUG_PRINT1("\nSAVING match as best so far.\n");33793380for(mcnt =1; mcnt < num_regs; mcnt++)3381{3382 best_regstart[mcnt] = regstart[mcnt];3383 best_regend[mcnt] = regend[mcnt];3384}3385}3386goto fail;3387}33883389/* If no failure points, don't restore garbage. */3390else if(best_regs_set)3391{3392 restore_best_regs:3393/* Restore best match. It may happen that `dend ==3394 end_match_1' while the restored d is in string2.3395 For example, the pattern `x.*y.*z' against the3396 strings `x-' and `y-z-', if the two strings are3397 not consecutive in memory. */3398DEBUG_PRINT1("Restoring best registers.\n");33993400 d = match_end;3401 dend = ((d >= string1 && d <= end1)3402? end_match_1 : end_match_2);34033404for(mcnt =1; mcnt < num_regs; mcnt++)3405{3406 regstart[mcnt] = best_regstart[mcnt];3407 regend[mcnt] = best_regend[mcnt];3408}3409}3410}/* d != end_match_2 */34113412DEBUG_PRINT1("Accepting match.\n");34133414/* If caller wants register contents data back, do it. */3415if(regs && !bufp->no_sub)3416{3417/* Have the register data arrays been allocated? */3418if(bufp->regs_allocated == REGS_UNALLOCATED)3419{/* No. So allocate them with malloc. We need one3420 extra element beyond `num_regs' for the `-1' marker3421 GNU code uses. */3422 regs->num_regs =MAX(RE_NREGS, num_regs +1);3423 regs->start =TALLOC(regs->num_regs, regoff_t);3424 regs->end =TALLOC(regs->num_regs, regoff_t);3425if(regs->start == NULL || regs->end == NULL)3426return-2;3427 bufp->regs_allocated = REGS_REALLOCATE;3428}3429else if(bufp->regs_allocated == REGS_REALLOCATE)3430{/* Yes. If we need more elements than were already3431 allocated, reallocate them. If we need fewer, just3432 leave it alone. */3433if(regs->num_regs < num_regs +1)3434{3435 regs->num_regs = num_regs +1;3436RETALLOC(regs->start, regs->num_regs, regoff_t);3437RETALLOC(regs->end, regs->num_regs, regoff_t);3438if(regs->start == NULL || regs->end == NULL)3439return-2;3440}3441}3442else3443assert(bufp->regs_allocated == REGS_FIXED);34443445/* Convert the pointer data in `regstart' and `regend' to3446 indices. Register zero has to be set differently,3447 since we haven't kept track of any info for it. */3448if(regs->num_regs >0)3449{3450 regs->start[0] = pos;3451 regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string13452: d - string2 + size1);3453}34543455/* Go through the first `min (num_regs, regs->num_regs)'3456 registers, since that is all we initialized. */3457for(mcnt =1; mcnt <MIN(num_regs, regs->num_regs); mcnt++)3458{3459if(REG_UNSET(regstart[mcnt]) ||REG_UNSET(regend[mcnt]))3460 regs->start[mcnt] = regs->end[mcnt] = -1;3461else3462{3463 regs->start[mcnt] =POINTER_TO_OFFSET(regstart[mcnt]);3464 regs->end[mcnt] =POINTER_TO_OFFSET(regend[mcnt]);3465}3466}34673468/* If the regs structure we return has more elements than3469 were in the pattern, set the extra elements to -1. If3470 we (re)allocated the registers, this is the case,3471 because we always allocate enough to have at least one3472 -1 at the end. */3473for(mcnt = num_regs; mcnt < regs->num_regs; mcnt++)3474 regs->start[mcnt] = regs->end[mcnt] = -1;3475}/* regs && !bufp->no_sub */34763477FREE_VARIABLES();3478DEBUG_PRINT4("%ufailure points pushed,%upopped (%uremain).\n",3479 nfailure_points_pushed, nfailure_points_popped,3480 nfailure_points_pushed - nfailure_points_popped);3481DEBUG_PRINT2("%uregisters pushed.\n", num_regs_pushed);34823483 mcnt = d - pos - (MATCHING_IN_FIRST_STRING3484? string13485: string2 - size1);34863487DEBUG_PRINT2("Returning%dfrom re_match_2.\n", mcnt);34883489return mcnt;3490}34913492/* Otherwise match next pattern command. */3493#ifdef SWITCH_ENUM_BUG3494switch((int) ((re_opcode_t) *p++))3495#else3496switch((re_opcode_t) *p++)3497#endif3498{3499/* Ignore these. Used to ignore the n of succeed_n's which3500 currently have n == 0. */3501case no_op:3502DEBUG_PRINT1("EXECUTING no_op.\n");3503break;350435053506/* Match the next n pattern characters exactly. The following3507 byte in the pattern defines n, and the n bytes after that3508 are the characters to match. */3509case exactn:3510 mcnt = *p++;3511DEBUG_PRINT2("EXECUTING exactn%d.\n", mcnt);35123513/* This is written out as an if-else so we don't waste time3514 testing `translate' inside the loop. */3515if(translate)3516{3517do3518{3519PREFETCH();3520if(translate[(unsigned char) *d++] != (char) *p++)3521goto fail;3522}3523while(--mcnt);3524}3525else3526{3527do3528{3529PREFETCH();3530if(*d++ != (char) *p++)goto fail;3531}3532while(--mcnt);3533}3534SET_REGS_MATCHED();3535break;353635373538/* Match any character except possibly a newline or a null. */3539case anychar:3540DEBUG_PRINT1("EXECUTING anychar.\n");35413542PREFETCH();35433544if((!(bufp->syntax & RE_DOT_NEWLINE) &&TRANSLATE(*d) =='\n')3545|| (bufp->syntax & RE_DOT_NOT_NULL &&TRANSLATE(*d) =='\000'))3546goto fail;35473548SET_REGS_MATCHED();3549DEBUG_PRINT2(" Matched `%d'.\n", *d);3550 d++;3551break;355235533554case charset:3555case charset_not:3556{3557registerunsigned char c;3558 boolean not= (re_opcode_t) *(p -1) == charset_not;35593560DEBUG_PRINT2("EXECUTING charset%s.\n",not?"_not":"");35613562PREFETCH();3563 c =TRANSLATE(*d);/* The character to match. */35643565/* Cast to `unsigned' instead of `unsigned char' in case the3566 bit list is a full 32 bytes long. */3567if(c < (unsigned) (*p * BYTEWIDTH)3568&& p[1+ c / BYTEWIDTH] & (1<< (c % BYTEWIDTH)))3569not= !not;35703571 p +=1+ *p;35723573if(!not)goto fail;35743575SET_REGS_MATCHED();3576 d++;3577break;3578}357935803581/* The beginning of a group is represented by start_memory.3582 The arguments are the register number in the next byte, and the3583 number of groups inner to this one in the next. The text3584 matched within the group is recorded (in the internal3585 registers data structure) under the register number. */3586case start_memory:3587DEBUG_PRINT3("EXECUTING start_memory%d(%d):\n", *p, p[1]);35883589/* Find out if this group can match the empty string. */3590 p1 = p;/* To send to group_match_null_string_p. */35913592if(REG_MATCH_NULL_STRING_P(reg_info[*p]) == MATCH_NULL_UNSET_VALUE)3593REG_MATCH_NULL_STRING_P(reg_info[*p])3594=group_match_null_string_p(&p1, pend, reg_info);35953596/* Save the position in the string where we were the last time3597 we were at this open-group operator in case the group is3598 operated upon by a repetition operator, e.g., with `(a*)*b'3599 against `ab'; then we want to ignore where we are now in3600 the string in case this attempt to match fails. */3601 old_regstart[*p] =REG_MATCH_NULL_STRING_P(reg_info[*p])3602?REG_UNSET(regstart[*p]) ? d : regstart[*p]3603: regstart[*p];3604DEBUG_PRINT2(" old_regstart:%d\n",3605POINTER_TO_OFFSET(old_regstart[*p]));36063607 regstart[*p] = d;3608DEBUG_PRINT2(" regstart:%d\n",POINTER_TO_OFFSET(regstart[*p]));36093610IS_ACTIVE(reg_info[*p]) =1;3611MATCHED_SOMETHING(reg_info[*p]) =0;36123613/* This is the new highest active register. */3614 highest_active_reg = *p;36153616/* If nothing was active before, this is the new lowest active3617 register. */3618if(lowest_active_reg == NO_LOWEST_ACTIVE_REG)3619 lowest_active_reg = *p;36203621/* Move past the register number and inner group count. */3622 p +=2;3623break;362436253626/* The stop_memory opcode represents the end of a group. Its3627 arguments are the same as start_memory's: the register3628 number, and the number of inner groups. */3629case stop_memory:3630DEBUG_PRINT3("EXECUTING stop_memory%d(%d):\n", *p, p[1]);36313632/* We need to save the string position the last time we were at3633 this close-group operator in case the group is operated3634 upon by a repetition operator, e.g., with `((a*)*(b*)*)*'3635 against `aba'; then we want to ignore where we are now in3636 the string in case this attempt to match fails. */3637 old_regend[*p] =REG_MATCH_NULL_STRING_P(reg_info[*p])3638?REG_UNSET(regend[*p]) ? d : regend[*p]3639: regend[*p];3640DEBUG_PRINT2(" old_regend:%d\n",3641POINTER_TO_OFFSET(old_regend[*p]));36423643 regend[*p] = d;3644DEBUG_PRINT2(" regend:%d\n",POINTER_TO_OFFSET(regend[*p]));36453646/* This register isn't active anymore. */3647IS_ACTIVE(reg_info[*p]) =0;36483649/* If this was the only register active, nothing is active3650 anymore. */3651if(lowest_active_reg == highest_active_reg)3652{3653 lowest_active_reg = NO_LOWEST_ACTIVE_REG;3654 highest_active_reg = NO_HIGHEST_ACTIVE_REG;3655}3656else3657{/* We must scan for the new highest active register, since3658 it isn't necessarily one less than now: consider3659 (a(b)c(d(e)f)g). When group 3 ends, after the f), the3660 new highest active register is 1. */3661unsigned char r = *p -1;3662while(r >0&& !IS_ACTIVE(reg_info[r]))3663 r--;36643665/* If we end up at register zero, that means that we saved3666 the registers as the result of an `on_failure_jump', not3667 a `start_memory', and we jumped to past the innermost3668 `stop_memory'. For example, in ((.)*) we save3669 registers 1 and 2 as a result of the *, but when we pop3670 back to the second ), we are at the stop_memory 1.3671 Thus, nothing is active. */3672if(r ==0)3673{3674 lowest_active_reg = NO_LOWEST_ACTIVE_REG;3675 highest_active_reg = NO_HIGHEST_ACTIVE_REG;3676}3677else3678 highest_active_reg = r;3679}36803681/* If just failed to match something this time around with a3682 group that's operated on by a repetition operator, try to3683 force exit from the ``loop'', and restore the register3684 information for this group that we had before trying this3685 last match. */3686if((!MATCHED_SOMETHING(reg_info[*p])3687|| (re_opcode_t) p[-3] == start_memory)3688&& (p +2) < pend)3689{3690 boolean is_a_jump_n =false;36913692 p1 = p +2;3693 mcnt =0;3694switch((re_opcode_t) *p1++)3695{3696case jump_n:3697 is_a_jump_n =true;3698case pop_failure_jump:3699case maybe_pop_jump:3700case jump:3701case dummy_failure_jump:3702EXTRACT_NUMBER_AND_INCR(mcnt, p1);3703if(is_a_jump_n)3704 p1 +=2;3705break;37063707default:3708/* do nothing */;3709}3710 p1 += mcnt;37113712/* If the next operation is a jump backwards in the pattern3713 to an on_failure_jump right before the start_memory3714 corresponding to this stop_memory, exit from the loop3715 by forcing a failure after pushing on the stack the3716 on_failure_jump's jump in the pattern, and d. */3717if(mcnt <0&& (re_opcode_t) *p1 == on_failure_jump3718&& (re_opcode_t) p1[3] == start_memory && p1[4] == *p)3719{3720/* If this group ever matched anything, then restore3721 what its registers were before trying this last3722 failed match, e.g., with `(a*)*b' against `ab' for3723 regstart[1], and, e.g., with `((a*)*(b*)*)*'3724 against `aba' for regend[3].37253726 Also restore the registers for inner groups for,3727 e.g., `((a*)(b*))*' against `aba' (register 3 would3728 otherwise get trashed). */37293730if(EVER_MATCHED_SOMETHING(reg_info[*p]))3731{3732unsigned r;37333734EVER_MATCHED_SOMETHING(reg_info[*p]) =0;37353736/* Restore this and inner groups' (if any) registers. */3737for(r = *p; r < *p + *(p +1); r++)3738{3739 regstart[r] = old_regstart[r];37403741/* xx why this test? */3742if((int) old_regend[r] >= (int) regstart[r])3743 regend[r] = old_regend[r];3744}3745}3746 p1++;3747EXTRACT_NUMBER_AND_INCR(mcnt, p1);3748PUSH_FAILURE_POINT(p1 + mcnt, d, -2);37493750goto fail;3751}3752}37533754/* Move past the register number and the inner group count. */3755 p +=2;3756break;375737583759/* \<digit> has been turned into a `duplicate' command which is3760 followed by the numeric value of <digit> as the register number. */3761case duplicate:3762{3763registerconst char*d2, *dend2;3764int regno = *p++;/* Get which register to match against. */3765DEBUG_PRINT2("EXECUTING duplicate%d.\n", regno);37663767/* Can't back reference a group which we've never matched. */3768if(REG_UNSET(regstart[regno]) ||REG_UNSET(regend[regno]))3769goto fail;37703771/* Where in input to try to start matching. */3772 d2 = regstart[regno];37733774/* Where to stop matching; if both the place to start and3775 the place to stop matching are in the same string, then3776 set to the place to stop, otherwise, for now have to use3777 the end of the first string. */37783779 dend2 = ((FIRST_STRING_P(regstart[regno])3780==FIRST_STRING_P(regend[regno]))3781? regend[regno] : end_match_1);3782for(;;)3783{3784/* If necessary, advance to next segment in register3785 contents. */3786while(d2 == dend2)3787{3788if(dend2 == end_match_2)break;3789if(dend2 == regend[regno])break;37903791/* End of string1 => advance to string2. */3792 d2 = string2;3793 dend2 = regend[regno];3794}3795/* At end of register contents => success */3796if(d2 == dend2)break;37973798/* If necessary, advance to next segment in data. */3799PREFETCH();38003801/* How many characters left in this segment to match. */3802 mcnt = dend - d;38033804/* Want how many consecutive characters we can match in3805 one shot, so, if necessary, adjust the count. */3806if(mcnt > dend2 - d2)3807 mcnt = dend2 - d2;38083809/* Compare that many; failure if mismatch, else move3810 past them. */3811if(translate3812?bcmp_translate(d, d2, mcnt, translate)3813:bcmp(d, d2, mcnt))3814goto fail;3815 d += mcnt, d2 += mcnt;3816}3817}3818break;381938203821/* begline matches the empty string at the beginning of the string3822 (unless `not_bol' is set in `bufp'), and, if3823 `newline_anchor' is set, after newlines. */3824case begline:3825DEBUG_PRINT1("EXECUTING begline.\n");38263827if(AT_STRINGS_BEG(d))3828{3829if(!bufp->not_bol)break;3830}3831else if(d[-1] =='\n'&& bufp->newline_anchor)3832{3833break;3834}3835/* In all other cases, we fail. */3836goto fail;383738383839/* endline is the dual of begline. */3840case endline:3841DEBUG_PRINT1("EXECUTING endline.\n");38423843if(AT_STRINGS_END(d))3844{3845if(!bufp->not_eol)break;3846}38473848/* We have to ``prefetch'' the next character. */3849else if((d == end1 ? *string2 : *d) =='\n'3850&& bufp->newline_anchor)3851{3852break;3853}3854goto fail;385538563857/* Match at the very beginning of the data. */3858case begbuf:3859DEBUG_PRINT1("EXECUTING begbuf.\n");3860if(AT_STRINGS_BEG(d))3861break;3862goto fail;386338643865/* Match at the very end of the data. */3866case endbuf:3867DEBUG_PRINT1("EXECUTING endbuf.\n");3868if(AT_STRINGS_END(d))3869break;3870goto fail;387138723873/* on_failure_keep_string_jump is used to optimize `.*\n'. It3874 pushes NULL as the value for the string on the stack. Then3875 `pop_failure_point' will keep the current value for the3876 string, instead of restoring it. To see why, consider3877 matching `foo\nbar' against `.*\n'. The .* matches the foo;3878 then the . fails against the \n. But the next thing we want3879 to do is match the \n against the \n; if we restored the3880 string value, we would be back at the foo.38813882 Because this is used only in specific cases, we don't need to3883 check all the things that `on_failure_jump' does, to make3884 sure the right things get saved on the stack. Hence we don't3885 share its code. The only reason to push anything on the3886 stack at all is that otherwise we would have to change3887 `anychar's code to do something besides goto fail in this3888 case; that seems worse than this. */3889case on_failure_keep_string_jump:3890DEBUG_PRINT1("EXECUTING on_failure_keep_string_jump");38913892EXTRACT_NUMBER_AND_INCR(mcnt, p);3893DEBUG_PRINT3("%d(to 0x%x):\n", mcnt, p + mcnt);38943895PUSH_FAILURE_POINT(p + mcnt, NULL, -2);3896break;389738983899/* Uses of on_failure_jump:39003901 Each alternative starts with an on_failure_jump that points3902 to the beginning of the next alternative. Each alternative3903 except the last ends with a jump that in effect jumps past3904 the rest of the alternatives. (They really jump to the3905 ending jump of the following alternative, because tensioning3906 these jumps is a hassle.)39073908 Repeats start with an on_failure_jump that points past both3909 the repetition text and either the following jump or3910 pop_failure_jump back to this on_failure_jump. */3911case on_failure_jump:3912 on_failure:3913DEBUG_PRINT1("EXECUTING on_failure_jump");39143915EXTRACT_NUMBER_AND_INCR(mcnt, p);3916DEBUG_PRINT3("%d(to 0x%x)", mcnt, p + mcnt);39173918/* If this on_failure_jump comes right before a group (i.e.,3919 the original * applied to a group), save the information3920 for that group and all inner ones, so that if we fail back3921 to this point, the group's information will be correct.3922 For example, in \(a*\)*\1, we need the preceding group,3923 and in \(\(a*\)b*\)\2, we need the inner group. */39243925/* We can't use `p' to check ahead because we push3926 a failure point to `p + mcnt' after we do this. */3927 p1 = p;39283929/* We need to skip no_op's before we look for the3930 start_memory in case this on_failure_jump is happening as3931 the result of a completed succeed_n, as in \(a\)\{1,3\}b\13932 against aba. */3933while(p1 < pend && (re_opcode_t) *p1 == no_op)3934 p1++;39353936if(p1 < pend && (re_opcode_t) *p1 == start_memory)3937{3938/* We have a new highest active register now. This will3939 get reset at the start_memory we are about to get to,3940 but we will have saved all the registers relevant to3941 this repetition op, as described above. */3942 highest_active_reg = *(p1 +1) + *(p1 +2);3943if(lowest_active_reg == NO_LOWEST_ACTIVE_REG)3944 lowest_active_reg = *(p1 +1);3945}39463947DEBUG_PRINT1(":\n");3948PUSH_FAILURE_POINT(p + mcnt, d, -2);3949break;395039513952/* A smart repeat ends with `maybe_pop_jump'.3953 We change it to either `pop_failure_jump' or `jump'. */3954case maybe_pop_jump:3955EXTRACT_NUMBER_AND_INCR(mcnt, p);3956DEBUG_PRINT2("EXECUTING maybe_pop_jump%d.\n", mcnt);3957{3958registerunsigned char*p2 = p;39593960/* Compare the beginning of the repeat with what in the3961 pattern follows its end. If we can establish that there3962 is nothing that they would both match, i.e., that we3963 would have to backtrack because of (as in, e.g., `a*a')3964 then we can change to pop_failure_jump, because we'll3965 never have to backtrack.39663967 This is not true in the case of alternatives: in3968 `(a|ab)*' we do need to backtrack to the `ab' alternative3969 (e.g., if the string was `ab'). But instead of trying to3970 detect that here, the alternative has put on a dummy3971 failure point which is what we will end up popping. */39723973/* Skip over open/close-group commands. */3974while(p2 +2< pend3975&& ((re_opcode_t) *p2 == stop_memory3976|| (re_opcode_t) *p2 == start_memory))3977 p2 +=3;/* Skip over args, too. */39783979/* If we're at the end of the pattern, we can change. */3980if(p2 == pend)3981{3982/* Consider what happens when matching ":\(.*\)"3983 against ":/". I don't really understand this code3984 yet. */3985 p[-3] = (unsigned char) pop_failure_jump;3986 DEBUG_PRINT13987(" End of pattern: change to `pop_failure_jump'.\n");3988}39893990else if((re_opcode_t) *p2 == exactn3991|| (bufp->newline_anchor && (re_opcode_t) *p2 == endline))3992{3993registerunsigned char c3994= *p2 == (unsigned char) endline ?'\n': p2[2];3995 p1 = p + mcnt;39963997/* p1[0] ... p1[2] are the `on_failure_jump' corresponding3998 to the `maybe_finalize_jump' of this case. Examine what3999 follows. */4000if((re_opcode_t) p1[3] == exactn && p1[5] != c)4001{4002 p[-3] = (unsigned char) pop_failure_jump;4003DEBUG_PRINT3("%c!=%c=> pop_failure_jump.\n",4004 c, p1[5]);4005}40064007else if((re_opcode_t) p1[3] == charset4008|| (re_opcode_t) p1[3] == charset_not)4009{4010intnot= (re_opcode_t) p1[3] == charset_not;40114012if(c < (unsigned char) (p1[4] * BYTEWIDTH)4013&& p1[5+ c / BYTEWIDTH] & (1<< (c % BYTEWIDTH)))4014not= !not;40154016/* `not' is equal to 1 if c would match, which means4017 that we can't change to pop_failure_jump. */4018if(!not)4019{4020 p[-3] = (unsigned char) pop_failure_jump;4021DEBUG_PRINT1(" No match => pop_failure_jump.\n");4022}4023}4024}4025}4026 p -=2;/* Point at relative address again. */4027if((re_opcode_t) p[-1] != pop_failure_jump)4028{4029 p[-1] = (unsigned char) jump;4030DEBUG_PRINT1(" Match => jump.\n");4031goto unconditional_jump;4032}4033/* Note fall through. */403440354036/* The end of a simple repeat has a pop_failure_jump back to4037 its matching on_failure_jump, where the latter will push a4038 failure point. The pop_failure_jump takes off failure4039 points put on by this pop_failure_jump's matching4040 on_failure_jump; we got through the pattern to here from the4041 matching on_failure_jump, so didn't fail. */4042case pop_failure_jump:4043{4044/* We need to pass separate storage for the lowest and4045 highest registers, even though we don't care about the4046 actual values. Otherwise, we will restore only one4047 register from the stack, since lowest will == highest in4048 `pop_failure_point'. */4049unsigned dummy_low_reg, dummy_high_reg;4050unsigned char*pdummy;4051const char*sdummy;40524053DEBUG_PRINT1("EXECUTING pop_failure_jump.\n");4054POP_FAILURE_POINT(sdummy, pdummy,4055 dummy_low_reg, dummy_high_reg,4056 reg_dummy, reg_dummy, reg_info_dummy);4057}4058/* Note fall through. */405940604061/* Unconditionally jump (without popping any failure points). */4062case jump:4063 unconditional_jump:4064EXTRACT_NUMBER_AND_INCR(mcnt, p);/* Get the amount to jump. */4065DEBUG_PRINT2("EXECUTING jump%d", mcnt);4066 p += mcnt;/* Do the jump. */4067DEBUG_PRINT2("(to 0x%x).\n", p);4068break;406940704071/* We need this opcode so we can detect where alternatives end4072 in `group_match_null_string_p' et al. */4073case jump_past_alt:4074DEBUG_PRINT1("EXECUTING jump_past_alt.\n");4075goto unconditional_jump;407640774078/* Normally, the on_failure_jump pushes a failure point, which4079 then gets popped at pop_failure_jump. We will end up at4080 pop_failure_jump, also, and with a pattern of, say, `a+', we4081 are skipping over the on_failure_jump, so we have to push4082 something meaningless for pop_failure_jump to pop. */4083case dummy_failure_jump:4084DEBUG_PRINT1("EXECUTING dummy_failure_jump.\n");4085/* It doesn't matter what we push for the string here. What4086 the code at `fail' tests is the value for the pattern. */4087PUSH_FAILURE_POINT(0,0, -2);4088goto unconditional_jump;408940904091/* At the end of an alternative, we need to push a dummy failure4092 point in case we are followed by a `pop_failure_jump', because4093 we don't want the failure point for the alternative to be4094 popped. For example, matching `(a|ab)*' against `aab'4095 requires that we match the `ab' alternative. */4096case push_dummy_failure:4097DEBUG_PRINT1("EXECUTING push_dummy_failure.\n");4098/* See comments just above at `dummy_failure_jump' about the4099 two zeroes. */4100PUSH_FAILURE_POINT(0,0, -2);4101break;41024103/* Have to succeed matching what follows at least n times.4104 After that, handle like `on_failure_jump'. */4105case succeed_n:4106EXTRACT_NUMBER(mcnt, p +2);4107DEBUG_PRINT2("EXECUTING succeed_n%d.\n", mcnt);41084109assert(mcnt >=0);4110/* Originally, this is how many times we HAVE to succeed. */4111if(mcnt >0)4112{4113 mcnt--;4114 p +=2;4115STORE_NUMBER_AND_INCR(p, mcnt);4116DEBUG_PRINT3(" Setting 0x%xto%d.\n", p, mcnt);4117}4118else if(mcnt ==0)4119{4120DEBUG_PRINT2(" Setting two bytes from 0x%xto no_op.\n", p+2);4121 p[2] = (unsigned char) no_op;4122 p[3] = (unsigned char) no_op;4123goto on_failure;4124}4125break;41264127case jump_n:4128EXTRACT_NUMBER(mcnt, p +2);4129DEBUG_PRINT2("EXECUTING jump_n%d.\n", mcnt);41304131/* Originally, this is how many times we CAN jump. */4132if(mcnt)4133{4134 mcnt--;4135STORE_NUMBER(p +2, mcnt);4136goto unconditional_jump;4137}4138/* If don't have to jump any more, skip over the rest of command. */4139else4140 p +=4;4141break;41424143case set_number_at:4144{4145DEBUG_PRINT1("EXECUTING set_number_at.\n");41464147EXTRACT_NUMBER_AND_INCR(mcnt, p);4148 p1 = p + mcnt;4149EXTRACT_NUMBER_AND_INCR(mcnt, p);4150DEBUG_PRINT3(" Setting 0x%xto%d.\n", p1, mcnt);4151STORE_NUMBER(p1, mcnt);4152break;4153}41544155case wordbound:4156DEBUG_PRINT1("EXECUTING wordbound.\n");4157if(AT_WORD_BOUNDARY(d))4158break;4159goto fail;41604161case notwordbound:4162DEBUG_PRINT1("EXECUTING notwordbound.\n");4163if(AT_WORD_BOUNDARY(d))4164goto fail;4165break;41664167case wordbeg:4168DEBUG_PRINT1("EXECUTING wordbeg.\n");4169if(WORDCHAR_P(d) && (AT_STRINGS_BEG(d) || !WORDCHAR_P(d -1)))4170break;4171goto fail;41724173case wordend:4174DEBUG_PRINT1("EXECUTING wordend.\n");4175if(!AT_STRINGS_BEG(d) &&WORDCHAR_P(d -1)4176&& (!WORDCHAR_P(d) ||AT_STRINGS_END(d)))4177break;4178goto fail;41794180#ifdef emacs4181#ifdef emacs194182case before_dot:4183DEBUG_PRINT1("EXECUTING before_dot.\n");4184if(PTR_CHAR_POS((unsigned char*) d) >= point)4185goto fail;4186break;41874188case at_dot:4189DEBUG_PRINT1("EXECUTING at_dot.\n");4190if(PTR_CHAR_POS((unsigned char*) d) != point)4191goto fail;4192break;41934194case after_dot:4195DEBUG_PRINT1("EXECUTING after_dot.\n");4196if(PTR_CHAR_POS((unsigned char*) d) <= point)4197goto fail;4198break;4199#else/* not emacs19 */4200case at_dot:4201DEBUG_PRINT1("EXECUTING at_dot.\n");4202if(PTR_CHAR_POS((unsigned char*) d) +1!= point)4203goto fail;4204break;4205#endif/* not emacs19 */42064207case syntaxspec:4208DEBUG_PRINT2("EXECUTING syntaxspec%d.\n", mcnt);4209 mcnt = *p++;4210goto matchsyntax;42114212case wordchar:4213DEBUG_PRINT1("EXECUTING Emacs wordchar.\n");4214 mcnt = (int) Sword;4215 matchsyntax:4216PREFETCH();4217if(SYNTAX(*d++) != (enum syntaxcode) mcnt)4218goto fail;4219SET_REGS_MATCHED();4220break;42214222case notsyntaxspec:4223DEBUG_PRINT2("EXECUTING notsyntaxspec%d.\n", mcnt);4224 mcnt = *p++;4225goto matchnotsyntax;42264227case notwordchar:4228DEBUG_PRINT1("EXECUTING Emacs notwordchar.\n");4229 mcnt = (int) Sword;4230 matchnotsyntax:4231PREFETCH();4232if(SYNTAX(*d++) == (enum syntaxcode) mcnt)4233goto fail;4234SET_REGS_MATCHED();4235break;42364237#else/* not emacs */4238case wordchar:4239DEBUG_PRINT1("EXECUTING non-Emacs wordchar.\n");4240PREFETCH();4241if(!WORDCHAR_P(d))4242goto fail;4243SET_REGS_MATCHED();4244 d++;4245break;42464247case notwordchar:4248DEBUG_PRINT1("EXECUTING non-Emacs notwordchar.\n");4249PREFETCH();4250if(WORDCHAR_P(d))4251goto fail;4252SET_REGS_MATCHED();4253 d++;4254break;4255#endif/* not emacs */42564257default:4258abort();4259}4260continue;/* Successfully executed one pattern command; keep going. */426142624263/* We goto here if a matching operation fails. */4264 fail:4265if(!FAIL_STACK_EMPTY())4266{/* A restart point is known. Restore to that state. */4267DEBUG_PRINT1("\nFAIL:\n");4268POP_FAILURE_POINT(d, p,4269 lowest_active_reg, highest_active_reg,4270 regstart, regend, reg_info);42714272/* If this failure point is a dummy, try the next one. */4273if(!p)4274goto fail;42754276/* If we failed to the end of the pattern, don't examine *p. */4277assert(p <= pend);4278if(p < pend)4279{4280 boolean is_a_jump_n =false;42814282/* If failed to a backwards jump that's part of a repetition4283 loop, need to pop this failure point and use the next one. */4284switch((re_opcode_t) *p)4285{4286case jump_n:4287 is_a_jump_n =true;4288case maybe_pop_jump:4289case pop_failure_jump:4290case jump:4291 p1 = p +1;4292EXTRACT_NUMBER_AND_INCR(mcnt, p1);4293 p1 += mcnt;42944295if((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)4296|| (!is_a_jump_n4297&& (re_opcode_t) *p1 == on_failure_jump))4298goto fail;4299break;4300default:4301/* do nothing */;4302}4303}43044305if(d >= string1 && d <= end1)4306 dend = end_match_1;4307}4308else4309break;/* Matching at this starting point really fails. */4310}/* for (;;) */43114312if(best_regs_set)4313goto restore_best_regs;43144315FREE_VARIABLES();43164317return-1;/* Failure to match. */4318}/* re_match_2 */4319\f4320/* Subroutine definitions for re_match_2. */432143224323/* We are passed P pointing to a register number after a start_memory.43244325 Return true if the pattern up to the corresponding stop_memory can4326 match the empty string, and false otherwise.43274328 If we find the matching stop_memory, sets P to point to one past its number.4329 Otherwise, sets P to an undefined byte less than or equal to END.43304331 We don't handle duplicates properly (yet). */43324333static boolean4334group_match_null_string_p(p, end, reg_info)4335unsigned char**p, *end;4336 register_info_type *reg_info;4337{4338int mcnt;4339/* Point to after the args to the start_memory. */4340unsigned char*p1 = *p +2;43414342while(p1 < end)4343{4344/* Skip over opcodes that can match nothing, and return true or4345 false, as appropriate, when we get to one that can't, or to the4346 matching stop_memory. */43474348switch((re_opcode_t) *p1)4349{4350/* Could be either a loop or a series of alternatives. */4351case on_failure_jump:4352 p1++;4353EXTRACT_NUMBER_AND_INCR(mcnt, p1);43544355/* If the next operation is not a jump backwards in the4356 pattern. */43574358if(mcnt >=0)4359{4360/* Go through the on_failure_jumps of the alternatives,4361 seeing if any of the alternatives cannot match nothing.4362 The last alternative starts with only a jump,4363 whereas the rest start with on_failure_jump and end4364 with a jump, e.g., here is the pattern for `a|b|c':43654366 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/64367 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/34368 /exactn/1/c43694370 So, we have to first go through the first (n-1)4371 alternatives and then deal with the last one separately. */437243734374/* Deal with the first (n-1) alternatives, which start4375 with an on_failure_jump (see above) that jumps to right4376 past a jump_past_alt. */43774378while((re_opcode_t) p1[mcnt-3] == jump_past_alt)4379{4380/* `mcnt' holds how many bytes long the alternative4381 is, including the ending `jump_past_alt' and4382 its number. */43834384if(!alt_match_null_string_p(p1, p1 + mcnt -3,4385 reg_info))4386return false;43874388/* Move to right after this alternative, including the4389 jump_past_alt. */4390 p1 += mcnt;43914392/* Break if it's the beginning of an n-th alternative4393 that doesn't begin with an on_failure_jump. */4394if((re_opcode_t) *p1 != on_failure_jump)4395break;43964397/* Still have to check that it's not an n-th4398 alternative that starts with an on_failure_jump. */4399 p1++;4400EXTRACT_NUMBER_AND_INCR(mcnt, p1);4401if((re_opcode_t) p1[mcnt-3] != jump_past_alt)4402{4403/* Get to the beginning of the n-th alternative. */4404 p1 -=3;4405break;4406}4407}44084409/* Deal with the last alternative: go back and get number4410 of the `jump_past_alt' just before it. `mcnt' contains4411 the length of the alternative. */4412EXTRACT_NUMBER(mcnt, p1 -2);44134414if(!alt_match_null_string_p(p1, p1 + mcnt, reg_info))4415return false;44164417 p1 += mcnt;/* Get past the n-th alternative. */4418}/* if mcnt > 0 */4419break;442044214422case stop_memory:4423assert(p1[1] == **p);4424*p = p1 +2;4425return true;442644274428default:4429if(!common_op_match_null_string_p(&p1, end, reg_info))4430return false;4431}4432}/* while p1 < end */44334434return false;4435}/* group_match_null_string_p */443644374438/* Similar to group_match_null_string_p, but doesn't deal with alternatives:4439 It expects P to be the first byte of a single alternative and END one4440 byte past the last. The alternative can contain groups. */44414442static boolean4443alt_match_null_string_p(p, end, reg_info)4444unsigned char*p, *end;4445 register_info_type *reg_info;4446{4447int mcnt;4448unsigned char*p1 = p;44494450while(p1 < end)4451{4452/* Skip over opcodes that can match nothing, and break when we get4453 to one that can't. */44544455switch((re_opcode_t) *p1)4456{4457/* It's a loop. */4458case on_failure_jump:4459 p1++;4460EXTRACT_NUMBER_AND_INCR(mcnt, p1);4461 p1 += mcnt;4462break;44634464default:4465if(!common_op_match_null_string_p(&p1, end, reg_info))4466return false;4467}4468}/* while p1 < end */44694470return true;4471}/* alt_match_null_string_p */447244734474/* Deals with the ops common to group_match_null_string_p and4475 alt_match_null_string_p.44764477 Sets P to one after the op and its arguments, if any. */44784479static boolean4480common_op_match_null_string_p(p, end, reg_info)4481unsigned char**p, *end;4482 register_info_type *reg_info;4483{4484int mcnt;4485 boolean ret;4486int reg_no;4487unsigned char*p1 = *p;44884489switch((re_opcode_t) *p1++)4490{4491case no_op:4492case begline:4493case endline:4494case begbuf:4495case endbuf:4496case wordbeg:4497case wordend:4498case wordbound:4499case notwordbound:4500#ifdef emacs4501case before_dot:4502case at_dot:4503case after_dot:4504#endif4505break;45064507case start_memory:4508 reg_no = *p1;4509assert(reg_no >0&& reg_no <= MAX_REGNUM);4510 ret =group_match_null_string_p(&p1, end, reg_info);45114512/* Have to set this here in case we're checking a group which4513 contains a group and a back reference to it. */45144515if(REG_MATCH_NULL_STRING_P(reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)4516REG_MATCH_NULL_STRING_P(reg_info[reg_no]) = ret;45174518if(!ret)4519return false;4520break;45214522/* If this is an optimized succeed_n for zero times, make the jump. */4523case jump:4524EXTRACT_NUMBER_AND_INCR(mcnt, p1);4525if(mcnt >=0)4526 p1 += mcnt;4527else4528return false;4529break;45304531case succeed_n:4532/* Get to the number of times to succeed. */4533 p1 +=2;4534EXTRACT_NUMBER_AND_INCR(mcnt, p1);45354536if(mcnt ==0)4537{4538 p1 -=4;4539EXTRACT_NUMBER_AND_INCR(mcnt, p1);4540 p1 += mcnt;4541}4542else4543return false;4544break;45454546case duplicate:4547if(!REG_MATCH_NULL_STRING_P(reg_info[*p1]))4548return false;4549break;45504551case set_number_at:4552 p1 +=4;45534554default:4555/* All other opcodes mean we cannot match the empty string. */4556return false;4557}45584559*p = p1;4560return true;4561}/* common_op_match_null_string_p */456245634564/* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN4565 bytes; nonzero otherwise. */45664567static int4568bcmp_translate(4569unsigned char*s1,4570unsigned char*s2,4571int len,4572char*translate4573)4574{4575registerunsigned char*p1 = s1, *p2 = s2;4576while(len)4577{4578if(translate[*p1++] != translate[*p2++])return1;4579 len--;4580}4581return0;4582}4583\f4584/* Entry points for GNU code. */45854586/* re_compile_pattern is the GNU regular expression compiler: it4587 compiles PATTERN (of length SIZE) and puts the result in BUFP.4588 Returns 0 if the pattern was valid, otherwise an error string.45894590 Assumes the `allocated' (and perhaps `buffer') and `translate' fields4591 are set in BUFP on entry.45924593 We call regex_compile to do the actual compilation. */45944595const char*4596re_compile_pattern(pattern, length, bufp)4597const char*pattern;4598int length;4599struct re_pattern_buffer *bufp;4600{4601 reg_errcode_t ret;46024603/* GNU code is written to assume at least RE_NREGS registers will be set4604 (and at least one extra will be -1). */4605 bufp->regs_allocated = REGS_UNALLOCATED;46064607/* And GNU code determines whether or not to get register information4608 by passing null for the REGS argument to re_match, etc., not by4609 setting no_sub. */4610 bufp->no_sub =0;46114612/* Match anchors at newline. */4613 bufp->newline_anchor =1;46144615 ret =regex_compile(pattern, length, re_syntax_options, bufp);46164617return re_error_msg[(int) ret];4618}4619\f4620/* Entry points compatible with 4.2 BSD regex library. We don't define4621 them if this is an Emacs or POSIX compilation. */46224623#if !defined (emacs) && !defined (_POSIX_SOURCE)46244625/* BSD has one and only one pattern buffer. */4626static struct re_pattern_buffer re_comp_buf;46274628char*4629re_comp(s)4630const char*s;4631{4632 reg_errcode_t ret;46334634if(!s)4635{4636if(!re_comp_buf.buffer)4637return"No previous regular expression";4638return0;4639}46404641if(!re_comp_buf.buffer)4642{4643 re_comp_buf.buffer = (unsigned char*)malloc(200);4644if(re_comp_buf.buffer == NULL)4645return"Memory exhausted";4646 re_comp_buf.allocated =200;46474648 re_comp_buf.fastmap = (char*)malloc(1<< BYTEWIDTH);4649if(re_comp_buf.fastmap == NULL)4650return"Memory exhausted";4651}46524653/* Since `re_exec' always passes NULL for the `regs' argument, we4654 don't need to initialize the pattern buffer fields which affect it. */46554656/* Match anchors at newlines. */4657 re_comp_buf.newline_anchor =1;46584659 ret =regex_compile(s,strlen(s), re_syntax_options, &re_comp_buf);46604661/* Yes, we're discarding `const' here. */4662return(char*) re_error_msg[(int) ret];4663}466446654666int4667re_exec(s)4668const char*s;4669{4670const int len =strlen(s);4671return46720<=re_search(&re_comp_buf, s, len,0, len, (struct re_registers *)0);4673}4674#endif/* not emacs and not _POSIX_SOURCE */4675\f4676/* POSIX.2 functions. Don't define these for Emacs. */46774678#ifndef emacs46794680/* regcomp takes a regular expression as a string and compiles it.46814682 PREG is a regex_t *. We do not expect any fields to be initialized,4683 since POSIX says we shouldn't. Thus, we set46844685 `buffer' to the compiled pattern;4686 `used' to the length of the compiled pattern;4687 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the4688 REG_EXTENDED bit in CFLAGS is set; otherwise, to4689 RE_SYNTAX_POSIX_BASIC;4690 `newline_anchor' to REG_NEWLINE being set in CFLAGS;4691 `fastmap' and `fastmap_accurate' to zero;4692 `re_nsub' to the number of subexpressions in PATTERN.46934694 PATTERN is the address of the pattern string.46954696 CFLAGS is a series of bits which affect compilation.46974698 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we4699 use POSIX basic syntax.47004701 If REG_NEWLINE is set, then . and [^...] don't match newline.4702 Also, regexec will try a match beginning after every newline.47034704 If REG_ICASE is set, then we considers upper- and lowercase4705 versions of letters to be equivalent when matching.47064707 If REG_NOSUB is set, then when PREG is passed to regexec, that4708 routine will report only success or failure, and nothing about the4709 registers.47104711 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for4712 the return codes and their meanings.) */47134714int4715regcomp(preg, pattern, cflags)4716 regex_t *preg;4717const char*pattern;4718int cflags;4719{4720 reg_errcode_t ret;4721unsigned syntax4722= (cflags & REG_EXTENDED) ?4723 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;47244725/* regex_compile will allocate the space for the compiled pattern. */4726 preg->buffer =0;4727 preg->allocated =0;47284729/* Don't bother to use a fastmap when searching. This simplifies the4730 REG_NEWLINE case: if we used a fastmap, we'd have to put all the4731 characters after newlines into the fastmap. This way, we just try4732 every character. */4733 preg->fastmap =0;47344735if(cflags & REG_ICASE)4736{4737unsigned i;47384739 preg->translate = (char*)malloc(CHAR_SET_SIZE);4740if(preg->translate == NULL)4741return(int) REG_ESPACE;47424743/* Map uppercase characters to corresponding lowercase ones. */4744for(i =0; i < CHAR_SET_SIZE; i++)4745 preg->translate[i] =ISUPPER(i) ?tolower(i) : i;4746}4747else4748 preg->translate = NULL;47494750/* If REG_NEWLINE is set, newlines are treated differently. */4751if(cflags & REG_NEWLINE)4752{/* REG_NEWLINE implies neither . nor [^...] match newline. */4753 syntax &= ~RE_DOT_NEWLINE;4754 syntax |= RE_HAT_LISTS_NOT_NEWLINE;4755/* It also changes the matching behavior. */4756 preg->newline_anchor =1;4757}4758else4759 preg->newline_anchor =0;47604761 preg->no_sub = !!(cflags & REG_NOSUB);47624763/* POSIX says a null character in the pattern terminates it, so we4764 can use strlen here in compiling the pattern. */4765 ret =regex_compile(pattern,strlen(pattern), syntax, preg);47664767/* POSIX doesn't distinguish between an unmatched open-group and an4768 unmatched close-group: both are REG_EPAREN. */4769if(ret == REG_ERPAREN) ret = REG_EPAREN;47704771return(int) ret;4772}477347744775/* regexec searches for a given pattern, specified by PREG, in the4776 string STRING.47774778 If NMATCH is zero or REG_NOSUB was set in the cflags argument to4779 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at4780 least NMATCH elements, and we set them to the offsets of the4781 corresponding matched substrings.47824783 EFLAGS specifies `execution flags' which affect matching: if4784 REG_NOTBOL is set, then ^ does not match at the beginning of the4785 string; if REG_NOTEOL is set, then $ does not match at the end.47864787 We return 0 if we find a match and REG_NOMATCH if not. */47884789int4790regexec(preg, string, nmatch, pmatch, eflags)4791const regex_t *preg;4792const char*string;4793size_t nmatch;4794 regmatch_t pmatch[];4795int eflags;4796{4797int ret;4798struct re_registers regs;4799 regex_t private_preg;4800int len =strlen(string);4801 boolean want_reg_info = !preg->no_sub && nmatch >0;48024803 private_preg = *preg;48044805 private_preg.not_bol = !!(eflags & REG_NOTBOL);4806 private_preg.not_eol = !!(eflags & REG_NOTEOL);48074808/* The user has told us exactly how many registers to return4809 information about, via `nmatch'. We have to pass that on to the4810 matching routines. */4811 private_preg.regs_allocated = REGS_FIXED;48124813if(want_reg_info)4814{4815 regs.num_regs = nmatch;4816 regs.start =TALLOC(nmatch, regoff_t);4817 regs.end =TALLOC(nmatch, regoff_t);4818if(regs.start == NULL || regs.end == NULL)4819return(int) REG_NOMATCH;4820}48214822/* Perform the searching operation. */4823 ret =re_search(&private_preg, string, len,4824/* start: */0,/* range: */ len,4825 want_reg_info ? ®s : (struct re_registers *)0);48264827/* Copy the register information to the POSIX structure. */4828if(want_reg_info)4829{4830if(ret >=0)4831{4832unsigned r;48334834for(r =0; r < nmatch; r++)4835{4836 pmatch[r].rm_so = regs.start[r];4837 pmatch[r].rm_eo = regs.end[r];4838}4839}48404841/* If we needed the temporary register info, free the space now. */4842free(regs.start);4843free(regs.end);4844}48454846/* We want zero return to mean success, unlike `re_search'. */4847return ret >=0? (int) REG_NOERROR : (int) REG_NOMATCH;4848}484948504851/* Returns a message corresponding to an error code, ERRCODE, returned4852 from either regcomp or regexec. We don't use PREG here. */48534854size_t4855regerror(int errcode,const regex_t *preg,4856char*errbuf,size_t errbuf_size)4857{4858const char*msg;4859size_t msg_size;48604861if(errcode <04862|| errcode >= (sizeof(re_error_msg) /sizeof(re_error_msg[0])))4863/* Only error codes returned by the rest of the code should be passed4864 to this routine. If we are given anything else, or if other regex4865 code generates an invalid error code, then the program has a bug.4866 Dump core so we can fix it. */4867abort();48684869 msg = re_error_msg[errcode];48704871/* POSIX doesn't require that we do anything in this case, but why4872 not be nice. */4873if(! msg)4874 msg ="Success";48754876 msg_size =strlen(msg) +1;/* Includes the null. */48774878if(errbuf_size !=0)4879{4880if(msg_size > errbuf_size)4881{4882strncpy(errbuf, msg, errbuf_size -1);4883 errbuf[errbuf_size -1] =0;4884}4885else4886strcpy(errbuf, msg);4887}48884889return msg_size;4890}489148924893/* Free dynamically allocated space used by PREG. */48944895void4896regfree(preg)4897 regex_t *preg;4898{4899if(preg->buffer != NULL)4900free(preg->buffer);4901 preg->buffer = NULL;49024903 preg->allocated =0;4904 preg->used =0;49054906if(preg->fastmap != NULL)4907free(preg->fastmap);4908 preg->fastmap = NULL;4909 preg->fastmap_accurate =0;49104911if(preg->translate != NULL)4912free(preg->translate);4913 preg->translate = NULL;4914}49154916#endif/* not emacs */4917\f4918/*4919Local variables:4920make-backup-files: t4921version-control: t4922trim-versions-without-asking: nil4923End:4924*/