-
Notifications
You must be signed in to change notification settings - Fork 1
/
dfa.c
4136 lines (3648 loc) · 126 KB
/
dfa.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
/* dfa.c - deterministic extended regexp routines for GNU
Copyright (C) 1988, 1998, 2000, 2002, 2004-2005, 2007-2013 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
#ifdef HAVE_STDBOOL_H
#include <stdbool.h>
#else
#include "missing_d/gawkbool.h"
#endif /* HAVE_STDBOOL_H */
#include "dfa.h"
#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)
/* gettext.h ensures that we don't use gettext if ENABLE_NLS is not defined */
#include "gettext.h"
#define _(str) gettext (str)
#include "mbsupport.h" /* defines MBS_SUPPORT to 1 or 0, as appropriate */
#if MBS_SUPPORT
/* We can handle multibyte strings. */
# include <wchar.h>
# include <wctype.h>
#endif
#ifdef GAWK
/* The __pure__ attribute was added in gcc 2.96. */
#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
# define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
#else
# define _GL_ATTRIBUTE_PURE /* empty */
#endif
#endif /* GAWK */
#if HAVE_LANGINFO_CODESET
# include <langinfo.h>
#endif
#include "xalloc.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, define those as macros in sys/param.h */
#ifdef setbit
# undef setbit
#endif
#ifdef clrbit
# undef clrbit
#endif
/* Number of bits in an unsigned char. */
#ifndef CHARBITS
# define CHARBITS 8
#endif
/* First integer value that is greater than any character code. */
#define NOTCHAR (1 << CHARBITS)
/* INTBITS need not be exact, just a lower bound. */
#ifndef INTBITS
# define INTBITS (CHARBITS * sizeof (int))
#endif
/* Number of ints required to hold a bit for every character. */
#define CHARCLASS_INTS ((NOTCHAR + INTBITS - 1) / INTBITS)
/* Sets of unsigned characters are stored as bit vectors in arrays of ints. */
typedef int charclass[CHARCLASS_INTS];
/* 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 inline 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 give information about 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>; it
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 if it is at the beginning
of a line. */
ENDLINE, /* ENDLINE is a terminal symbol that matches
the empty string if it is at the end of
a line. */
BEGWORD, /* BEGWORD is a terminal symbol that matches
the empty string if it is at the beginning
of a word. */
ENDWORD, /* ENDWORD is a terminal symbol that matches
the empty string if it is at the end of
a word. */
LIMWORD, /* LIMWORD is a terminal symbol that matches
the empty string if it is at the beginning
or the end of a word. */
NOTLIMWORD, /* NOTLIMWORD is a terminal symbol that
matches the empty string if it is 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
any multibyte (or single byte) characters.
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. */
char backref; /* True if this state matches a \<digit>. */
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.
These staff are 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;
int invert;
wchar_t *chars; /* Normal characters. */
size_t nchars;
wctype_t *ch_classes; /* Character classes. */
size_t nch_classes;
wchar_t *range_sts; /* Range characters (start of the range). */
wchar_t *range_ends; /* Range characters (end of the range). */
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 currently 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(). */
unsigned int mb_cur_max; /* Cached value of MB_CUR_MAX. */
token utf8_anychar_classes[5]; /* To lower ANYCHAR in UTF-8 locales. */
/* The following are used 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
*/
size_t nmultibyte_prop;
int *multibyte_prop;
/* Array of the bracket expression in the DFA. */
struct mb_char_classes *mbcsets;
size_t nmbcsets;
size_t mbcsets_alloc;
/* Fields filled by the state builder. */
dfa_state *states; /* States of the dfa. */
state_num sindex; /* Index for adding new states. */
state_num 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. */
int searchflag; /* True if 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. */
int trcount; /* Number of transition tables that have
actually been built. */
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. */
state_num **realtrans; /* Trans always points to realtrans + 1; this
is so trans[-1] can contain 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. */
struct dfamust *musts; /* List of strings, at least one of which
is known to appear in any r.e. matching
the dfa. */
};
/* Some macros for user access to dfa internals. */
/* ACCEPTING returns true if s could possibly be an accepting state of r. */
#define ACCEPTING(s, r) ((r).states[s].constraint)
/* ACCEPTS_IN_CONTEXT returns true if the given 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);
/* These two macros are identical to the ones in gnulib's xalloc.h,
except that they not to case the result to "(t *)", and thus may
be used via type-free CALLOC and MALLOC macros. */
#undef XNMALLOC
#undef XCALLOC
/* Allocate memory for N elements of type T, with error checking. */
/* extern t *XNMALLOC (size_t n, typename t); */
# define XNMALLOC(n, t) \
(sizeof (t) == 1 ? xmalloc (n) : xnmalloc (n, sizeof (t)))
/* Allocate memory for N elements of type T, with error checking,
and zero it. */
/* extern t *XCALLOC (size_t n, typename t); */
# define XCALLOC(n, t) \
(sizeof (t) == 1 ? xzalloc (n) : xcalloc (n, sizeof (t)))
#define CALLOC(p, n) do { (p) = XCALLOC (n, *(p)); } while (0)
#undef MALLOC /* Irix defines this */
#define MALLOC(p, n) do { (p) = XNMALLOC (n, *(p)); } while (0)
#define REALLOC(p, n) do {(p) = xnrealloc (p, n, sizeof (*(p))); } while (0)
/* Reallocate an array of type *P if N_ALLOC is <= N_REQUIRED. */
#define REALLOC_IF_NECESSARY(p, n_alloc, n_required) \
do \
{ \
if ((n_alloc) <= (n_required)) \
{ \
size_t new_n_alloc = (n_required) + !(p); \
(p) = x2nrealloc (p, &new_n_alloc, sizeof (*(p))); \
(n_alloc) = new_n_alloc; \
} \
} \
while (false)
#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 int
tstbit (unsigned int b, charclass const c)
{
return c[b / INTBITS] & 1 << b % INTBITS;
}
static void
setbit (unsigned int b, charclass c)
{
c[b / INTBITS] |= 1 << b % INTBITS;
}
static void
clrbit (unsigned int b, charclass c)
{
c[b / INTBITS] &= ~(1 << b % INTBITS);
}
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_INTS; ++i)
s[i] = ~s[i];
}
static int
equal (charclass const s1, charclass const s2)
{
return memcmp (s1, s2, sizeof (charclass)) == 0;
}
/* A pointer to the current dfa is kept here during parsing. */
static struct dfa *dfa;
/* Find the index of charclass s in dfa->charclasses, or allocate a new charclass. */
static size_t
charclass_index (charclass const s)
{
size_t i;
for (i = 0; i < dfa->cindex; ++i)
if (equal (s, dfa->charclasses[i]))
return i;
REALLOC_IF_NECESSARY (dfa->charclasses, dfa->calloc, dfa->cindex + 1);
++dfa->cindex;
copyset (s, dfa->charclasses[i]);
return i;
}
/* 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 int 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) (! (MBS_SUPPORT && btowc (c) == WEOF))
#endif
/* Return non-zero if C is a "word-constituent" byte; zero otherwise. */
#define IS_WORD_CONSTITUENT(C) \
(is_valid_unibyte_character (C) && (isalnum (C) || (C) == '_'))
static int
char_context (unsigned char c)
{
if (c == eolbyte || c == 0)
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;
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. */
#if MBS_SUPPORT
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 in the charclass for the given single byte character,
if it is valid in the current character set. */
static void
setbit_c (int b, charclass c)
{
/* Do nothing if b is invalid in this character set. */
if (MB_CUR_MAX > 1 && btowc (b) == WEOF)
return;
setbit (b, c);
}
#else
# define setbit_c setbit
static inline bool
setbit_wc (wint_t wc, charclass c)
{
abort ();
/*NOTREACHED*/ return false;
}
#endif
/* Like setbit_c, but if case is folded, set both cases of a letter. For
MB_CUR_MAX > 1, the resulting charset is only used as an optimization,
and the caller takes care of setting the appropriate field of struct
mb_char_classes. */
static void
setbit_case_fold_c (int b, charclass c)
{
if (MB_CUR_MAX > 1)
{
wint_t wc = btowc (b);
if (wc == WEOF)
return;
setbit (b, c);
if (case_fold && iswalpha (wc))
setbit_wc (iswupper (wc) ? towlower (wc) : towupper (wc), c);
}
else
{
setbit (b, c);
if (case_fold && isalpha (b))
setbit_c (isupper (b) ? tolower (b) : toupper (b), c);
}
}
/* UTF-8 encoding allows some optimizations that we can't otherwise
assume in a multibyte encoding. */
static inline int
using_utf8 (void)
{
static int utf8 = -1;
if (utf8 == -1)
{
#if defined HAVE_LANGINFO_CODESET && MBS_SUPPORT
utf8 = (STREQ (nl_langinfo (CODESET), "UTF-8"));
#else
utf8 = 0;
#endif
#ifdef LIBC_IS_BORKED
if (gawk_mb_cur_max == 1)
utf8 = 0;
#endif
}
return utf8;
}
/* 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 int laststart; /* True if 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. */
/* These variables are used only if (MB_CUR_MAX > 1). */
static mbstate_t mbs; /* Mbstate for mbrlen(). */
static wchar_t wctok; /* Wide character representation of the current
multibyte character. */
static unsigned char *mblen_buf; /* Correspond to the input buffer in dfaexec().
Each element store the amount of remain
byte of corresponding multibyte character
in the input string. A element's value
is 0 if corresponding character is a
single byte character.
e.g. input : 'a', <mb(0)>, <mb(1)>, <mb(2)>
mblen_buf : 0, 3, 2, 1
*/
static wchar_t *inputwcs; /* Wide character representation of input
string in dfaexec().
The length of this array is same as
the length of input string(char array).
inputstring[i] is a single-byte char,
or 1st byte of a multibyte char.
And inputwcs[i] is the codepoint. */
static unsigned char const *buf_begin; /* reference to begin in dfaexec(). */
static unsigned char const *buf_end; /* reference to end in dfaexec(). */
#if MBS_SUPPORT
/* Note that characters become unsigned here. */
# define FETCH_WC(c, wc, eoferr) \
do { \
if (! lexleft) \
{ \
if ((eoferr) != 0) \
dfaerror (eoferr); \
else \
return lasttok = END; \
} \
else \
{ \
wchar_t _wc; \
cur_mb_len = mbrtowc (&_wc, lexptr, lexleft, &mbs); \
if (cur_mb_len <= 0) \
{ \
cur_mb_len = 1; \
--lexleft; \
(wc) = (c) = to_uchar (*lexptr++); \
} \
else \
{ \
lexptr += cur_mb_len; \
lexleft -= cur_mb_len; \
(wc) = _wc; \
(c) = wctob (wc); \
} \
} \
} while(0)
# define FETCH(c, eoferr) \
do { \
wint_t wc; \
FETCH_WC (c, wc, eoferr); \
} while (0)
#else
/* Note that characters become unsigned here. */
# define FETCH(c, eoferr) \
do { \
if (! lexleft) \
{ \
if ((eoferr) != 0) \
dfaerror (eoferr); \
else \
return lasttok = END; \
} \
(c) = to_uchar (*lexptr++); \
--lexleft; \
} while(0)
# define FETCH_WC(c, unused, eoferr) FETCH (c, eoferr)
#endif /* MBS_SUPPORT */
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
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, true},
{"space", isspace, false},
{"punct", ispunct, false},
{"alnum", isalnum, false},
{"print", isprint, false},
{"graph", isgraph, false},
{"cntrl", iscntrl, false},
{"blank", is_blank, false},
{NULL, NULL, false}
};
static const struct dfa_ctype *_GL_ATTRIBUTE_PURE
find_pred (const char *str)
{
unsigned int i;
for (i = 0; prednames[i].name; ++i)
if (STREQ (str, prednames[i].name))
break;
return &prednames[i];
}
/* Multibyte character handling sub-routine for lex.
This function parse a bracket expression and build a struct
mb_char_classes. */
static token
parse_bracket_exp (void)
{
int invert;
int c, c1, c2;
charclass ccl;
/* Used to warn about [:space:].
Bit 0 = first character is a colon.
Bit 1 = last character is a colon.
Bit 2 = includes any other character but a colon.
Bit 3 = includes ranges, char/equiv classes or collation elements. */
int colon_warning_state;
wint_t wc;
wint_t wc2;
wint_t wc1 = 0;
/* Work area to build a mb_char_classes. */
struct mb_char_classes *work_mbc;
size_t chars_al, range_sts_al, range_ends_al, ch_classes_al,
equivs_al, coll_elems_al;
chars_al = 0;
range_sts_al = range_ends_al = 0;
ch_classes_al = equivs_al = coll_elems_al = 0;
if (MB_CUR_MAX > 1)
{
REALLOC_IF_NECESSARY (dfa->mbcsets, dfa->mbcsets_alloc,
dfa->nmbcsets + 1);
/* dfa->multibyte_prop[] hold the index of dfa->mbcsets.
We will update dfa->multibyte_prop[] in addtok(), because we can't
decide the index in dfa->tokens[]. */
/* Initialize work area. */
work_mbc = &(dfa->mbcsets[dfa->nmbcsets++]);
memset (work_mbc, 0, sizeof *work_mbc);
}
else
work_mbc = NULL;
memset (ccl, 0, sizeof ccl);
FETCH_WC (c, wc, _("unbalanced ["));
if (c == '^')
{