-
-
Notifications
You must be signed in to change notification settings - Fork 694
/
regex.d
3596 lines (3252 loc) · 112 KB
/
regex.d
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
// Written in the D programming language.
// Regular Expressions.
/**
$(WEB digitalmars.com/ctg/regular.html, Regular expressions) are a
powerful method of string pattern matching. The regular expression
language used in this library is the same as that commonly used,
however, some of the very advanced forms may behave slightly
differently. The standard observed is the $(WEB
www.ecma-international.org/publications/standards/Ecma-262.htm, ECMA
standard) for regular expressions.
$(D std.regex) is designed to work only with valid UTF strings as
input - UTF8 ($(D char)), UTF16 ($(D wchar)), or UTF32 ($(D dchar)).
To validate untrusted input, use $(D std.utf.validate()).
In the following guide, $(D pattern[]) refers to a $(WEB
digitalmars.com/ctg/regular.html, regular expression). The $(D
attributes[]) refers to a string controlling the interpretation of the
regular expression. It consists of a sequence of one or more of the
following characters:
$(BOOKTABLE Attribute Characters,
$(TR $(TH Attribute) $(TH Action))
$(TR $(TD $(B g)) $(TD global; repeat over the whole input string))
$(TR $(TD $(B i)) $(TD case insensitive))
$(TR $(TD $(B m)) $(TD treat as multiple lines separated by newlines)))
The $(D format[]) string has the formatting characters:
$(BOOKTABLE Formatting Characters,
$(TR $(TH Format) $(TH Replaced With))
$(TR $(TD $(B $$)) $(TD $))
$(TR$(TD $(B $&)) $(TD The matched substring.))
$(TR $(TD $(B $`)) $(TD The portion of string that precedes the matched
substring.))
$(TR $(TD $(B $')) $(TD The portion of string that follows the matched
substring.))
$(TR $(TD $(B $(DOLLAR))$(I n)) $(TD The $(I n)th capture, where $(I
n) is a single digit 1-9 and $$(I n) is not followed by a decimal
digit.))
$(TR $(TD $(B $(DOLLAR))$(I nn)) $(TD The $(I nn)th
capture, where $(I nn) is a two-digit decimal number 01-99. If $(I
nn)th capture is undefined or more than the number of parenthesized
subexpressions, use the empty string instead.)))
Any other $ are left as is.
References: $(WEB en.wikipedia.org/wiki/Regular_expressions,
Wikipedia)
Macros:
WIKI = StdRegex
DOLLAR = $
Copyright: Copyright Digital Mars 2000 - 2009.
License: <a href="http://www.boost.org/LICENSE_1_0.txt">Boost License 1.0</a>.
Authors: $(WEB digitalmars.com, Walter Bright),
$(WEB erdani.org, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/_regex.d)
*/
/*
Copyright Digital Mars 2000 - 2009.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
/*
Escape sequences:
\nnn starts out a 1, 2 or 3 digit octal sequence, where n is an octal
digit. If nnn is larger than 0377, then the 3rd digit is not part of
the sequence and is not consumed. For maximal portability, use
exactly 3 digits.
\xXX starts out a 1 or 2 digit hex sequence. X
is a hex character. If the first character after the \x
is not a hex character, the value of the sequence is 'x'
and the XX are not consumed.
For maximal portability, use exactly 2 digits.
\uUUUU is a unicode sequence. There are exactly
4 hex characters after the \u, if any are not, then
the value of the sequence is 'u', and the UUUU are not
consumed.
Character classes:
[a-b], where a is greater than b, will produce
an error.
References:
http://www.unicode.org/unicode/reports/tr18/
*/
module std.regex;
//debug = std_regex; // uncomment to turn on debugging writef's
import core.stdc.stdlib;
import core.stdc.string;
import std.stdio;
import std.string;
import std.ctype;
import std.outbuffer;
import std.bitmanip;
import std.utf;
import std.algorithm;
import std.array;
import std.traits;
import std.typecons;
import std.typetuple;
import std.range;
import std.conv;
import std.functional;
unittest
{
auto r = regex("abc"w);
auto m = match("abc"w, r);
if (!m.empty) return;
writeln(m.pre);
writeln(m.hit);
writeln(m.post);
r.printProgram;
assert(false);
}
/** Regular expression to extract an _email address.
References:
$(WEB regular-expressions.info/_email.html, How to Find or Validate an
Email Address); $(WEB tools.ietf.org/html/rfc2822#section-3.4.1, RFC
2822 Internet Message Format)
*/
enum string email =
r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}";
unittest
{
assert(match("asdassfsd@", regex(email)).empty);
assert(!match("andrei@metalanguage.com", regex(email)).empty);
}
/** Regular expression to extract a _url */
enum string url = r"(([h|H][t|T]|[f|F])[t|T][p|P]([s|S]?)\:\/\/|~/|/)?"
r"([\w]+:\w+@)?(([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))"
r"(:[\d]{1,5})?)?((/?\w+/)+|/?)"
r"(\w+\.[\w]{3,4})?([,]\w+)*((\?\w+=\w+)?(&\w+=\w+)*([,]\w*)*)?";
unittest
{
assert(!match("http://www.erdani.org/asd/sd?asd#eds",
regex(url)).empty);
}
/****************************************************
A $(D Regex) stores a regular expression engine. A $(D Regex) object
is constructed from a string and compiled into an internal format for
performance.
The type parameter $(D E) specifies the character type recognized by
the regular expression. Currently $(D char), $(D wchar), and $(D
dchar) are supported. The encoding of the regex string and of the
recognized strings must be the same.
This object will be mostly used via a call to the $(D regex) function,
which automatically deduces the character type.
Example: Declare two variables and assign to them a $(D Regex)
object. The first matches UTF-8 strings, the second matches UTF-32
strings and also has the global option set.
---
auto r = regex("pattern");
auto s = regex(r"p[1-5]\s*"w, "g");
---
*/
struct Regex(E) if (is(E == Unqual!E))
{
private:
alias Tuple!(size_t, "startIdx", size_t, "endIdx") regmatch_t;
enum REA
{
global = 1, // has the g attribute
ignoreCase = 2, // has the i attribute
multiline = 4, // if treat as multiple lines separated by
// newlines, or as a single line
dotmatchlf = 8, // if . matches \n
}
enum uint inf = ~0u;
uint re_nsub; // number of parenthesized subexpression matches
uint nCounters; //current counter (internal), number of counters
ubyte attributes;
immutable(ubyte)[] program; // pattern[] compiled into regular
// expression program
// Opcodes
enum : ubyte
{
REend, // end of program
REchar, // single character
REichar, // single character, case insensitive
REdchar, // single UCS character
REidchar, // single wide character, case insensitive
REanychar, // any character
REanystar, // ".*?"
REanystarg, // ".*"
REstring, // string of characters
REistring, // string of characters, case insensitive
REtestbit, // any in bitmap, non-consuming
REbit, // any in the bit map
REnotbit, // any not in the bit map
RErange, // any in the string
REnotrange, // any not in the string
REor, // a | b
REplus, // 1 or more
REstar, // 0 or more
REquest, // 0 or 1
REcounter, // begining of repetition
REloopg, // loop on body of repetition (greedy)
REloop, // ditto non-greedy
REbol, // begining of line
REeol, // end of line
REsave, // save submatch position i.e. "(" & ")"
REgoto, // goto offset
REret, // end of subprogram
RElookahead,
REneglookahead,
RElookbehind,
REneglookbehind,
REwordboundary,
REnotwordboundary,
REdigit,
REnotdigit,
REspace,
REnotspace,
REword,
REnotword,
REbackref,
};
public:
// @@@BUG Should be a constructor but template constructors don't work
// private void initialize(String)(String pattern, string attributes)
// {
// compile(pattern, attributes);
// }
/**
Construct a $(D Regex) object. Compile pattern with $(D attributes)
into an internal form for fast execution.
Params:
pattern = regular expression
attributes = The _attributes (g, i, and m accepted)
Throws: $(D Exception) if there are any compilation errors.
*/
this(String)(String pattern, string attributes = null)
{
compile(pattern, attributes);
}
unittest
{
debug(std_regex) writefln("regex.opCall.unittest()");
auto r1 = Regex("hello", "m");
string msg;
try
{
auto r2 = Regex("hello", "q");
assert(0);
}
catch (Exception ree)
{
msg = ree.toString();
//writefln("message: %s", ree);
}
assert(std.algorithm.countUntil(msg, "unrecognized attribute") >= 0);
}
/**
Returns the number of parenthesized captures
*/
uint captures() const
{
return re_nsub;
}
/* ********************************
* Throws Exception on error
*/
public void compile(String)(String pattern, string attributes)
{
this.attributes = 0;
foreach (c; attributes)
{
REA att;
switch (c)
{
case 'g': att = REA.global; break;
case 'i': att = REA.ignoreCase; break;
case 'm': att = REA.multiline; break;
default:
error("unrecognized attribute");
assert(0);
}
if (this.attributes & att)
{
error("redundant attribute");
assert(0);
}
this.attributes |= att;
}
uint oldre_nsub = re_nsub;
re_nsub = 0;
auto buf = new OutBuffer;
buf.reserve(pattern.length * 8);
size_t p = 0;
parseRegex(pattern, p, buf);
if (p < pattern.length)
{
error("unmatched ')'");
}
re_nsub /= 2; //start & ends -> pairs
postprocess(buf.data);
program = cast(immutable(ubyte)[]) buf.data;
buf.data = null;
delete buf;
}
void error(string msg)
{
debug(std_regex) writefln("error: %s", msg);
throw new Exception(msg);
}
//adjust jumps, after removing instructions at 'place'
void fixup(ubyte[] prog, size_t place, uint change)
{
for (size_t pc=0;pc<prog.length;)
{
switch (prog[pc])
{
case REend:
return;
case REcounter: //jump forward
if(pc < place)
{
auto dest = cast(uint *)&prog[pc + 1 + uint.sizeof];
if (pc + *dest > place)
*dest -= change;
}
pc += 1 + 2*uint.sizeof;
break;
case REloop, REloopg: //jump back
if (pc > place)
{
auto dest = cast(uint *)&prog[pc + 1 + 2*uint.sizeof];
if (pc + *dest > place)
*dest += change;
}
pc += 1 + 3*uint.sizeof;
break;
case REneglookahead://jump or call forward
case RElookahead:
case REor:
case REgoto:
if (pc < place)
{
auto dest = cast(uint *)&prog[pc+1];
if (pc + *dest > place)
*dest -= change;
}
pc += 1 + uint.sizeof;
break;
case REret:
case REanychar:
case REanystarg:
case REanystar:
case REbol:
case REeol:
case REwordboundary:
case REnotwordboundary:
case REdigit:
case REnotdigit:
case REspace:
case REnotspace:
case REword:
case REnotword:
pc++;
break;
case REchar:
case REichar:
case REbackref:
pc += 2;
break;
case REdchar:
case REidchar:
pc += 1 + dchar.sizeof;
break;
case REstring:
case REistring:
auto len = *cast(size_t *)&prog[pc + 1];
assert(len % E.sizeof == 0);
pc += 1 + size_t.sizeof + len;
break;
case REtestbit:
case REbit:
case REnotbit:
auto pu = cast(ushort *)&prog[pc + 1];
auto len = pu[1];
pc += 1 + 2 * ushort.sizeof + len;
break;
case RErange:
case REnotrange:
auto len = *cast(uint *)&prog[pc + 1];
pc += 1 + uint.sizeof + len;
break;
case REsave:
pc += 1 + uint.sizeof;
break;
default:
writeln("%d",prog[pc]);
assert(0);
}
}
}
//Fixup counter numbers, simplify instructions
private void postprocess(ubyte[] prog)
{
uint counter = 0;
size_t len;
ushort* pu;
nCounters = 0;
size_t pc = 0;
for (;;)
{
switch (prog[pc])
{
case REend:
return;
case REcounter:
size_t offs = pc + 1 + 2*uint.sizeof;
bool anyloop = counter == 0 && prog[offs] == REanychar
&& (prog[offs+1] == REloop || prog[offs+1] == REloopg);
uint* puint = cast(uint*)&prog[offs+2];
if (anyloop && puint[0] == 0 && puint[1] == inf)
{
prog[pc] = prog[offs+1] == REloop ? REanystar : REanystarg;
uint change = 2*(1 + uint.sizeof) + 1 + 3*uint.sizeof - 1;
std.array.replaceInPlace(prog, pc + 1,
pc + change + 1, cast(ubyte[])[]);
fixup(prog, pc, change);
pc++;
}
else
{
*cast(uint *)&prog[pc+1] = counter;
counter++;
nCounters = max(nCounters, counter);
pc += 1 + 2*uint.sizeof;
}
break;
case REloop, REloopg:
counter--;
pc += 1 + 3*uint.sizeof;
break;
case REret:
case REanychar:
case REbol:
case REeol:
case REwordboundary:
case REnotwordboundary:
case REdigit:
case REnotdigit:
case REspace:
case REnotspace:
case REword:
case REnotword:
pc++;
break;
case REbackref:
case REchar:
case REichar:
pc += 2;
break;
case REdchar:
case REidchar:
pc += 1 + dchar.sizeof;
break;
case REstring:
case REistring:
len = *cast(size_t *)&prog[pc+1];
assert(len % E.sizeof == 0);
pc += 1 + size_t.sizeof + len;
break;
case REtestbit:
case REbit:
case REnotbit:
pu = cast(ushort *)&prog[pc+1];
len = pu[1];
pc += 1 + 2 * ushort.sizeof + len;
break;
case RErange:
case REnotrange:
len = *cast(uint *)&prog[pc+1];
pc += 1 + uint.sizeof + len;
break;
case REneglookahead:
case RElookahead:
case REor:
case REgoto:
pc += 1 + uint.sizeof;
break;
case REsave:
pc += 1 + uint.sizeof;
break;
default:
assert(0);
}
}
}
/* =================== Compiler ================== */
void parseRegex(String)(String pattern, ref size_t p, OutBuffer buf)
{
auto offset = buf.offset;
for (;;)
{
assert(p <= pattern.length);
if (p == pattern.length)
{
buf.write(REend);
return;
}
switch (pattern[p])
{
case ')':
return;
case '|':
p++;
auto gotooffset = buf.offset;
buf.write(REgoto);
buf.write(cast(uint)0);
immutable uint len1 = cast(uint) (buf.offset - offset);
buf.spread(offset, 1 + uint.sizeof);
gotooffset += 1 + uint.sizeof;
parseRegex(pattern, p, buf);
immutable len2 = cast(uint)
(buf.offset - (gotooffset + 1 + uint.sizeof));
buf.data[offset] = REor;
(cast(uint *)&buf.data[offset + 1])[0] = len1;
(cast(uint *)&buf.data[gotooffset + 1])[0] = len2;
break;
default:
parsePiece(pattern, p, buf);
break;
}
}
}
void parsePiece(String)(String pattern, ref size_t p, OutBuffer buf)
{
uint n;
uint m;
debug(std_regex)
{
auto sss = pattern[p .. pattern.length];
writefln("parsePiece() '%s'", sss);
}
size_t offset = buf.offset;
size_t plength = pattern.length;
parseAtom(pattern, p, buf);
if (p == plength)
return;
switch (pattern[p])
{
case '*':
n = 0;
m = inf;
break;
case '+':
n = 1;
m = inf;
break;
case '?':
n = 0;
m = 1;
break;
case '{': // {n} {n,} {n,m}
p++;
if (p == plength || !isdigit(pattern[p]))
error("badly formed {n,m}");
auto src = pattern[p..$];
n = parse!uint(src);
p = plength - src.length;
if (pattern[p] == '}') // {n}
{
m = n;
break;
}
if (pattern[p] != ',')
error("',' expected in {n,m}");
p++;
if (p == plength)
error("unexpected end of pattern in {n,m}");
if (pattern[p] == /*{*/ '}') // {n,}
{
m = inf;
break;
}
if (!isdigit(pattern[p]))
error("badly formed {n,m}");
src = pattern[p..$];
m = parse!uint(src);
p = plength - src.length;
if (pattern[p] != /*{*/ '}')
error("unmatched '}' in {n,m}");
break;
default:
return;
}
p++;
uint len = cast(uint)(buf.offset - offset);
if (p < plength && pattern[p] == '?')
{
buf.write(REloop);
p++;
}
else
buf.write(REloopg);
buf.write(cast(uint)n);
buf.write(cast(uint)m);
buf.write(cast(uint)len);//set jump back
buf.spread(offset, (1 + 2*uint.sizeof));
buf.data[offset] = REcounter;
*(cast(uint*)&buf.data[offset+1]) = 0;//reserve counter num
*(cast(uint*)&buf.data[offset+5]) = len;
return;
}
void parseAtom(String)(String pattern, ref size_t p, OutBuffer buf)
{
ubyte op;
size_t offset;
E c;
debug(std_regex)
{
auto sss = pattern[p .. pattern.length];
writefln("parseAtom() '%s'", sss);
}
if (p >= pattern.length) return;
c = pattern[p];
switch (c)
{
case '*':
case '+':
case '?':
error("*+? not allowed in atom");
assert(0);
case '(':
p++;
if (pattern[p] != '?')
{
buf.write(REsave);
buf.write(2 + re_nsub);
//handle nested groups
uint end = re_nsub;
re_nsub += 2;
parseRegex(pattern, p, buf);
buf.write(REsave);
buf.write(2 + end + 1);
}
else if (pattern.length > p+1)
{
p++;
switch (pattern[p])
{
case ':':
p++;
parseRegex(pattern, p, buf);
break;
case '=': case '!':
buf.write(pattern[p] == '=' ? RElookahead : REneglookahead);
offset = buf.offset;
buf.write(cast(uint)0); // reserve space for length
p++;
parseRegex(pattern, p, buf);
*cast(uint *)&buf.data[offset] =
cast(uint)(buf.offset - (offset + uint.sizeof)+1);
buf.write(REret);
break;
default:
error("any of :=! expected after '(?'");
assert(0);
}
}
else
{
error("any of :=! expected after '(?'");
assert(0);
}
if (p == pattern.length || pattern[p] != ')')
{
error("')' expected");
assert(0);
}
p++;
break;
case '[':
parseRange(pattern, p, buf);
break;
case '.':
p++;
buf.write(REanychar);
break;
case '^':
p++;
buf.write(REbol);
break;
case '$':
p++;
buf.write(REeol);
break;
case '\\':
p++;
if (p == pattern.length)
{
error("no character past '\\'");
assert(0);
}
c = pattern[p];
switch (c)
{
case 'b': op = REwordboundary; goto Lop;
case 'B': op = REnotwordboundary; goto Lop;
case 'd': op = REdigit; goto Lop;
case 'D': op = REnotdigit; goto Lop;
case 's': op = REspace; goto Lop;
case 'S': op = REnotspace; goto Lop;
case 'w': op = REword; goto Lop;
case 'W': op = REnotword; goto Lop;
Lop:
buf.write(op);
p++;
break;
case 'f':
case 'n':
case 'r':
case 't':
case 'v':
case 'c':
case 'x':
case 'u':
case '0':
c = cast(char)escape(pattern, p);
goto Lbyte;
case '1': case '2': case '3':
case '4': case '5': case '6':
case '7': case '8': case '9':
c -= '1';
if (c < re_nsub)
{
buf.write(REbackref);
buf.write(cast(ubyte)c);
}
else
error("no matching back reference");
p++;
break;
default:
p++;
goto Lbyte;
}
break;
default:
p++;
Lbyte:
op = REchar;
if (attributes & REA.ignoreCase)
{
if (isalpha(c))
{
op = REichar;
c = cast(char)std.ctype.toupper(c);
}
}
if (op == REchar && c <= 0xFF)
{
// Look ahead and see if we can make this into
// an REstring
sizediff_t q = p;
sizediff_t len;
for (; q < pattern.length; ++q)
{
auto qc = pattern[q];
switch (qc)
{
case '{':
case '*':
case '+':
case '?':
if (q == p)
goto Lchar;
q--;
break;
case '(': case ')':
case '|':
case '[': case ']':
case '.': case '^':
case '$': case '\\':
case '}':
break;
default:
continue;
}
break;
}
len = q - p;
if (len > 0)
{
debug(std_regex) writefln("writing string len %d, c = '%s'"
", pattern[p] = '%s'", len+1, c, pattern[p]);
buf.reserve(5 + (1 + len) * E.sizeof);
buf.write((attributes & REA.ignoreCase)
? REistring : REstring);
//auto narrow = to!string(pattern[p .. p + len]);
buf.write(E.sizeof * (len + 1));
//buf.write(narrow.length + 1);
buf.write(c);
buf.write(pattern[p .. p + len]);
//buf.write(narrow);
p = q;
break;
}
}
if (c >= 0x80)
{
debug(std_regex) writefln("dchar");
// Convert to dchar opcode
op = (op == REchar) ? REdchar : REidchar;
buf.write(op);
buf.write(c);
}
else
{
Lchar:
debug(std_regex) writefln("It's an REchar '%s'", c);
buf.write(op);
buf.write(cast(char)c);
}
break;
}
}
struct Range
{
size_t maxc;
size_t maxb;
OutBuffer buf;
ubyte* base;
BitArray bits;
this(OutBuffer buf)
{
this.buf = buf;
if (buf.data.length)
this.base = &buf.data[buf.offset];
}
void setbitmax(size_t u)
{
//writefln("setbitmax(x%x), maxc = x%x", u, maxc);
if (u <= maxc)
return;
maxc = u;
auto b = u / 8;
if (b >= maxb)
{
size_t u2 = base ? base - &buf.data[0] : 0;
buf.fill0(b - maxb + 1);
base = &buf.data[u2];
maxb = b + 1;
//bits = (cast(bit*)this.base)[0 .. maxc + 1];
bits.ptr = cast(size_t*)this.base;
}
bits.len = maxc + 1;
}
void setbit2(size_t u)
{
setbitmax(u + 1);
//writefln("setbit2 [x%02x] |= x%02xn", u >> 3, 1 << (u & 7));
bits[u] = 1;
}
}
int parseRange(String)(in String pattern, ref size_t p, OutBuffer buf)
{
int c;
int c2;
uint i;
uint cmax = 0x7F;
p++;
ubyte op = REbit;
if (p == pattern.length)
goto Lerr;
if (pattern[p] == '^')
{
p++;
op = REnotbit;
if (p == pattern.length)
goto Lerr;
}
buf.write(op);
auto offset = buf.offset;
buf.write(cast(uint)0); // reserve space for length
buf.reserve(128 / 8);
auto r = Range(buf);
if (op == REnotbit)
r.setbit2(0);
switch (pattern[p])
{
case ']':
case '-':
c = pattern[p];
p++;
r.setbit2(c);
break;
default:
break;
}
enum RS { start, rliteral, dash };
auto rs = RS.start;
for (;;)
{
if (p == pattern.length)
goto Lerr;
switch (pattern[p])
{
case ']':
switch (rs)