-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfa.c
More file actions
4275 lines (3749 loc) · 133 KB
/
dfa.c
File metadata and controls
4275 lines (3749 loc) · 133 KB
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
/* dfa.c - deterministic extended regexp routines for GNU
Copyright (C) 1988, 1998, 2000, 2002, 2004-2005, 2007-2015 Free Software
Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc.,
51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA */
/* Written June, 1988 by Mike Haertel
Modified July, 1988 by Arthur David Olson to assist BMG speedups */
#include <config.h>
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#ifndef VMS
#include <sys/types.h>
#else
#include <stddef.h>
#endif
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#if HAVE_SETLOCALE
#include <locale.h>
#endif
/* Gawk doesn't use Gnulib, so don't assume that setlocale is present. */
#ifndef LC_ALL
# define setlocale(category, locale) NULL
#endif
#define STREQ(a, b) (strcmp (a, b) == 0)
/* ISASCIIDIGIT differs from isdigit, as follows:
- Its arg may be any int or unsigned int; it need not be an unsigned char.
- It's guaranteed to evaluate its argument exactly once.
- It's typically faster.
Posix 1003.2-1992 section 2.5.2.1 page 50 lines 1556-1558 says that
only '0' through '9' are digits. Prefer ISASCIIDIGIT to isdigit unless
it's important to use the locale's definition of "digit" even when the
host does not conform to Posix. */
#define ISASCIIDIGIT(c) ((unsigned) (c) - '0' <= 9)
#include "gettext.h"
#define _(str) gettext (str)
#include <wchar.h>
#include <wctype.h>
#include "xalloc.h"
#if defined(__DJGPP__)
#include "mbsupport.h"
#endif
#include "dfa.h"
#ifdef GAWK
static int
is_blank (int c)
{
return (c == ' ' || c == '\t');
}
#endif /* GAWK */
#ifdef LIBC_IS_BORKED
extern int gawk_mb_cur_max;
#undef MB_CUR_MAX
#define MB_CUR_MAX gawk_mb_cur_max
#undef mbrtowc
#define mbrtowc(a, b, c, d) (-1)
#endif
/* HPUX defines these as macros in sys/param.h. */
#ifdef setbit
# undef setbit
#endif
#ifdef clrbit
# undef clrbit
#endif
/* First integer value that is greater than any character code. */
enum { NOTCHAR = 1 << CHAR_BIT };
/* This represents part of a character class. It must be unsigned and
at least CHARCLASS_WORD_BITS wide. Any excess bits are zero. */
typedef unsigned int charclass_word;
/* The number of bits used in a charclass word. utf8_classes assumes
this is exactly 32. */
enum { CHARCLASS_WORD_BITS = 32 };
/* The maximum useful value of a charclass_word; all used bits are 1. */
#define CHARCLASS_WORD_MASK \
(((charclass_word) 1 << (CHARCLASS_WORD_BITS - 1) << 1) - 1)
/* Number of words required to hold a bit for every character. */
enum
{
CHARCLASS_WORDS = (NOTCHAR + CHARCLASS_WORD_BITS - 1) / CHARCLASS_WORD_BITS
};
/* Sets of unsigned characters are stored as bit vectors in arrays of ints. */
typedef charclass_word charclass[CHARCLASS_WORDS];
/* Convert a possibly-signed character to an unsigned character. This is
a bit safer than casting to unsigned char, since it catches some type
errors that the cast doesn't. */
static unsigned char
to_uchar (char ch)
{
return ch;
}
/* Contexts tell us whether a character is a newline or a word constituent.
Word-constituent characters are those that satisfy iswalnum, plus '_'.
Each character has a single CTX_* value; bitmasks of CTX_* values denote
a particular character class.
A state also stores a context value, which is a bitmask of CTX_* values.
A state's context represents a set of characters that the state's
predecessors must match. For example, a state whose context does not
include CTX_LETTER will never have transitions where the previous
character is a word constituent. A state whose context is CTX_ANY
might have transitions from any character. */
#define CTX_NONE 1
#define CTX_LETTER 2
#define CTX_NEWLINE 4
#define CTX_ANY 7
/* Sometimes characters can only be matched depending on the surrounding
context. Such context decisions depend on what the previous character
was, and the value of the current (lookahead) character. Context
dependent constraints are encoded as 8 bit integers. Each bit that
is set indicates that the constraint succeeds in the corresponding
context.
bit 8-11 - valid contexts when next character is CTX_NEWLINE
bit 4-7 - valid contexts when next character is CTX_LETTER
bit 0-3 - valid contexts when next character is CTX_NONE
The macro SUCCEEDS_IN_CONTEXT determines whether a given constraint
succeeds in a particular context. Prev is a bitmask of possible
context values for the previous character, curr is the (single-bit)
context value for the lookahead character. */
#define NEWLINE_CONSTRAINT(constraint) (((constraint) >> 8) & 0xf)
#define LETTER_CONSTRAINT(constraint) (((constraint) >> 4) & 0xf)
#define OTHER_CONSTRAINT(constraint) ((constraint) & 0xf)
#define SUCCEEDS_IN_CONTEXT(constraint, prev, curr) \
((((curr) & CTX_NONE ? OTHER_CONSTRAINT (constraint) : 0) \
| ((curr) & CTX_LETTER ? LETTER_CONSTRAINT (constraint) : 0) \
| ((curr) & CTX_NEWLINE ? NEWLINE_CONSTRAINT (constraint) : 0)) & (prev))
/* The following macros describe what a constraint depends on. */
#define PREV_NEWLINE_CONSTRAINT(constraint) (((constraint) >> 2) & 0x111)
#define PREV_LETTER_CONSTRAINT(constraint) (((constraint) >> 1) & 0x111)
#define PREV_OTHER_CONSTRAINT(constraint) ((constraint) & 0x111)
#define PREV_NEWLINE_DEPENDENT(constraint) \
(PREV_NEWLINE_CONSTRAINT (constraint) != PREV_OTHER_CONSTRAINT (constraint))
#define PREV_LETTER_DEPENDENT(constraint) \
(PREV_LETTER_CONSTRAINT (constraint) != PREV_OTHER_CONSTRAINT (constraint))
/* Tokens that match the empty string subject to some constraint actually
work by applying that constraint to determine what may follow them,
taking into account what has gone before. The following values are
the constraints corresponding to the special tokens previously defined. */
#define NO_CONSTRAINT 0x777
#define BEGLINE_CONSTRAINT 0x444
#define ENDLINE_CONSTRAINT 0x700
#define BEGWORD_CONSTRAINT 0x050
#define ENDWORD_CONSTRAINT 0x202
#define LIMWORD_CONSTRAINT 0x252
#define NOTLIMWORD_CONSTRAINT 0x525
/* The regexp is parsed into an array of tokens in postfix form. Some tokens
are operators and others are terminal symbols. Most (but not all) of these
codes are returned by the lexical analyzer. */
typedef ptrdiff_t token;
/* Predefined token values. */
enum
{
END = -1, /* END is a terminal symbol that matches the
end of input; any value of END or less in
the parse tree is such a symbol. Accepting
states of the DFA are those that would have
a transition on END. */
/* Ordinary character values are terminal symbols that match themselves. */
EMPTY = NOTCHAR, /* EMPTY is a terminal symbol that matches
the empty string. */
BACKREF, /* BACKREF is generated by \<digit>
or by any other construct that
is not completely handled. If the scanner
detects a transition on backref, it returns
a kind of "semi-success" indicating that
the match will have to be verified with
a backtracking matcher. */
BEGLINE, /* BEGLINE is a terminal symbol that matches
the empty string at the beginning of a
line. */
ENDLINE, /* ENDLINE is a terminal symbol that matches
the empty string at the end of a line. */
BEGWORD, /* BEGWORD is a terminal symbol that matches
the empty string at the beginning of a
word. */
ENDWORD, /* ENDWORD is a terminal symbol that matches
the empty string at the end of a word. */
LIMWORD, /* LIMWORD is a terminal symbol that matches
the empty string at the beginning or the
end of a word. */
NOTLIMWORD, /* NOTLIMWORD is a terminal symbol that
matches the empty string not at
the beginning or end of a word. */
QMARK, /* QMARK is an operator of one argument that
matches zero or one occurrences of its
argument. */
STAR, /* STAR is an operator of one argument that
matches the Kleene closure (zero or more
occurrences) of its argument. */
PLUS, /* PLUS is an operator of one argument that
matches the positive closure (one or more
occurrences) of its argument. */
REPMN, /* REPMN is a lexical token corresponding
to the {m,n} construct. REPMN never
appears in the compiled token vector. */
CAT, /* CAT is an operator of two arguments that
matches the concatenation of its
arguments. CAT is never returned by the
lexical analyzer. */
OR, /* OR is an operator of two arguments that
matches either of its arguments. */
LPAREN, /* LPAREN never appears in the parse tree,
it is only a lexeme. */
RPAREN, /* RPAREN never appears in the parse tree. */
ANYCHAR, /* ANYCHAR is a terminal symbol that matches
a valid multibyte (or single byte) character.
It is used only if MB_CUR_MAX > 1. */
MBCSET, /* MBCSET is similar to CSET, but for
multibyte characters. */
WCHAR, /* Only returned by lex. wctok contains
the wide character representation. */
CSET /* CSET and (and any value greater) is a
terminal symbol that matches any of a
class of characters. */
};
/* States of the recognizer correspond to sets of positions in the parse
tree, together with the constraints under which they may be matched.
So a position is encoded as an index into the parse tree together with
a constraint. */
typedef struct
{
size_t index; /* Index into the parse array. */
unsigned int constraint; /* Constraint for matching this position. */
} position;
/* Sets of positions are stored as arrays. */
typedef struct
{
position *elems; /* Elements of this position set. */
size_t nelem; /* Number of elements in this set. */
size_t alloc; /* Number of elements allocated in ELEMS. */
} position_set;
/* Sets of leaves are also stored as arrays. */
typedef struct
{
size_t *elems; /* Elements of this position set. */
size_t nelem; /* Number of elements in this set. */
} leaf_set;
/* A state of the dfa consists of a set of positions, some flags,
and the token value of the lowest-numbered position of the state that
contains an END token. */
typedef struct
{
size_t hash; /* Hash of the positions of this state. */
position_set elems; /* Positions this state could match. */
unsigned char context; /* Context from previous state. */
bool has_backref; /* This state matches a \<digit>. */
bool has_mbcset; /* This state matches a MBCSET. */
unsigned short constraint; /* Constraint for this state to accept. */
token first_end; /* Token value of the first END in elems. */
position_set mbps; /* Positions which can match multibyte
characters, e.g., period.
Used only if MB_CUR_MAX > 1. */
} dfa_state;
/* States are indexed by state_num values. These are normally
nonnegative but -1 is used as a special value. */
typedef ptrdiff_t state_num;
/* A bracket operator.
e.g., [a-c], [[:alpha:]], etc. */
struct mb_char_classes
{
ptrdiff_t cset;
bool invert;
wchar_t *chars; /* Normal characters. */
size_t nchars;
wctype_t *ch_classes; /* Character classes. */
size_t nch_classes;
struct /* Range characters. */
{
wchar_t beg; /* Range start. */
wchar_t end; /* Range end. */
} *ranges;
size_t nranges;
char **equivs; /* Equivalence classes. */
size_t nequivs;
char **coll_elems;
size_t ncoll_elems; /* Collating elements. */
};
/* A compiled regular expression. */
struct dfa
{
/* Fields filled by the scanner. */
charclass *charclasses; /* Array of character sets for CSET tokens. */
size_t cindex; /* Index for adding new charclasses. */
size_t calloc; /* Number of charclasses allocated. */
/* Fields filled by the parser. */
token *tokens; /* Postfix parse array. */
size_t tindex; /* Index for adding new tokens. */
size_t talloc; /* Number of tokens currently allocated. */
size_t depth; /* Depth required of an evaluation stack
used for depth-first traversal of the
parse tree. */
size_t nleaves; /* Number of leaves on the parse tree. */
size_t nregexps; /* Count of parallel regexps being built
with dfaparse. */
bool fast; /* The DFA is fast. */
bool multibyte; /* MB_CUR_MAX > 1. */
token utf8_anychar_classes[5]; /* To lower ANYCHAR in UTF-8 locales. */
mbstate_t mbs; /* Multibyte conversion state. */
/* dfaexec implementation. */
char *(*dfaexec) (struct dfa *, char const *, char *, int, size_t *, int *);
/* The following are valid only if MB_CUR_MAX > 1. */
/* The value of multibyte_prop[i] is defined by following rule.
if tokens[i] < NOTCHAR
bit 0 : tokens[i] is the first byte of a character, including
single-byte characters.
bit 1 : tokens[i] is the last byte of a character, including
single-byte characters.
if tokens[i] = MBCSET
("the index of mbcsets corresponding to this operator" << 2) + 3
e.g.
tokens
= 'single_byte_a', 'multi_byte_A', single_byte_b'
= 'sb_a', 'mb_A(1st byte)', 'mb_A(2nd byte)', 'mb_A(3rd byte)', 'sb_b'
multibyte_prop
= 3 , 1 , 0 , 2 , 3
*/
int *multibyte_prop;
/* A table indexed by byte values that contains the corresponding wide
character (if any) for that byte. WEOF means the byte is not a
valid single-byte character. */
wint_t mbrtowc_cache[NOTCHAR];
/* Array of the bracket expression in the DFA. */
struct mb_char_classes *mbcsets;
size_t nmbcsets;
size_t mbcsets_alloc;
/* Fields filled by the superset. */
struct dfa *superset; /* Hint of the dfa. */
/* Fields filled by the state builder. */
dfa_state *states; /* States of the dfa. */
state_num sindex; /* Index for adding new states. */
size_t salloc; /* Number of states currently allocated. */
/* Fields filled by the parse tree->NFA conversion. */
position_set *follows; /* Array of follow sets, indexed by position
index. The follow of a position is the set
of positions containing characters that
could conceivably follow a character
matching the given position in a string
matching the regexp. Allocated to the
maximum possible position index. */
bool searchflag; /* We are supposed to build a searching
as opposed to an exact matcher. A searching
matcher finds the first and shortest string
matching a regexp anywhere in the buffer,
whereas an exact matcher finds the longest
string matching, but anchored to the
beginning of the buffer. */
/* Fields filled by dfaexec. */
state_num tralloc; /* Number of transition tables that have
slots so far, not counting trans[-1]. */
int trcount; /* Number of transition tables that have
actually been built. */
int min_trcount; /* Minimum of number of transition tables.
Always keep the number, even after freeing
the transition tables. It is also the
number of initial states. */
state_num **trans; /* Transition tables for states that can
never accept. If the transitions for a
state have not yet been computed, or the
state could possibly accept, its entry in
this table is NULL. This points to one
past the start of the allocated array,
and trans[-1] is always NULL. */
state_num **fails; /* Transition tables after failing to accept
on a state that potentially could do so. */
int *success; /* Table of acceptance conditions used in
dfaexec and computed in build_state. */
state_num *newlines; /* Transitions on newlines. The entry for a
newline in any transition table is always
-1 so we can count lines without wasting
too many cycles. The transition for a
newline is stored separately and handled
as a special case. Newline is also used
as a sentinel at the end of the buffer. */
state_num initstate_letter; /* Initial state for letter context. */
state_num initstate_others; /* Initial state for other contexts. */
struct dfamust *musts; /* List of strings, at least one of which
is known to appear in any r.e. matching
the dfa. */
position_set mb_follows; /* Follow set added by ANYCHAR and/or MBCSET
on demand. */
int *mb_match_lens; /* Array of length reduced by ANYCHAR and/or
MBCSET. Null if mb_follows.elems has not
been allocated. */
};
/* Some macros for user access to dfa internals. */
/* S could possibly be an accepting state of R. */
#define ACCEPTING(s, r) ((r).states[s].constraint)
/* STATE accepts in the specified context. */
#define ACCEPTS_IN_CONTEXT(prev, curr, state, dfa) \
SUCCEEDS_IN_CONTEXT ((dfa).states[state].constraint, prev, curr)
static void dfamust (struct dfa *dfa);
static void regexp (void);
static void
dfambcache (struct dfa *d)
{
int i;
for (i = CHAR_MIN; i <= CHAR_MAX; ++i)
{
char c = i;
unsigned char uc = i;
mbstate_t s = { 0 };
wchar_t wc;
d->mbrtowc_cache[uc] = mbrtowc (&wc, &c, 1, &s) <= 1 ? wc : WEOF;
}
}
/* Store into *PWC the result of converting the leading bytes of the
multibyte buffer S of length N bytes, using the mbrtowc_cache in *D
and updating the conversion state in *D. On conversion error,
convert just a single byte, to WEOF. Return the number of bytes
converted.
This differs from mbrtowc (PWC, S, N, &D->mbs) as follows:
* PWC points to wint_t, not to wchar_t.
* The last arg is a dfa *D instead of merely a multibyte conversion
state D->mbs. D also contains an mbrtowc_cache for speed.
* N must be at least 1.
* S[N - 1] must be a sentinel byte.
* Shift encodings are not supported.
* The return value is always in the range 1..N.
* D->mbs is always valid afterwards.
* *PWC is always set to something. */
static size_t
mbs_to_wchar (wint_t *pwc, char const *s, size_t n, struct dfa *d)
{
unsigned char uc = s[0];
wint_t wc = d->mbrtowc_cache[uc];
if (wc == WEOF)
{
wchar_t wch;
size_t nbytes = mbrtowc (&wch, s, n, &d->mbs);
if (0 < nbytes && nbytes < (size_t) -2)
{
*pwc = wch;
return nbytes;
}
memset (&d->mbs, 0, sizeof d->mbs);
}
*pwc = wc;
return 1;
}
#ifdef DEBUG
static void
prtok (token t)
{
char const *s;
if (t < 0)
fprintf (stderr, "END");
else if (t < NOTCHAR)
{
int ch = t;
fprintf (stderr, "%c", ch);
}
else
{
switch (t)
{
case EMPTY:
s = "EMPTY";
break;
case BACKREF:
s = "BACKREF";
break;
case BEGLINE:
s = "BEGLINE";
break;
case ENDLINE:
s = "ENDLINE";
break;
case BEGWORD:
s = "BEGWORD";
break;
case ENDWORD:
s = "ENDWORD";
break;
case LIMWORD:
s = "LIMWORD";
break;
case NOTLIMWORD:
s = "NOTLIMWORD";
break;
case QMARK:
s = "QMARK";
break;
case STAR:
s = "STAR";
break;
case PLUS:
s = "PLUS";
break;
case CAT:
s = "CAT";
break;
case OR:
s = "OR";
break;
case LPAREN:
s = "LPAREN";
break;
case RPAREN:
s = "RPAREN";
break;
case ANYCHAR:
s = "ANYCHAR";
break;
case MBCSET:
s = "MBCSET";
break;
default:
s = "CSET";
break;
}
fprintf (stderr, "%s", s);
}
}
#endif /* DEBUG */
/* Stuff pertaining to charclasses. */
static bool
tstbit (unsigned int b, charclass const c)
{
return c[b / CHARCLASS_WORD_BITS] >> b % CHARCLASS_WORD_BITS & 1;
}
static void
setbit (unsigned int b, charclass c)
{
c[b / CHARCLASS_WORD_BITS] |= (charclass_word) 1 << b % CHARCLASS_WORD_BITS;
}
static void
clrbit (unsigned int b, charclass c)
{
c[b / CHARCLASS_WORD_BITS] &= ~((charclass_word) 1
<< b % CHARCLASS_WORD_BITS);
}
static void
copyset (charclass const src, charclass dst)
{
memcpy (dst, src, sizeof (charclass));
}
static void
zeroset (charclass s)
{
memset (s, 0, sizeof (charclass));
}
static void
notset (charclass s)
{
int i;
for (i = 0; i < CHARCLASS_WORDS; ++i)
s[i] = CHARCLASS_WORD_MASK & ~s[i];
}
static bool
equal (charclass const s1, charclass const s2)
{
return memcmp (s1, s2, sizeof (charclass)) == 0;
}
/* Ensure that the array addressed by PTR holds at least NITEMS +
(PTR || !NITEMS) items. Either return PTR, or reallocate the array
and return its new address. Although PTR may be null, the returned
value is never null.
The array holds *NALLOC items; *NALLOC is updated on reallocation.
ITEMSIZE is the size of one item. Avoid O(N**2) behavior on arrays
growing linearly. */
static void *
maybe_realloc (void *ptr, size_t nitems, size_t *nalloc, size_t itemsize)
{
if (nitems < *nalloc)
return ptr;
*nalloc = nitems;
return x2nrealloc (ptr, nalloc, itemsize);
}
/* In DFA D, find the index of charclass S, or allocate a new one. */
static size_t
dfa_charclass_index (struct dfa *d, charclass const s)
{
size_t i;
for (i = 0; i < d->cindex; ++i)
if (equal (s, d->charclasses[i]))
return i;
d->charclasses = maybe_realloc (d->charclasses, d->cindex, &d->calloc,
sizeof *d->charclasses);
++d->cindex;
copyset (s, d->charclasses[i]);
return i;
}
/* A pointer to the current dfa is kept here during parsing. */
static struct dfa *dfa;
/* Find the index of charclass S in the current DFA, or allocate a new one. */
static size_t
charclass_index (charclass const s)
{
return dfa_charclass_index (dfa, s);
}
/* Syntax bits controlling the behavior of the lexical analyzer. */
static reg_syntax_t syntax_bits, syntax_bits_set;
/* Flag for case-folding letters into sets. */
static bool case_fold;
/* End-of-line byte in data. */
static unsigned char eolbyte;
/* Cache of char-context values. */
static int sbit[NOTCHAR];
/* Set of characters considered letters. */
static charclass letters;
/* Set of characters that are newline. */
static charclass newline;
/* Add this to the test for whether a byte is word-constituent, since on
BSD-based systems, many values in the 128..255 range are classified as
alphabetic, while on glibc-based systems, they are not. */
#ifdef __GLIBC__
# define is_valid_unibyte_character(c) 1
#else
# define is_valid_unibyte_character(c) (btowc (c) != WEOF)
#endif
/* C is a "word-constituent" byte. */
#define IS_WORD_CONSTITUENT(C) \
(is_valid_unibyte_character (C) && (isalnum (C) || (C) == '_'))
static int
char_context (unsigned char c)
{
if (c == eolbyte)
return CTX_NEWLINE;
if (IS_WORD_CONSTITUENT (c))
return CTX_LETTER;
return CTX_NONE;
}
static int
wchar_context (wint_t wc)
{
if (wc == (wchar_t) eolbyte || wc == 0)
return CTX_NEWLINE;
if (wc == L'_' || iswalnum (wc))
return CTX_LETTER;
return CTX_NONE;
}
/* Entry point to set syntax options. */
void
dfasyntax (reg_syntax_t bits, int fold, unsigned char eol)
{
unsigned int i;
syntax_bits_set = 1;
syntax_bits = bits;
case_fold = fold != 0;
eolbyte = eol;
for (i = 0; i < NOTCHAR; ++i)
{
sbit[i] = char_context (i);
switch (sbit[i])
{
case CTX_LETTER:
setbit (i, letters);
break;
case CTX_NEWLINE:
setbit (i, newline);
break;
}
}
}
/* Set a bit in the charclass for the given wchar_t. Do nothing if WC
is represented by a multi-byte sequence. Even for MB_CUR_MAX == 1,
this may happen when folding case in weird Turkish locales where
dotless i/dotted I are not included in the chosen character set.
Return whether a bit was set in the charclass. */
static bool
setbit_wc (wint_t wc, charclass c)
{
int b = wctob (wc);
if (b == EOF)
return false;
setbit (b, c);
return true;
}
/* Set a bit for B and its case variants in the charclass C.
MB_CUR_MAX must be 1. */
static void
setbit_case_fold_c (int b, charclass c)
{
int ub = toupper (b);
int i;
for (i = 0; i < NOTCHAR; i++)
if (toupper (i) == ub)
setbit (i, c);
}
/* UTF-8 encoding allows some optimizations that we can't otherwise
assume in a multibyte encoding. */
int
using_utf8 (void)
{
static int utf8 = -1;
if (utf8 < 0)
{
wchar_t wc;
mbstate_t mbs = { 0 };
utf8 = mbrtowc (&wc, "\xc4\x80", 2, &mbs) == 2 && wc == 0x100;
#ifdef LIBC_IS_BORKED
if (gawk_mb_cur_max == 1)
utf8 = 0;
#endif
}
return utf8;
}
/* The current locale is known to be a unibyte locale
without multicharacter collating sequences and where range
comparisons simply use the native encoding. These locales can be
processed more efficiently. */
static bool
using_simple_locale (void)
{
/* The native character set is known to be compatible with
the C locale. The following test isn't perfect, but it's good
enough in practice, as only ASCII and EBCDIC are in common use
and this test correctly accepts ASCII and rejects EBCDIC. */
enum { native_c_charset =
('\b' == 8 && '\t' == 9 && '\n' == 10 && '\v' == 11 && '\f' == 12
&& '\r' == 13 && ' ' == 32 && '!' == 33 && '"' == 34 && '#' == 35
&& '%' == 37 && '&' == 38 && '\'' == 39 && '(' == 40 && ')' == 41
&& '*' == 42 && '+' == 43 && ',' == 44 && '-' == 45 && '.' == 46
&& '/' == 47 && '0' == 48 && '9' == 57 && ':' == 58 && ';' == 59
&& '<' == 60 && '=' == 61 && '>' == 62 && '?' == 63 && 'A' == 65
&& 'Z' == 90 && '[' == 91 && '\\' == 92 && ']' == 93 && '^' == 94
&& '_' == 95 && 'a' == 97 && 'z' == 122 && '{' == 123 && '|' == 124
&& '}' == 125 && '~' == 126)
};
if (! native_c_charset || dfa->multibyte)
return false;
else
{
static int unibyte_c = -1;
if (unibyte_c < 0)
{
char const *locale = setlocale (LC_ALL, NULL);
unibyte_c = (!locale
|| STREQ (locale, "C")
|| STREQ (locale, "POSIX"));
}
return unibyte_c;
}
}
/* Lexical analyzer. All the dross that deals with the obnoxious
GNU Regex syntax bits is located here. The poor, suffering
reader is referred to the GNU Regex documentation for the
meaning of the @#%!@#%^!@ syntax bits. */
static char const *lexptr; /* Pointer to next input character. */
static size_t lexleft; /* Number of characters remaining. */
static token lasttok; /* Previous token returned; initially END. */
static bool laststart; /* We're separated from beginning or (,
| only by zero-width characters. */
static size_t parens; /* Count of outstanding left parens. */
static int minrep, maxrep; /* Repeat counts for {m,n}. */
static int cur_mb_len = 1; /* Length of the multibyte representation of
wctok. */
static wint_t wctok; /* Wide character representation of the current
multibyte character, or WEOF if there was
an encoding error. Used only if
MB_CUR_MAX > 1. */
/* Fetch the next lexical input character. Set C (of type int) to the
next input byte, except set C to EOF if the input is a multibyte
character of length greater than 1. Set WC (of type wint_t) to the
value of the input if it is a valid multibyte character (possibly
of length 1); otherwise set WC to WEOF. If there is no more input,
report EOFERR if EOFERR is not null, and return lasttok = END
otherwise. */
# define FETCH_WC(c, wc, eoferr) \
do { \
if (! lexleft) \
{ \
if ((eoferr) != 0) \
dfaerror (eoferr); \
else \
return lasttok = END; \
} \
else \
{ \
wint_t _wc; \
size_t nbytes = mbs_to_wchar (&_wc, lexptr, lexleft, dfa); \
cur_mb_len = nbytes; \
(wc) = _wc; \
(c) = nbytes == 1 ? to_uchar (*lexptr) : EOF; \
lexptr += nbytes; \
lexleft -= nbytes; \
} \
} while (0)
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
/* The set of wchar_t values C such that there's a useful locale
somewhere where C != towupper (C) && C != towlower (towupper (C)).
For example, 0x00B5 (U+00B5 MICRO SIGN) is in this table, because
towupper (0x00B5) == 0x039C (U+039C GREEK CAPITAL LETTER MU), and
towlower (0x039C) == 0x03BC (U+03BC GREEK SMALL LETTER MU). */
static short const lonesome_lower[] =
{
0x00B5, 0x0131, 0x017F, 0x01C5, 0x01C8, 0x01CB, 0x01F2, 0x0345,
0x03C2, 0x03D0, 0x03D1, 0x03D5, 0x03D6, 0x03F0, 0x03F1,
/* U+03F2 GREEK LUNATE SIGMA SYMBOL lacks a specific uppercase
counterpart in locales predating Unicode 4.0.0 (April 2003). */
0x03F2,
0x03F5, 0x1E9B, 0x1FBE,
};
/* Maximum number of characters that can be the case-folded
counterparts of a single character, not counting the character
itself. This is 1 for towupper, 1 for towlower, and 1 for each
entry in LONESOME_LOWER. */
enum
{ CASE_FOLDED_BUFSIZE = 2 + sizeof lonesome_lower / sizeof *lonesome_lower };
/* Find the characters equal to C after case-folding, other than C
itself, and store them into FOLDED. Return the number of characters
stored. */
static int
case_folded_counterparts (wchar_t c, wchar_t folded[CASE_FOLDED_BUFSIZE])
{
int i;
int n = 0;
wint_t uc = towupper (c);
wint_t lc = towlower (uc);
if (uc != c)
folded[n++] = uc;
if (lc != uc && lc != c && towupper (lc) == uc)
folded[n++] = lc;
for (i = 0; i < sizeof lonesome_lower / sizeof *lonesome_lower; i++)
{
wint_t li = lonesome_lower[i];
if (li != lc && li != uc && li != c && towupper (li) == uc)
folded[n++] = li;
}
return n;
}
typedef int predicate (int);
/* The following list maps the names of the Posix named character classes
to predicate functions that determine whether a given character is in
the class. The leading [ has already been eaten by the lexical
analyzer. */
struct dfa_ctype
{
const char *name;
predicate *func;
bool single_byte_only;
};
static const struct dfa_ctype prednames[] = {
{"alpha", isalpha, false},
{"upper", isupper, false},
{"lower", islower, false},
{"digit", isdigit, true},
{"xdigit", isxdigit, false},
{"space", isspace, false},
{"punct", ispunct, false},
{"alnum", isalnum, false},
{"print", isprint, false},
{"graph", isgraph, false},
{"cntrl", iscntrl, false},