-
Notifications
You must be signed in to change notification settings - Fork 123
/
jimregexp.c
1917 lines (1747 loc) · 45.1 KB
/
jimregexp.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* vi:se ts=8:
*
* regcomp and regexec -- regsub and regerror are elsewhere
*
* Copyright (c) 1986 by University of Toronto.
* Written by Henry Spencer. Not derived from licensed software.
*
* Permission is granted to anyone to use this software for any
* purpose on any computer system, and to redistribute it freely,
* subject to the following restrictions:
*
* 1. The author is not responsible for the consequences of use of
* this software, no matter how awful, even if they arise
* from defects in it.
*
* 2. The origin of this software must not be misrepresented, either
* by explicit claim or by omission.
*
* 3. Altered versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
*** hoptoad!gnu, on 27 Dec 1986, to add \n as an alternative to |
*** to assist in implementing egrep.
*** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
*** hoptoad!gnu, on 27 Dec 1986, to add \< and \> for word-matching
*** as in BSD grep and ex.
*** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
*** hoptoad!gnu, on 28 Dec 1986, to optimize characters quoted with \.
*** THIS IS AN ALTERED VERSION. It was altered by James A. Woods,
*** ames!jaw, on 19 June 1987, to quash a regcomp() redundancy.
*** THIS IS AN ALTERED VERSION. It was altered by Christopher Seiwald
*** [email protected], on 28 August 1993, for use in jam. Regmagic.h
*** was moved into regexp.h, and the include of regexp.h now uses "'s
*** to avoid conflicting with the system regexp.h. Const, bless its
*** soul, was removed so it can compile everywhere. The declaration
*** of strchr() was in conflict on AIX, so it was removed (as it is
*** happily defined in string.h).
*** THIS IS AN ALTERED VERSION. It was altered by Christopher Seiwald
*** [email protected], on 20 January 2000, to use function prototypes.
*** THIS IS AN ALTERED VERSION. It was altered by Christopher Seiwald
*** [email protected], on 05 November 2002, to const string literals.
*
* THIS IS AN ALTERED VERSION. It was altered by Steve Bennett <[email protected]>
* on 16 October 2010, to remove static state and add better Tcl ARE compatibility.
* This includes counted repetitions, UTF-8 support, character classes,
* shorthand character classes, increased number of parentheses to 100,
* backslash escape sequences. It also removes \n as an alternative to |.
*
* Beware that some of this code is subtly aware of the way operator
* precedence is structured in regular expressions. Serious changes in
* regular-expression syntax might require a total rethink.
*/
#include "jimautoconf.h"
#if defined(JIM_REGEXP)
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "jim.h"
#include "jimregexp.h"
#include "utf8.h"
/* An arbitrary limit, but this seems enough. Must be less than 1000. */
#define REG_MAX_PAREN 100
/*
* Structure for regexp "program". This is essentially a linear encoding
* of a nondeterministic finite-state machine (aka syntax charts or
* "railroad normal form" in parsing technology). Each node is an opcode
* plus a "next" pointer, possibly plus an operand. "Next" pointers of
* all nodes except BRANCH implement concatenation; a "next" pointer with
* a BRANCH on both ends of it is connecting two alternatives. (Here we
* have one of the subtle syntax dependencies: an individual BRANCH (as
* opposed to a collection of them) is never concatenated with anything
* because of operator precedence.) The operand of some types of node is
* a literal string; for others, it is a node leading into a sub-FSM. In
* particular, the operand of a BRANCH node is the first node of the branch.
* (NB this is *not* a tree structure: the tail of the branch connects
* to the thing following the set of BRANCHes.) The opcodes are:
*/
/* definition number opnd? meaning */
#define END 0 /* no End of program. */
#define BOL 1 /* no Match "" at beginning of line. */
#define EOL 2 /* no Match "" at end of line. */
#define ANY 3 /* no Match any one character. */
#define ANYOF 4 /* str Match any character in this string. */
#define ANYBUT 5 /* str Match any character not in this string. */
#define BRANCH 6 /* node Match this alternative, or the next... */
#define BACK 7 /* no Match "", "next" ptr points backward. */
#define EXACTLY 8 /* str Match this string. */
#define NOTHING 9 /* no Match empty string. */
#define REP 10 /* max,min Match this (simple) thing [min,max] times. */
#define REPMIN 11 /* max,min Match this (simple) thing [min,max] times, minimal match. */
#define REPX 12 /* max,min Match this (complex) thing [min,max] times. */
#define REPXMIN 13 /* max,min Match this (complex) thing [min,max] times, minimal match. */
#define BOLX 14 /* no Match "" at beginning of input. */
#define EOLX 15 /* no Match "" at end of input. */
#define WORDA 16 /* no Match "" at wordchar, where prev is nonword */
#define WORDZ 17 /* no Match "" at nonwordchar, where prev is word */
#define OPENNC 1000 /* no Non-capturing parentheses - must be OPEN-1 */
#define OPEN 1001 /* no Mark this point in input as start of #n. */
/* OPEN+1 is number 1, etc. */
/* must not be any other opts between OPEN and CLOSE */
#define CLOSENC 2000 /* no Non-capturing parentheses - must be CLOSE-1 */
#define CLOSE 2001 /* no Analogous to OPEN. */
#define CLOSE_END (CLOSE+REG_MAX_PAREN)
/*
* The first word of the regexp internal "program" is actually this magic
* number; the start node begins in the second word.
*/
#define REG_MAGIC 0xFADED00D
/*
* Opcode notes:
*
* BRANCH The set of branches constituting a single choice are hooked
* together with their "next" pointers, since precedence prevents
* anything being concatenated to any individual branch. The
* "next" pointer of the last BRANCH in a choice points to the
* thing following the whole choice. This is also where the
* final "next" pointer of each individual branch points; each
* branch starts with the operand node of a BRANCH node.
*
* BACK Normal "next" pointers all implicitly point forward; BACK
* exists to make loop structures possible.
*
* REP,REPX Repeated matches ('?', '*', '+' and {min,max}) are implemented
* as either simple repeats (REP) or complex repeats (REPX).
* These opcodes include a "min" and "max" count after the opcode.
* This is followed by a fourth "current count" word that is
* only used by REPX, as it implements a recursive match.
* REPMIN and REPXMIN are identical except they implement minimal repeats.
*
* OPEN,CLOSE ...are numbered at compile time.
*/
/*
* A node is one word of opcode followed by one word of "next" pointer.
* The "next" pointer value is a positive offset from the opcode of the node
* containing it.
* An operand, if any, simply follows the node. (Note that much of the
* code generation knows about this implicit relationship.)
*/
#define OP(preg, p) (preg->program[p])
#define NEXT(preg, p) (preg->program[p + 1])
#define OPERAND(p) ((p) + 2)
/*
* See regmagic.h for one further detail of program structure.
*/
/*
* Utility definitions.
*/
#define FAIL(R,M) { (R)->err = (M); return (M); }
#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?' || (c) == '{')
#define META "^$.[()|?{+*"
/*
* Flags to be passed up and down.
*/
#define HASWIDTH 1 /* Known never to match null string. */
#define SIMPLE 2 /* Simple enough to be STAR/PLUS operand. */
#define SPSTART 4 /* Starts with * or +. */
#define WORST 0 /* Worst case. */
#define MAX_REP_COUNT 1000000
/*
* Forward declarations for regcomp()'s friends.
*/
static int reg(regex_t *preg, int paren /* Parenthesized? */, int *flagp );
static int regpiece(regex_t *preg, int *flagp );
static int regbranch(regex_t *preg, int *flagp );
static int regatom(regex_t *preg, int *flagp );
static int regnode(regex_t *preg, int op );
static int regnext(regex_t *preg, int p );
static void regc(regex_t *preg, int b );
static int reginsert(regex_t *preg, int op, int size, int opnd );
static void regtail(regex_t *preg, int p, int val);
static void regoptail(regex_t *preg, int p, int val );
static int regopsize(regex_t *preg, int p );
static int reg_range_find(const int *string, int c);
static const char *str_find(const char *string, int c, int nocase);
static int prefix_cmp(const int *prog, int proglen, const char *string, int nocase);
/*#define DEBUG*/
#ifdef DEBUG
static int regnarrate = 0;
static void regdump(regex_t *preg);
static const char *regprop( int op );
#endif
/**
* Returns the length of the null-terminated integer sequence.
*/
static int str_int_len(const int *seq)
{
int n = 0;
while (*seq++) {
n++;
}
return n;
}
/*
- regcomp - compile a regular expression into internal code
*
* We can't allocate space until we know how big the compiled form will be,
* but we can't compile it (and thus know how big it is) until we've got a
* place to put the code. So we cheat: we compile it twice, once with code
* generation turned off and size counting turned on, and once "for real".
* This also means that we don't allocate space until we are sure that the
* thing really will compile successfully, and we never have to move the
* code and thus invalidate pointers into it. (Note that it has to be in
* one piece because free() must be able to free it all.)
*
* Beware that the optimization-preparation code in here knows about some
* of the structure of the compiled regexp.
*/
int jim_regcomp(regex_t *preg, const char *exp, int cflags)
{
int scan;
int longest;
unsigned len;
int flags;
#ifdef DEBUG
fprintf(stderr, "Compiling: '%s'\n", exp);
#endif
memset(preg, 0, sizeof(*preg));
if (exp == NULL)
FAIL(preg, REG_ERR_NULL_ARGUMENT);
/* First pass: determine size, legality. */
preg->cflags = cflags;
preg->regparse = exp;
/* Allocate space. */
preg->proglen = (strlen(exp) + 1) * 5;
preg->program = malloc(preg->proglen * sizeof(int));
if (preg->program == NULL)
FAIL(preg, REG_ERR_NOMEM);
/* Note that since we store a magic value as the first item in the program,
* program offsets will never be 0
*/
regc(preg, REG_MAGIC);
if (reg(preg, 0, &flags) == 0) {
return preg->err;
}
/* Small enough for pointer-storage convention? */
if (preg->re_nsub >= REG_MAX_PAREN) /* Probably could be 65535L. */
FAIL(preg,REG_ERR_TOO_BIG);
/* Dig out information for optimizations. */
preg->regstart = 0; /* Worst-case defaults. */
preg->reganch = 0;
preg->regmust = 0;
preg->regmlen = 0;
scan = 1; /* First BRANCH. */
if (OP(preg, regnext(preg, scan)) == END) { /* Only one top-level choice. */
scan = OPERAND(scan);
/* Starting-point info. */
if (OP(preg, scan) == EXACTLY) {
preg->regstart = preg->program[OPERAND(scan)];
}
else if (OP(preg, scan) == BOL)
preg->reganch++;
/*
* If there's something expensive in the r.e., find the
* longest literal string that must appear and make it the
* regmust. Resolve ties in favor of later strings, since
* the regstart check works with the beginning of the r.e.
* and avoiding duplication strengthens checking. Not a
* strong reason, but sufficient in the absence of others.
*/
if (flags&SPSTART) {
longest = 0;
len = 0;
for (; scan != 0; scan = regnext(preg, scan)) {
if (OP(preg, scan) == EXACTLY) {
int plen = str_int_len(preg->program + OPERAND(scan));
if (plen >= len) {
longest = OPERAND(scan);
len = plen;
}
}
}
preg->regmust = longest;
preg->regmlen = len;
}
}
#ifdef DEBUG
regdump(preg);
#endif
return 0;
}
/*
- reg - regular expression, i.e. main body or parenthesized thing
*
* Caller must absorb opening parenthesis.
*
* Combining parenthesis handling with the base level of regular expression
* is a trifle forced, but the need to tie the tails of the branches to what
* follows makes it hard to avoid.
*/
static int reg(regex_t *preg, int paren /* Parenthesized? */, int *flagp )
{
int ret;
int br;
int ender;
int parno = 0;
int flags;
*flagp = HASWIDTH; /* Tentatively. */
/* Make an OPEN node, if parenthesized. */
if (paren) {
if (preg->regparse[0] == '?' && preg->regparse[1] == ':') {
/* non-capturing paren */
preg->regparse += 2;
parno = -1;
}
else {
parno = ++preg->re_nsub;
}
ret = regnode(preg, OPEN+parno);
} else
ret = 0;
/* Pick up the branches, linking them together. */
br = regbranch(preg, &flags);
if (br == 0)
return 0;
if (ret != 0)
regtail(preg, ret, br); /* OPEN -> first. */
else
ret = br;
if (!(flags&HASWIDTH))
*flagp &= ~HASWIDTH;
*flagp |= flags&SPSTART;
while (*preg->regparse == '|') {
preg->regparse++;
br = regbranch(preg, &flags);
if (br == 0)
return 0;
regtail(preg, ret, br); /* BRANCH -> BRANCH. */
if (!(flags&HASWIDTH))
*flagp &= ~HASWIDTH;
*flagp |= flags&SPSTART;
}
/* Make a closing node, and hook it on the end. */
ender = regnode(preg, (paren) ? CLOSE+parno : END);
regtail(preg, ret, ender);
/* Hook the tails of the branches to the closing node. */
for (br = ret; br != 0; br = regnext(preg, br))
regoptail(preg, br, ender);
/* Check for proper termination. */
if (paren && *preg->regparse++ != ')') {
preg->err = REG_ERR_UNMATCHED_PAREN;
return 0;
} else if (!paren && *preg->regparse != '\0') {
if (*preg->regparse == ')') {
preg->err = REG_ERR_UNMATCHED_PAREN;
return 0;
} else {
preg->err = REG_ERR_JUNK_ON_END;
return 0;
}
}
return(ret);
}
/*
- regbranch - one alternative of an | operator
*
* Implements the concatenation operator.
*/
static int regbranch(regex_t *preg, int *flagp )
{
int ret;
int chain;
int latest;
int flags;
*flagp = WORST; /* Tentatively. */
ret = regnode(preg, BRANCH);
chain = 0;
while (*preg->regparse != '\0' && *preg->regparse != ')' &&
*preg->regparse != '|') {
latest = regpiece(preg, &flags);
if (latest == 0)
return 0;
*flagp |= flags&HASWIDTH;
if (chain == 0) {/* First piece. */
*flagp |= flags&SPSTART;
}
else {
regtail(preg, chain, latest);
}
chain = latest;
}
if (chain == 0) /* Loop ran zero times. */
(void) regnode(preg, NOTHING);
return(ret);
}
/*
- regpiece - something followed by possible [*+?]
*
* Note that the branching code sequences used for ? and the general cases
* of * and + are somewhat optimized: they use the same NOTHING node as
* both the endmarker for their branch list and the body of the last branch.
* It might seem that this node could be dispensed with entirely, but the
* endmarker role is not redundant.
*/
static int regpiece(regex_t *preg, int *flagp)
{
int ret;
char op;
int next;
int flags;
int min;
int max;
ret = regatom(preg, &flags);
if (ret == 0)
return 0;
op = *preg->regparse;
if (!ISMULT(op)) {
*flagp = flags;
return(ret);
}
if (!(flags&HASWIDTH) && op != '?') {
preg->err = REG_ERR_OPERAND_COULD_BE_EMPTY;
return 0;
}
/* Handle braces (counted repetition) by expansion */
if (op == '{') {
char *end;
min = strtoul(preg->regparse + 1, &end, 10);
if (end == preg->regparse + 1) {
preg->err = REG_ERR_BAD_COUNT;
return 0;
}
if (*end == '}') {
max = min;
}
else if (*end == '\0') {
preg->err = REG_ERR_UNMATCHED_BRACES;
return 0;
}
else {
preg->regparse = end;
max = strtoul(preg->regparse + 1, &end, 10);
if (*end != '}') {
preg->err = REG_ERR_UNMATCHED_BRACES;
return 0;
}
}
if (end == preg->regparse + 1) {
max = MAX_REP_COUNT;
}
else if (max < min || max >= 100) {
preg->err = REG_ERR_BAD_COUNT;
return 0;
}
if (min >= 100) {
preg->err = REG_ERR_BAD_COUNT;
return 0;
}
preg->regparse = strchr(preg->regparse, '}');
}
else {
min = (op == '+');
max = (op == '?' ? 1 : MAX_REP_COUNT);
}
if (preg->regparse[1] == '?') {
preg->regparse++;
next = reginsert(preg, flags & SIMPLE ? REPMIN : REPXMIN, 5, ret);
}
else {
next = reginsert(preg, flags & SIMPLE ? REP: REPX, 5, ret);
}
preg->program[ret + 2] = max;
preg->program[ret + 3] = min;
preg->program[ret + 4] = 0;
*flagp = (min) ? (WORST|HASWIDTH) : (WORST|SPSTART);
if (!(flags & SIMPLE)) {
int back = regnode(preg, BACK);
regtail(preg, back, ret);
regtail(preg, next, back);
}
preg->regparse++;
if (ISMULT(*preg->regparse)) {
preg->err = REG_ERR_NESTED_COUNT;
return 0;
}
return ret;
}
/**
* Add all characters in the inclusive range between lower and upper.
*
* Handles a swapped range (upper < lower).
*/
static void reg_addrange(regex_t *preg, int lower, int upper)
{
if (lower > upper) {
reg_addrange(preg, upper, lower);
}
/* Add a range as length, start */
regc(preg, upper - lower + 1);
regc(preg, lower);
}
/**
* Add a null-terminated literal string as a set of ranges.
*/
static void reg_addrange_str(regex_t *preg, const char *str)
{
while (*str) {
reg_addrange(preg, *str, *str);
str++;
}
}
/**
* Extracts the next unicode char from utf8.
*
* If 'upper' is set, converts the char to uppercase.
*/
static int reg_utf8_tounicode_case(const char *s, int *uc, int upper)
{
int l = utf8_tounicode(s, uc);
if (upper) {
*uc = utf8_upper(*uc);
}
return l;
}
/**
* Converts a hex digit to decimal.
*
* Returns -1 for an invalid hex digit.
*/
static int hexdigitval(int c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return -1;
}
/**
* Parses up to 'n' hex digits at 's' and stores the result in *uc.
*
* Returns the number of hex digits parsed.
* If there are no hex digits, returns 0 and stores nothing.
*/
static int parse_hex(const char *s, int n, int *uc)
{
int val = 0;
int k;
for (k = 0; k < n; k++) {
int c = hexdigitval(*s++);
if (c == -1) {
break;
}
val = (val << 4) | c;
}
if (k) {
*uc = val;
}
return k;
}
/**
* Call for chars after a backlash to decode the escape sequence.
*
* Stores the result in *ch.
*
* Returns the number of bytes consumed.
*/
static int reg_decode_escape(const char *s, int *ch)
{
int n;
const char *s0 = s;
*ch = *s++;
switch (*ch) {
case 'b': *ch = '\b'; break;
case 'e': *ch = 27; break;
case 'f': *ch = '\f'; break;
case 'n': *ch = '\n'; break;
case 'r': *ch = '\r'; break;
case 't': *ch = '\t'; break;
case 'v': *ch = '\v'; break;
case 'u':
if (*s == '{') {
/* Expect \u{NNNN} */
n = parse_hex(s + 1, 6, ch);
if (n > 0 && s[n + 1] == '}' && *ch >= 0 && *ch <= 0x1fffff) {
s += n + 2;
}
else {
/* Invalid, so just treat as an escaped 'u' */
*ch = 'u';
}
}
else if ((n = parse_hex(s, 4, ch)) > 0) {
s += n;
}
break;
case 'U':
if ((n = parse_hex(s, 8, ch)) > 0) {
s += n;
}
break;
case 'x':
if ((n = parse_hex(s, 2, ch)) > 0) {
s += n;
}
break;
case '\0':
s--;
*ch = '\\';
break;
}
return s - s0;
}
/*
- regatom - the lowest level
*
* Optimization: gobbles an entire sequence of ordinary characters so that
* it can turn them into a single node, which is smaller to store and
* faster to run. Backslashed characters are exceptions, each becoming a
* separate node; the code is simpler that way and it's not worth fixing.
*/
static int regatom(regex_t *preg, int *flagp)
{
int ret;
int flags;
int nocase = (preg->cflags & REG_ICASE);
int ch;
int n = reg_utf8_tounicode_case(preg->regparse, &ch, nocase);
*flagp = WORST; /* Tentatively. */
preg->regparse += n;
switch (ch) {
/* FIXME: these chars only have meaning at beg/end of pat? */
case '^':
ret = regnode(preg, BOL);
break;
case '$':
ret = regnode(preg, EOL);
break;
case '.':
ret = regnode(preg, ANY);
*flagp |= HASWIDTH|SIMPLE;
break;
case '[': {
const char *pattern = preg->regparse;
if (*pattern == '^') { /* Complement of range. */
ret = regnode(preg, ANYBUT);
pattern++;
} else
ret = regnode(preg, ANYOF);
/* Special case. If the first char is ']' or '-', it is part of the set */
if (*pattern == ']' || *pattern == '-') {
reg_addrange(preg, *pattern, *pattern);
pattern++;
}
while (*pattern != ']') {
/* Is this a range? a-z */
int start;
int end;
enum {
CC_ALPHA, CC_ALNUM, CC_SPACE, CC_BLANK, CC_UPPER, CC_LOWER,
CC_DIGIT, CC_XDIGIT, CC_CNTRL, CC_GRAPH, CC_PRINT, CC_PUNCT,
CC_NUM
};
int cc;
if (!*pattern) {
preg->err = REG_ERR_UNMATCHED_BRACKET;
return 0;
}
pattern += reg_utf8_tounicode_case(pattern, &start, nocase);
if (start == '\\') {
/* First check for class shorthand escapes */
switch (*pattern) {
case 's':
pattern++;
cc = CC_SPACE;
goto cc_switch;
case 'd':
pattern++;
cc = CC_DIGIT;
goto cc_switch;
case 'w':
pattern++;
reg_addrange(preg, '_', '_');
cc = CC_ALNUM;
goto cc_switch;
}
pattern += reg_decode_escape(pattern, &start);
if (start == 0) {
preg->err = REG_ERR_NULL_CHAR;
return 0;
}
if (start == '\\' && *pattern == 0) {
preg->err = REG_ERR_INVALID_ESCAPE;
return 0;
}
}
if (pattern[0] == '-' && pattern[1] && pattern[1] != ']') {
/* skip '-' */
pattern += utf8_tounicode(pattern, &end);
pattern += reg_utf8_tounicode_case(pattern, &end, nocase);
if (end == '\\') {
pattern += reg_decode_escape(pattern, &end);
if (end == 0) {
preg->err = REG_ERR_NULL_CHAR;
return 0;
}
if (end == '\\' && *pattern == 0) {
preg->err = REG_ERR_INVALID_ESCAPE;
return 0;
}
}
reg_addrange(preg, start, end);
continue;
}
if (start == '[' && pattern[0] == ':') {
static const char *character_class[] = {
":alpha:", ":alnum:", ":space:", ":blank:", ":upper:", ":lower:",
":digit:", ":xdigit:", ":cntrl:", ":graph:", ":print:", ":punct:",
};
for (cc = 0; cc < CC_NUM; cc++) {
n = strlen(character_class[cc]);
if (strncmp(pattern, character_class[cc], n) == 0) {
if (pattern[n] != ']') {
preg->err = REG_ERR_UNMATCHED_BRACKET;
return 0;
}
/* Found a character class */
pattern += n + 1;
break;
}
}
if (cc != CC_NUM) {
cc_switch:
switch (cc) {
case CC_ALNUM:
reg_addrange(preg, '0', '9');
/* Fall through */
case CC_ALPHA:
if ((preg->cflags & REG_ICASE) == 0) {
reg_addrange(preg, 'a', 'z');
}
reg_addrange(preg, 'A', 'Z');
break;
case CC_SPACE:
reg_addrange_str(preg, " \t\r\n\f\v");
break;
case CC_BLANK:
reg_addrange_str(preg, " \t");
break;
case CC_UPPER:
reg_addrange(preg, 'A', 'Z');
break;
case CC_LOWER:
reg_addrange(preg, 'a', 'z');
break;
case CC_XDIGIT:
reg_addrange(preg, 'a', 'f');
reg_addrange(preg, 'A', 'F');
/* Fall through */
case CC_DIGIT:
reg_addrange(preg, '0', '9');
break;
case CC_CNTRL:
reg_addrange(preg, 0, 31);
reg_addrange(preg, 127, 127);
break;
case CC_PRINT:
reg_addrange(preg, ' ', '~');
break;
case CC_GRAPH:
reg_addrange(preg, '!', '~');
break;
case CC_PUNCT:
reg_addrange(preg, '!', '/');
reg_addrange(preg, ':', '@');
reg_addrange(preg, '[', '`');
reg_addrange(preg, '{', '~');
break;
}
continue;
}
}
/* Not a range, so just add the char */
reg_addrange(preg, start, start);
}
regc(preg, '\0');
if (*pattern) {
pattern++;
}
preg->regparse = pattern;
*flagp |= HASWIDTH|SIMPLE;
}
break;
case '(':
ret = reg(preg, 1, &flags);
if (ret == 0)
return 0;
*flagp |= flags&(HASWIDTH|SPSTART);
break;
case '\0':
case '|':
case ')':
preg->err = REG_ERR_INTERNAL;
return 0; /* Supposed to be caught earlier. */
case '?':
case '+':
case '*':
case '{':
preg->err = REG_ERR_COUNT_FOLLOWS_NOTHING;
return 0;
case '\\':
ch = *preg->regparse++;
switch (ch) {
case '\0':
preg->err = REG_ERR_INVALID_ESCAPE;
return 0;
case 'A':
ret = regnode(preg, BOLX);
break;
case 'Z':
ret = regnode(preg, EOLX);
break;
case '<':
case 'm':
ret = regnode(preg, WORDA);
break;
case '>':
case 'M':
ret = regnode(preg, WORDZ);
break;
case 'd':
case 'D':
ret = regnode(preg, ch == 'd' ? ANYOF : ANYBUT);
reg_addrange(preg, '0', '9');
regc(preg, '\0');
*flagp |= HASWIDTH|SIMPLE;
break;
case 'w':
case 'W':
ret = regnode(preg, ch == 'w' ? ANYOF : ANYBUT);
if ((preg->cflags & REG_ICASE) == 0) {
reg_addrange(preg, 'a', 'z');
}
reg_addrange(preg, 'A', 'Z');
reg_addrange(preg, '0', '9');
reg_addrange(preg, '_', '_');
regc(preg, '\0');
*flagp |= HASWIDTH|SIMPLE;
break;
case 's':
case 'S':
ret = regnode(preg, ch == 's' ? ANYOF : ANYBUT);
reg_addrange_str(preg," \t\r\n\f\v");
regc(preg, '\0');
*flagp |= HASWIDTH|SIMPLE;
break;
/* FIXME: Someday handle \1, \2, ... */
default:
/* Handle general quoted chars in exact-match routine */
/* Back up to include the backslash */
preg->regparse--;
goto de_fault;
}
break;
de_fault:
default: {
/*
* Encode a string of characters to be matched exactly.
*/
int added = 0;
/* Back up to pick up the first char of interest */
preg->regparse -= n;
ret = regnode(preg, EXACTLY);
/* Note that a META operator such as ? or * consumes the
* preceding char.
* Thus we must be careful to look ahead by 2 and add the
* last char as it's own EXACTLY if necessary
*/
/* Until end of string or a META char is reached */
while (*preg->regparse && strchr(META, *preg->regparse) == NULL) {
n = reg_utf8_tounicode_case(preg->regparse, &ch, (preg->cflags & REG_ICASE));
if (ch == '\\' && preg->regparse[n]) {
/* Non-trailing backslash.
* Is this a special escape, or a regular escape?
*/
if (strchr("<>mMwWdDsSAZ", preg->regparse[n])) {
/* A special escape. All done with EXACTLY */
break;
}
/* Decode it. Note that we add the length for the escape
* sequence to the length for the backlash so we can skip
* the entire sequence, or not as required.
*/
n += reg_decode_escape(preg->regparse + n, &ch);
if (ch == 0) {
preg->err = REG_ERR_NULL_CHAR;
return 0;
}
}
/* Now we have one char 'ch' of length 'n'.
* Check to see if the following char is a MULT
*/
if (ISMULT(preg->regparse[n])) {
/* Yes. But do we already have some EXACTLY chars? */
if (added) {
/* Yes, so return what we have and pick up the current char next time around */
break;
}
/* No, so add this single char and finish */
regc(preg, ch);
added++;
preg->regparse += n;
break;
}
/* No, so just add this char normally */
regc(preg, ch);
added++;
preg->regparse += n;
}