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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
|
/*
* Small POSIX-only regex engine.
*
* Copyright (c) 2009 Marko Kreen
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Simple recursive matcher, only features are small size
* and POSIX compatibility.
*
* ERE syntax: . * ^ $ [] [[:cname:]] () {} | + ?
* BRE syntax: . * ^ $ [] [[:cname:]] \(\) \{\} \1-9
*
* With REG_RELAXED_SYNTAX, following common escapes will be available:
* \b\B\d\D\s\S\w\W BRE: \| ERE: \1-9
*
* With REG_RELAXED_MATCHING it returns the first match found after applying
* leftmost-longest to all elements. It skips the combinatorics to turn it
* into guaranteed-longest match.
*
* Skipped POSIX features:
* - collation classes: [[. .]]
* - equivalence classes: [[= =]]
* - char ranges by locale order: [a-z] (byte order will be used)
* - multi-byte chars: UTF-8
*/
#include <usual/regex.h>
#ifndef USE_SYSTEM_REGEX
#include <usual/mempool.h>
#include <usual/ctype.h>
#include <string.h>
#include <stdio.h>
#undef STRICT
/* either dynamic or static decision */
#define STRICT (ctx->strict)
/* how many regmatch_t can be reported */
#define MAX_GROUPS 128
/* max count we want to store, means 'infinite' for simple atoms */
#define MAX_COUNT 0x7fff
/* max count for simple atoms: char, any or class */
#define SIMPLE_MAXCNT(op) (((op)->maxcnt == MAX_COUNT) ? 0x7FFFFFFF : (op)->maxcnt)
#define is_word(c) (isalnum(c) || (c) == '_')
struct Op;
struct ExecCtx;
struct GMatch;
/* Operation type */
enum OpType {
/* ops that take count */
OP_CHAR,
OP_ANY,
OP_CLASS,
OP_GROUP,
OP_BREF,
/* ops that dont take count */
OP_BOL,
OP_EOL,
OP_WCHANGE,
OP_NWCHANGE,
OP_GMATCH,
OP_FULLMATCH,
};
#define NONCOUNT_OPS_START OP_BOL
/* regex_t->internal */
struct RegexInt {
struct Op *root;
struct Op *glist;
struct MemPool *pool;
int flags;
};
/* match function and its setter */
typedef int (*matcher_f)(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm);
static void set_op_type(struct Op *op, enum OpType op_type);
/* List of tokens to be AND-ed together */
struct AndList {
struct AndList *next;
struct Op *op_list;
};
/* extra data for group Op */
struct GroupData {
struct Op *parent; /* parent group or NULL for first group */
struct AndList *or_list;/* alternative AndLists */
struct Op *glist_prev; /* prev group Op */
bool has_refs; /* if bref references it */
};
/* char class data */
struct ClassData {
uint32_t bitmap[256 / 32];
};
/* operation data */
struct Op {
struct Op *next;
matcher_f matcher;
uint16_t mincnt;
uint16_t maxcnt;
uint8_t type;
union {
uint8_t grp_no; /* OP_GROUP: group nr, 0-toplevel */
char lit; /* OP_CHAR */
uint8_t bref; /* OP_BREF */
};
union {
struct ClassData cdata;
struct GroupData gdata;
};
};
#define OP_BASE (offsetof(struct Op, cdata))
/*
* Operations on ClassData
*/
static bool class_isset(const struct ClassData *cd, unsigned char c)
{
return cd->bitmap[c / 32] & (1 << (c % 32));
}
static void class_set(struct ClassData *cd, unsigned char c)
{
cd->bitmap[c / 32] |= (1 << (c % 32));
}
static void class_negate(struct ClassData *cd)
{
int i;
class_set(cd, 0);
for (i = 0; i < 256/32; i++) cd->bitmap[i] ^= -1;
}
/*
* Parsing code
*/
/* top-level context */
struct ParseCtx {
regex_t *rx;
struct RegexInt *rxi;
struct Op *last_group;
struct AndList *last_andlist;
struct Op *last_elem; /* last op in current OR branch */
bool gotcnt; /* count was attached to last op */
bool strict; /* strict syntax */
};
static struct AndList *new_andlist(struct ParseCtx *ctx, struct Op *g)
{
struct AndList *al = mempool_alloc(&ctx->rxi->pool, sizeof(*al));
if (!al)
return NULL;
if (ctx->last_andlist) {
ctx->last_andlist->next = al;
} else {
g->gdata.or_list = al;
}
ctx->last_andlist = al;
return al;
}
static struct Op *new_op(struct ParseCtx *ctx, enum OpType t, int extra)
{
struct Op *op = mempool_alloc(&ctx->rxi->pool, OP_BASE + extra);
if (!op)
return NULL;
set_op_type(op, t);
op->mincnt = op->maxcnt = 1;
ctx->gotcnt = false;
/* append */
if (ctx->last_elem) {
ctx->last_elem->next = op;
} else if (ctx->last_andlist) {
ctx->last_andlist->op_list = op;
} else if (ctx->last_group) {
struct AndList *alist;
alist = new_andlist(ctx, ctx->last_group);
if (!alist)
return NULL;
alist->op_list = op;
}
ctx->last_elem = op;
if (t == OP_GROUP) {
struct Op *parent = ctx->last_group;
int gno = ++ctx->rx->re_nsub;
op->grp_no = gno;
op->gdata.parent = parent;
op->gdata.glist_prev = ctx->rxi->glist;
ctx->rxi->glist = op;
ctx->last_group = op;
ctx->last_andlist = NULL;
ctx->last_elem = NULL;
if (!ctx->rxi->root)
ctx->rxi->root = op;
}
return op;
}
static int op_char(struct ParseCtx *ctx, unsigned c)
{
struct Op *op = new_op(ctx, OP_CHAR, 0);
if (!op)
return REG_ESPACE;
op->lit = c;
if ((ctx->rxi->flags & REG_ICASE) && isalpha(c))
op->lit = tolower(c);
return 0;
}
static int op_bref(struct ParseCtx *ctx, unsigned c)
{
struct Op *g, *op;
op = new_op(ctx, OP_BREF, 0);
if (!op)
return REG_ESPACE;
op->bref = c - '0';
/* check if valid ref */
for (g = ctx->last_group; g; g = g->gdata.parent) {
if (g->grp_no == op->bref)
return REG_ESUBREG;
}
/* tag the group as referenced */
for (g = ctx->rxi->glist; g; g = g->gdata.glist_prev) {
if (g->grp_no == op->bref) {
g->gdata.has_refs = true;
return 0;
}
}
return REG_ESUBREG;
}
static int op_simple(struct ParseCtx *ctx, enum OpType t)
{
struct Op *op = new_op(ctx, t, 0);
if (!op)
return REG_ESPACE;
return 0;
}
static int op_count_simple(struct ParseCtx *ctx, int min, int max)
{
struct Op *op = ctx->last_elem;
if (!op || ctx->gotcnt)
return REG_BADRPT;
if (op->type >= NONCOUNT_OPS_START)
return REG_BADRPT;
ctx->gotcnt = true;
op->mincnt = min;
op->maxcnt = max;
return 0;
}
static int op_count_full(struct ParseCtx *ctx, const char **re)
{
unsigned a, b;
char *end = (char *)*re;
bool ext = ctx->rxi->flags & REG_EXTENDED;
int err;
/* apply sanity check */
err = op_count_simple(ctx, 1, 1);
if (err)
return err;
/* parse */
a = b = strtoul(*re, &end, 10);
if (end == *re)
return REG_EBRACE;
if (*end == ',') {
*re = end + 1;
end = (char*)*re;
b = strtoul(*re, &end, 10);
if (end == *re)
b = MAX_COUNT;
}
if (a > b || b > MAX_COUNT || a >= MAX_COUNT)
return REG_BADBR;
/* check for correct termination */
if (ext && end[0] == '}') {
*re = end + 1;
goto done;
} else if (!ext && end[0] == '\\' && end[1] == '}') {
*re = end + 2;
goto done;
}
/* bad fmt, decide between error codes */
return strchr(end, '}') ? REG_BADBR : REG_EBRACE;
done:
ctx->last_elem->mincnt = a;
ctx->last_elem->maxcnt = b;
return 0;
}
static int op_gstart(struct ParseCtx *ctx)
{
struct Op *op;
op = new_op(ctx, OP_GROUP, sizeof(struct GroupData));
if (!op)
return REG_ESPACE;
if (op->grp_no >= MAX_GROUPS)
return REG_BADPAT;
return 0;
}
static int finish_branch(struct ParseCtx *ctx)
{
int err;
/* disallow empty OR fragments, but not empty groups */
if (!ctx->last_elem && ctx->last_andlist && STRICT)
return REG_BADPAT;
if (ctx->last_group->gdata.parent)
err = op_simple(ctx, OP_GMATCH);
else
err = op_simple(ctx, OP_FULLMATCH);
if (err)
return err;
ctx->last_elem = NULL;
return 0;
}
static int op_gend(struct ParseCtx *ctx)
{
struct Op *op = ctx->last_group;
struct AndList *alist;
int err;
if (!op)
return REG_EPAREN;
err = finish_branch(ctx);
if (err)
return err;
ctx->last_group = op->gdata.parent;
ctx->last_elem = op;
/* recover previous andlist... */
alist = ctx->last_group->gdata.or_list;
while (alist && alist->next)
alist = alist->next;
ctx->last_andlist = alist;
return 0;
}
static int op_or(struct ParseCtx *ctx)
{
struct Op *gop = ctx->last_group;
struct AndList *alist;
int err;
/* disallow empty OR branches */
if (!ctx->last_elem && STRICT)
return REG_BADPAT;
/* start new branch */
err = finish_branch(ctx);
if (err)
return err;
alist = new_andlist(ctx, gop);
if (!alist)
return REG_ESPACE;
ctx->last_andlist = alist;
ctx->last_elem = NULL;
return 0;
}
/*
* Parse bracketed classes.
*/
static void add_char(struct ClassData *cd, unsigned char c, bool icase)
{
if (icase && isalpha(c)) {
class_set(cd, tolower(c));
class_set(cd, toupper(c));
} else {
class_set(cd, c);
}
}
struct NamedClass {
const char name[7];
unsigned char name_len;
int (*check_func)(int c);
};
static const struct NamedClass ctype_list[] = {
{ "alnum", 5, isalnum },
{ "alpha", 5, isalpha },
{ "blank", 5, isblank },
{ "cntrl", 5, iscntrl },
{ "digit", 5, isdigit },
{ "graph", 5, isgraph },
{ "lower", 5, islower },
{ "print", 5, isprint },
{ "punct", 5, ispunct },
{ "space", 5, isspace },
{ "upper", 5, isupper },
{ "xdigit", 6, isxdigit },
};
static int fill_class(struct ClassData *cd, const char *name, const char **s_p, bool icase)
{
unsigned c;
const struct NamedClass *cc = ctype_list;
for (c = 0; c < ARRAY_NELEM(ctype_list); c++) {
cc = ctype_list + c;
if (strncmp(name, cc->name, cc->name_len) != 0)
continue;
name += cc->name_len;
if (name[0] == ':' && name[1] == ']')
goto found;
break;
}
return *name ? REG_ECTYPE : REG_EBRACK;
found:
/* fill map */
for (c = 1; c < 256; c++) {
if (cc->check_func(c))
add_char(cd, c, icase);
}
*s_p = name + 2;
return 0;
}
#define MAP_RANGE 0x7FFF0001
#define MAP_END 0x7FFF0002
#define MAP_OTHER 0x7FFF0003
static int get_map_token(struct ParseCtx *ctx, const char **s_p, unsigned *dst_p,
bool start, struct ClassData *cd, bool icase)
{
const char *s = *s_p;
unsigned res;
if (*s == '-') {
if (start || s[1] == ']')
res = '-';
else
res = MAP_RANGE;
s += 1;
} else if (*s == ']' && !start) {
res = MAP_END;
s++;
} else if (*s == '[' && (s[1] == '.' || s[1] == ':' || s[1] == '=')) {
if (s[1] == ':') {
s += 2;
*dst_p = MAP_OTHER;
return fill_class(cd, s, s_p, icase);
}
return REG_BADPAT;
} else {
res = (unsigned char)*s++;
}
*dst_p = res;
*s_p = s;
return 0;
}
static int op_class(struct ParseCtx *ctx, const char **re)
{
const char *s = *re;
struct ClassData *cd;
struct Op *op;
bool not = false, icase = ctx->rxi->flags & REG_ICASE;
const char *start;
unsigned tk, c, prevtk = 0;
bool is_range = false;
int err;
if (*s == '^') {
s++;
not = true;
}
start = s;
op = new_op(ctx, OP_CLASS, sizeof(struct ClassData));
if (!op)
return REG_ESPACE;
cd = &op->cdata;
if (not && (ctx->rxi->flags & REG_NEWLINE))
class_set(cd, '\n');
while (*s) {
err = get_map_token(ctx, &s, &tk, s == start, cd, icase);
if (err)
return err;
if (tk == MAP_END) {
if (prevtk)
add_char(cd, prevtk, icase);
goto done;
} else if (tk == MAP_OTHER) {
if (is_range)
return REG_ERANGE;
if (prevtk)
add_char(cd, prevtk, icase);
prevtk = 0;
} else if (tk == MAP_RANGE) {
if (!prevtk)
return REG_ERANGE;
is_range = true;
} else if (is_range) {
if (tk < prevtk)
return REG_ERANGE;
for (c = prevtk; c <= tk; c++)
add_char(cd, c, icase);
is_range = false;
prevtk = 0;
} else {
if (prevtk)
add_char(cd, prevtk, icase);
prevtk = tk;
}
}
return REG_EBRACK;
done:
*re = s;
if (not) class_negate(cd);
return 0;
}
static int op_class_const(struct ParseCtx *ctx, const char *def)
{
const char *p = def + 1;
return op_class(ctx, &p);
}
/*
* Top-level syntax
*/
static int parse_relaxed_escapes(struct ParseCtx *ctx, char c)
{
if (STRICT)
return REG_BADPAT;
switch (c) {
case 'b': return op_simple(ctx, OP_WCHANGE);
case 'B': return op_simple(ctx, OP_NWCHANGE);
case 'w': return op_class_const(ctx, "[_[:alnum:]]");
case 'W': return op_class_const(ctx, "[^_[:alnum:]]");
case 'd': return op_class_const(ctx, "[[:digit:]]");
case 'D': return op_class_const(ctx, "[^[:digit:]]");
case 's': return op_class_const(ctx, "[[:space:]]");
case 'S': return op_class_const(ctx, "[^[:space:]]");
}
return REG_BADPAT;
}
static int parse_posix_ext(struct ParseCtx *ctx, const char *re)
{
int err = 0;
unsigned c;
int glevel = 0;
loop:
if (err)
return err;
c = *re++;
switch (c) {
case 0:
return (glevel == 0) ? 0 : REG_EPAREN;
case '(':
glevel++;
err = op_gstart(ctx);
break;
case ')':
if (glevel > 0) {
glevel--;
err = op_gend(ctx);
} else {
err = op_char(ctx, c); /* POSIX bug */
}
break;
case '|':
err = op_or(ctx);
break;
case '*':
err = op_count_simple(ctx, 0, MAX_COUNT);
break;
case '?':
err = op_count_simple(ctx, 0, 1);
break;
case '+':
err = op_count_simple(ctx, 1, MAX_COUNT);
break;
case '[':
err = op_class(ctx, &re);
break;
case '{':
err = op_count_full(ctx, &re);
break;
case '.':
err = op_simple(ctx, OP_ANY);
break;
case '^':
err = op_simple(ctx, OP_BOL);
break;
case '$':
err = op_simple(ctx, OP_EOL);
break;
case '\\':
goto escaped;
default:
err = op_char(ctx, c);
}
goto loop;
escaped:
c = *re++;
if (c == 0)
err = REG_EESCAPE;
else if (c >= '0' && c <= '9')
err = STRICT ? REG_BADPAT : op_bref(ctx, c);
else if (isalpha(c))
err = parse_relaxed_escapes(ctx, c);
else
err = op_char(ctx, c);
goto loop;
}
static int parse_posix_basic(struct ParseCtx *ctx, const char *re)
{
int err = 0;
unsigned c;
int glevel = 0;
loop:
if (err)
return err;
c = *re++;
switch (c) {
case 0:
return (glevel == 0) ? 0 : REG_EPAREN;
case '*':
if (ctx->last_elem && ctx->last_elem->type != OP_BOL)
err = op_count_simple(ctx, 0, MAX_COUNT);
else
err = op_char(ctx, '*');
break;
case '.':
err = op_simple(ctx, OP_ANY);
break;
case '[':
err = op_class(ctx, &re);
break;
case '^':
if (!ctx->last_elem)
err = op_simple(ctx, OP_BOL);
else
err = op_char(ctx, c);
break;
case '$':
if (!*re || (re[0] == '\\' && re[1] == ')'))
err = op_simple(ctx, OP_EOL);
else
err = op_char(ctx, c);
break;
case '\\':
goto escaped;
default:
err = op_char(ctx, c);
}
goto loop;
escaped:
c = *re++;
switch (c) {
case 0:
return REG_EESCAPE;
case '(':
glevel++;
err = op_gstart(ctx);
break;
case ')':
glevel--;
if (glevel < 0)
return REG_EPAREN;
err = op_gend(ctx);
break;
case '{':
err = op_count_full(ctx, &re);
break;
case '.': case '^': case '$': case '*':
case '[': case ']': case '\\':
err = op_char(ctx, c);
break;
case '1': case '2': case '3': case '4': case '5':
case '6': case '7': case '8': case '9':
err = op_bref(ctx, c);
break;
case '|':
err = STRICT ? REG_BADPAT : op_or(ctx);
break;
default:
err = parse_relaxed_escapes(ctx, c);
}
goto loop;
}
/*
* Public compiling API.
*/
int regcomp(regex_t *rx, const char *re, int flags)
{
struct ParseCtx ctx;
struct RegexInt *rxi;
int err;
struct MemPool *pool = NULL;
/* do it first, to allow regfree() */
memset(rx, 0, sizeof(*rx));
if (flags & ~(REG_EXTENDED | REG_ICASE | REG_NOSUB | REG_NEWLINE | REG_RELAXED))
return REG_BADPAT;
if (!*re)
return REG_BADPAT;
rxi = mempool_alloc(&pool, sizeof(*rxi));
if (!rxi)
return REG_ESPACE;
rx->internal = rxi;
rxi->pool = pool;
/* initialize rx and local context */
memset(&ctx, 0, sizeof(ctx));
ctx.rx = rx;
ctx.rxi = rxi;
ctx.strict = !(flags & REG_RELAXED_SYNTAX);
rxi->flags = flags;
/* setup group #0 */
rx->re_nsub = -1;
err = op_gstart(&ctx);
if (err)
goto failed;
/* launch proper parser */
if (flags & REG_EXTENDED)
err = parse_posix_ext(&ctx, re);
else
err = parse_posix_basic(&ctx, re);
/* finalize group #0 */
if (!err)
err = finish_branch(&ctx);
/* relax if details are not needed */
if (flags & REG_NOSUB) {
rxi->flags |= REG_RELAXED_MATCHING;
rx->re_nsub = 0;
}
failed:
/* clean up if problems */
if (err)
regfree(rx);
return err;
}
/*
* Matching code
*/
/* historical best match */
struct HMatch {
const char *hist_start;
const char *hist_end;
int rep_len; /* if repeated seq, full len thus far */
};
/* per-group-match context */
struct GMatch {
struct GMatch *parent; /* parent group */
const struct Op *owner; /* Op for this group */
const char *start; /* match start */
const char *end; /* match end, NULL if no match */
struct GMatch *prevgm; /* older stack entry */
struct HMatch hm_next; /* best match for following stack entry */
int count; /* match nr in repeated seq */
};
/* top context */
struct ExecCtx {
const regex_t *rx;
const struct RegexInt *rxi;
const char *str_start;
regmatch_t *pmatch;
int nmatch;
int flags;
bool strict;
const char *last_endpos;
struct HMatch hm_first[MAX_GROUPS];
struct GMatch *gm_stack[MAX_GROUPS];
struct GMatch *gm_cache[MAX_GROUPS];
};
static void push_gm(struct ExecCtx *ctx, struct GMatch *gm)
{
int gno = gm->owner->grp_no;
gm->prevgm = ctx->gm_stack[gno];
ctx->gm_stack[gno] = gm;
}
static void pop_gm(struct ExecCtx *ctx, struct GMatch *gm)
{
int gno = gm->owner->grp_no;
ctx->gm_stack[gno] = gm->prevgm;
}
static inline int do_match(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
return op->matcher(ctx, op, str, gm);
}
static int scan_next(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm, int curcnt, int alen)
{
int err = REG_NOMATCH;
bool gotmatch = false;
if (curcnt == op->mincnt)
return do_match(ctx, op->next, str, gm);
for (; curcnt >= op->mincnt; curcnt--) {
err = do_match(ctx, op->next, str, gm);
if (STRICT && err == 0)
gotmatch = true;
else if (err != REG_NOMATCH)
break;
str -= alen;
}
if (err == REG_NOMATCH && gotmatch)
err = 0;
return err;
}
static int match_char(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
bool icase = (ctx->flags & REG_ICASE);
int c, i, maxcnt = SIMPLE_MAXCNT(op);
for (i = 0; (i < maxcnt) && str[i]; i++) {
c = icase ? tolower((unsigned char)str[i]) : str[i];
if (c != op->lit)
break;
}
return scan_next(ctx, op, str + i, gm, i, 1);
}
static int match_any(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
bool nl = (ctx->flags & REG_NEWLINE);
int i, maxcnt = SIMPLE_MAXCNT(op);
for (i = 0; (i < maxcnt) && str[i]; i++) {
if (nl && str[i] == '\n')
break;
}
return scan_next(ctx, op, str + i, gm, i, 1);
}
static int match_class(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
int i, maxcnt = SIMPLE_MAXCNT(op);
for (i = 0; (i < maxcnt); i++) {
if (!class_isset(&op->cdata, str[i]))
break;
}
return scan_next(ctx, op, str + i, gm, i, 1);
}
static int match_bol(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
if (str == ctx->str_start && !(ctx->flags & REG_NOTBOL))
return do_match(ctx, op->next, str, gm);
else if (str != ctx->str_start && str[-1] == '\n' && (ctx->flags & REG_NEWLINE))
return do_match(ctx, op->next, str, gm);
return REG_NOMATCH;
}
static int match_eol(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
if (*str == '\n' && (ctx->flags & REG_NEWLINE))
return do_match(ctx, op->next, str, gm);
else if (*str == 0 && !(ctx->flags & REG_NOTEOL))
return do_match(ctx, op->next, str, gm);
return REG_NOMATCH;
}
static int match_wchange(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
bool prevw = (str == ctx->str_start) ? false : is_word(str[-1]);
bool curw = is_word(str[0]);
bool ischange = prevw ^ curw;
if ((op->type == OP_WCHANGE) ? ischange : !ischange)
return do_match(ctx, op->next, str, gm);
return REG_NOMATCH;
}
static int match_bref(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
bool icase = ctx->flags & REG_ICASE;
int i;
struct GMatch *bgm = ctx->gm_stack[op->bref];
int blen = (bgm && bgm->end) ? (bgm->end - bgm->start) : -1;
/* handle no-match, zero-len, zero-count */
if (blen < 0 && op->mincnt > 0)
return REG_NOMATCH;
if (blen <= 0 || op->maxcnt == 0)
return do_match(ctx, op->next, str, gm);
/* find max matches */
for (i = 0; (i < op->maxcnt) && *str; i++) {
if (icase && strncasecmp(str, bgm->start, blen) != 0)
break;
else if (!icase && strncmp(str, bgm->start, blen) != 0)
break;
str += blen;
}
return scan_next(ctx, op, str, gm, i, blen);
}
static int match_group(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
int err = REG_NOMATCH;
bool gotmatch = false;
struct GMatch gthis;
/* per-group-match context */
memset(>his, 0, sizeof(gthis));
gthis.owner = op;
gthis.start = str;
gthis.parent = gm;
if (gm && gm->owner == op) {
gthis.parent = gm->parent;
gthis.count = gm->count + 1;
}
gm = >his;
push_gm(ctx, gm);
if (op->maxcnt > 0) {
struct AndList *alist = op->gdata.or_list;
/* check all branches, unless relaxed matching */
while (alist) {
err = do_match(ctx, alist->op_list, str, gm);
if (err == 0 && STRICT) {
gm->end = NULL;
gotmatch = true;
} else if (err != REG_NOMATCH)
break;
alist = alist->next;
}
}
/* is no-match allowed? */
if ((op->mincnt == 0) && (gm->count == 0)
&& (err == REG_NOMATCH || (err == 0 && STRICT))) {
gm->end = NULL;
err = do_match(ctx, op->next, str, gm->parent);
}
pop_gm(ctx, gm);
return gotmatch ? 0 : err;
}
static int match_gend(struct ExecCtx *ctx, const struct Op *f_op, const char *str, struct GMatch *gm)
{
int err = REG_NOMATCH;
const struct Op *op = gm->owner;
bool zeromatch = (str == gm->start);
bool gotmatch = false;
/* ignore follow-up empty matches, unless it has backrefs */
if (zeromatch && gm->count > 0 && gm->count >= op->mincnt && !gm->owner->gdata.has_refs)
return REG_NOMATCH;
/* tag as matched */
gm->end = str;
/* try more repeats, stop if count full or last match was zero-length */
if (gm->count + 1 < op->maxcnt && !zeromatch) {
err = match_group(ctx, op, str, gm);
if (err == 0 && STRICT)
gotmatch = true;
else if (err != REG_NOMATCH)
return err;
}
/* fail if not enough repeats */
if (!zeromatch && gm->count + 1 < op->mincnt)
return err;
/* continue with parent branch */
err = do_match(ctx, op->next, str, gm->parent);
if (err == REG_NOMATCH && gotmatch)
err = 0;
return err;
}
/*
* The juice of POSIX - match weighting.
*/
static int gmatch_hist_cmp(struct ExecCtx *ctx, int gno, struct GMatch *gm, int replen)
{
struct HMatch *hm = (gm->prevgm) ? &gm->prevgm->hm_next : &ctx->hm_first[gno];
int gmlen = (gm->end) ? (gm->end - gm->start) : -1;
int hmlen = (hm->hist_end) ? (hm->hist_end - hm->hist_start) : -1;
int gmreplen = (gmlen >= 0) ? (gmlen + replen) : replen;
int hmreplen = ((hmlen >= 0) ? hmlen : 0) + hm->rep_len;
int gmofs = (gm->end) ? (gm->start - ctx->str_start) : -1;
int hmofs = (hm->hist_start) ? (hm->hist_start - ctx->str_start) : -1;
/* prefer rightmost match, to allow preceding elements match more */
int res = (gmofs - hmofs);
/* prefer longer repeated match */
if (res == 0 && gm->count == 0)
res = (gmreplen - hmreplen);
/* prefer longer single match */
if (res == 0)
res = (gmlen - hmlen);
return res;
}
static int cmp_gmatches(struct ExecCtx *ctx, int gno, struct GMatch *gm, int replen)
{
int cmp = 0, gmlen;
if (gm) {
/* need to compare preceding groups first */
gmlen = gm->end ? gm->end - gm->start : 0;
cmp = cmp_gmatches(ctx, gno, gm->prevgm,
(gm->count == 0) ? 0 : (replen + gmlen));
/* actual comparision */
if (!cmp) cmp = gmatch_hist_cmp(ctx, gno, gm, replen);
}
return cmp;
}
static int gm_resolve_tie(struct ExecCtx *ctx, int gno)
{
struct GMatch *gm = ctx->gm_stack[gno];
if (!gm) /* 0-count match is better than no match */
return ctx->hm_first[gno].hist_start ? -1 : 0;
return cmp_gmatches(ctx, gno, gm, 0);
}
static void fill_history(struct ExecCtx *ctx, int gno)
{
struct HMatch *hm;
int gmlen, rep_len = 0;
struct GMatch *gm = ctx->gm_stack[gno];
while (STRICT && gm) {
hm = (gm->prevgm) ? &gm->prevgm->hm_next : &ctx->hm_first[gno];
hm->hist_start = gm->start;
hm->hist_end = gm->end;
hm->rep_len = rep_len;
gmlen = gm->end ? (gm->end - gm->start) : 0;
rep_len += gmlen;
if (gm->count == 0)
rep_len = 0;
gm = gm->prevgm;
}
}
static void publish_gm(struct ExecCtx *ctx, int gno)
{
struct GMatch *gm = ctx->gm_stack[gno];
regmatch_t *rm = ctx->pmatch + gno;
/* ignore non-matches */
while (gm && !gm->end)
gm = gm->prevgm;
/* require it to be inside reported parent */
if (gm && gm->parent) {
int pno = gm->parent->owner->grp_no;
if (gm->parent != ctx->gm_cache[pno])
gm = NULL;
}
ctx->gm_cache[gno] = gm;
/* publish new match */
if (gm) {
rm->rm_so = gm->start - ctx->str_start;
rm->rm_eo = gm->end - ctx->str_start;
} else {
rm->rm_so = -1;
rm->rm_eo = -1;
}
}
/* compare and publish */
static int got_full_match(struct ExecCtx *ctx, const struct Op *f_op, const char *str, struct GMatch *gm)
{
int gno, cmp;
/* tag group as matched */
gm->end = str;
/* ignore shorter matches */
if (ctx->last_endpos && str < ctx->last_endpos)
return 0;
/* longer or equal length */
if (str > ctx->last_endpos) {
ctx->last_endpos = str;
goto better_match;
} else if (STRICT && ctx->nmatch > 1) {
for (gno = 0; gno < ctx->nmatch; gno++) {
cmp = gm_resolve_tie(ctx, gno);
if (cmp < 0)
break;
if (cmp > 0)
goto better_match;
}
}
return 0;
better_match:
for (gno = 0; gno < ctx->nmatch; gno++) {
publish_gm(ctx, gno);
fill_history(ctx, gno);
}
return 0;
}
/* fill in proper matcher */
static void set_op_type(struct Op *op, enum OpType op_type)
{
static const matcher_f mlist[] = {
match_char, match_any, match_class, match_group, match_bref,
match_bol, match_eol, match_wchange, match_wchange,
match_gend, got_full_match
};
op->matcher = mlist[op_type];
op->type = op_type;
}
/*
* Public matching API
*/
int regexec(const regex_t *rx, const char *str, size_t nmatch, regmatch_t pmatch[], int eflags)
{
int err;
struct ExecCtx ctx;
if (eflags & ~(REG_NOTBOL | REG_NOTEOL))
return REG_BADPAT;
/* init local context */
memset(&ctx, 0, sizeof(ctx));
ctx.pmatch = pmatch;
ctx.nmatch = nmatch;
ctx.str_start = str;
ctx.rx = rx;
ctx.rxi = rx->internal;
ctx.flags = ctx.rxi->flags | eflags;
/* reset pmatch area */
if (!(ctx.flags & REG_NOSUB))
memset(pmatch, -1, nmatch * sizeof(regmatch_t));
/* decide pmatch area that will be used */
if (!pmatch || (ctx.flags & REG_NOSUB))
ctx.nmatch = 0;
else if (nmatch > (size_t)rx->re_nsub + 1)
ctx.nmatch = rx->re_nsub + 1;
ctx.strict = !(ctx.flags & REG_RELAXED_MATCHING) && (ctx.nmatch > 0);
/* execute search */
str--;
do {
str++;
err = do_match(&ctx, ctx.rxi->root, str, NULL);
} while ((err == REG_NOMATCH) && *str);
return err;
}
/*
* Free parse tree
*/
void regfree(regex_t *rx)
{
struct RegexInt *rxi;
if (rx) {
rxi = rx->internal;
if (rxi)
mempool_destroy(&rxi->pool);
memset(rx, 0, sizeof(*rx));
}
}
/*
* Error strings
*/
size_t regerror(int err, const regex_t *rx, char *dst, size_t dstlen)
{
static const char errlist[][9] = {
"NOERROR", /* 0 */
"NOMATCH", /* 1 */
"BADBR", /* 2 */
"BADPAT", /* 3 */
"BADRPT", /* 4 */
"EBRACE", /* 5 */
"EBRACK", /* 6 */
"ECOLLATE", /* 7 */
"ECTYPE", /* 8 */
"EESCAPE", /* 9 */
"EPAREN", /* 10 */
"ERANGE", /* 11 */
"ESPACE", /* 12 */
"ESUBREG", /* 13 */
};
const char *s = "EUNKNOWN";
if ((size_t)err < ARRAY_NELEM(errlist))
s = errlist[err];
return snprintf(dst, dstlen, "%s", s);
}
#endif /* !USE_SYSTEM_REGEX */
|