Debian Codegraph @

libphobos/src/std/regex/internal/backtracking.d

raw
1 /*
2 Implementation of backtracking std.regex engine.
3 Contains both compile-time and run-time versions.
4 */
5 module std.regex.internal.backtracking;
6
7 package(std.regex):
8
9 import core.stdc.stdlib, std.range.primitives, std.traits, std.typecons;
10 import std.regex.internal.ir;
11
12 import core.memory : pureMalloc, pureFree;
13
14 /+
15 BacktrackingMatcher implements backtracking scheme of matching
16 regular expressions.
17 +/
18 @trusted class BacktrackingMatcher(Char, Stream = Input!Char) : Matcher!Char
19 if (is(Char : dchar))
20 {
21 alias DataIndex = Stream.DataIndex;
22 struct State
23 {//top bit in pc is set if saved along with matches
24 DataIndex index;
25 uint pc, counter, infiniteNesting;
26 }
27 static assert(State.sizeof % size_t.sizeof == 0);
28 enum stateSize = State.sizeof / size_t.sizeof;
29 enum initialStack = 1 << 11; // items in a block of segmented stack
30 alias String = const(Char)[];
31 alias RegEx = Regex!Char;
32 alias MatchFn = bool function(BacktrackingMatcher) pure;
33 const RegEx re; // regex program
34 MatchFn nativeFn; // native code for that program
35 // Stream state
36 Stream s;
37 DataIndex index;
38 dchar front;
39 bool exhausted;
40 // Backtracking machine state
41 uint pc, counter;
42 DataIndex lastState = 0; // Top of state stack
43 uint infiniteNesting;
44 size_t[] memory;
45 Trace[] merge;
46 static struct Trace
47 {
48 ulong mask;
49 size_t offset;
50
51 bool mark(size_t idx)
52 {
53 immutable d = idx - offset;
54 if (d < 64) // including overflow
55 {
56 immutable p = mask & (1UL << d);
57 mask |= 1UL << d;
58 return p != 0;
59 }
60 else
61 {
62 offset = idx;
63 mask = 1;
64 return false;
65 }
66 }
67 }
68 //local slice of matches, global for backref
69 Group!DataIndex[] matches, backrefed;
70 size_t _refCount;
71 final:
72
73 override @property ref size_t refCount() { return _refCount; }
74 override @property ref const(RegEx) pattern(){ return re; }
75
76 enum kicked = __traits(hasMember, Stream, "search");
77
78 static size_t initialMemory(const ref RegEx re)
79 {
80 return stackSize(re)*size_t.sizeof + re.hotspotTableSize*Trace.sizeof;
81 }
82
83 static size_t stackSize(const ref RegEx re)
84 {
85 size_t itemSize = stateSize
86 + re.ngroup * (Group!DataIndex).sizeof / size_t.sizeof;
87 return initialStack * itemSize + 2;
88 }
89
90 @property bool atStart(){ return index == 0; }
91
92 @property bool atEnd(){ return index == s.lastIndex && s.atEnd; }
93
94 void next()
95 {
96 if (!s.nextChar(front, index))
97 index = s.lastIndex;
98 }
99
100 void search()
101 {
102 static if (kicked)
103 {
104 if (!s.search(re.kickstart, front, index))
105 {
106 index = s.lastIndex;
107 }
108 }
109 else
110 next();
111 }
112
113 //
114 void newStack()
115 {
116 auto chunk = mallocArray!(size_t)(stackSize(re));
117 chunk[0] = cast(size_t)(memory.ptr);
118 chunk[1] = lastState;
119 memory = chunk[2..$];
120 lastState = 0;
121 }
122
123 bool prevStack()
124 {
125 // pointer to previous block
126 size_t* prev = cast(size_t*) memory.ptr[-2];
127 if (!prev)
128 {
129 // The last segment is freed in RegexMatch
130 return false;
131 }
132 else
133 {
134 import core.memory : pureFree;
135 // memory used in previous block
136 size_t size = memory.ptr[-1];
137 pureFree(memory.ptr-2);
138 memory = prev[0 .. size];
139 lastState = size;
140 return true;
141 }
142 }
143
144 void initExternalMemory(void[] memBlock)
145 {
146 merge = arrayInChunk!(Trace)(re.hotspotTableSize, memBlock);
147 merge[] = Trace.init;
148 memory = cast(size_t[]) memBlock;
149 memory[0] = 0; // hidden pointer
150 memory[1] = 0; // used size
151 memory = memory[2..$];
152 }
153
154 void initialize(ref const RegEx program, Stream stream, void[] memBlock)
155 {
156 s = stream;
157 exhausted = false;
158 initExternalMemory(memBlock);
159 backrefed = null;
160 }
161
162 override void dupTo(Matcher!Char m, void[] memBlock)
163 {
164 auto backtracking = cast(BacktrackingMatcher) m;
165 backtracking.s = s;
166 backtracking.front = front;
167 backtracking.index = index;
168 backtracking.exhausted = exhausted;
169 backtracking.initExternalMemory(memBlock);
170 }
171
172 override Matcher!Char rearm(in Char[] data)
173 {
174 merge[] = Trace.init;
175 exhausted = false;
176 s = Stream(data);
177 next();
178 return this;
179 }
180
181 this(ref const RegEx program, Stream stream, void[] memBlock, dchar ch, DataIndex idx)
182 {
183 _refCount = 1;
184 re = program;
185 nativeFn = null;
186 initialize(program, stream, memBlock);
187 front = ch;
188 index = idx;
189 }
190
191 this(ref const RegEx program, MatchFn func, Stream stream, void[] memBlock)
192 {
193 _refCount = 1;
194 re = program;
195 initialize(program, stream, memBlock);
196 nativeFn = func;
197 next();
198 }
199
200 this(ref const RegEx program, Stream stream, void[] memBlock)
201 {
202 _refCount = 1;
203 re = program;
204 nativeFn = null;
205 initialize(program, stream, memBlock);
206 next();
207 }
208
209 auto fwdMatcher(ref const RegEx re, void[] memBlock)
210 {
211 alias BackMatcher = BacktrackingMatcher!(Char, Stream);
212 auto fwdMatcher = new BackMatcher(re, s, memBlock, front, index);
213 return fwdMatcher;
214 }
215
216 auto bwdMatcher(ref const RegEx re, void[] memBlock)
217 {
218 alias BackMatcher = BacktrackingMatcher!(Char, typeof(s.loopBack(index)));
219 auto fwdMatcher =
220 new BackMatcher(re, s.loopBack(index), memBlock);
221 return fwdMatcher;
222 }
223
224 //
225 int matchFinalize()
226 {
227 immutable start = index;
228 immutable val = matchImpl();
229 if (val)
230 {//stream is updated here
231 matches[0].begin = start;
232 matches[0].end = index;
233 if (!(re.flags & RegexOption.global) || atEnd)
234 exhausted = true;
235 if (start == index)//empty match advances input
236 next();
237 return val;
238 }
239 else
240 return 0;
241 }
242
243 //lookup next match, fill matches with indices into input
244 override int match(Group!DataIndex[] matches)
245 {
246 debug(std_regex_matcher)
247 {
248 writeln("------------------------------------------");
249 }
250 if (exhausted) //all matches collected
251 return false;
252 this.matches = matches;
253 if (re.flags & RegexInfo.oneShot)
254 {
255 exhausted = true;
256 const DataIndex start = index;
257 immutable m = matchImpl();
258 if (m)
259 {
260 matches[0].begin = start;
261 matches[0].end = index;
262 }
263 return m;
264 }
265 static if (kicked)
266 {
267 if (!re.kickstart.empty)
268 {
269 for (;;)
270 {
271 immutable val = matchFinalize();
272 if (val)
273 return val;
274 else
275 {
276 if (atEnd)
277 break;
278 search();
279 if (atEnd)
280 {
281 exhausted = true;
282 return matchFinalize();
283 }
284 }
285 }
286 exhausted = true;
287 return 0; //early return
288 }
289 }
290 //no search available - skip a char at a time
291 for (;;)
292 {
293 immutable val = matchFinalize();
294 if (val)
295 return val;
296 else
297 {
298 if (atEnd)
299 break;
300 next();
301 if (atEnd)
302 {
303 exhausted = true;
304 return matchFinalize();
305 }
306 }
307 }
308 exhausted = true;
309 return 0;
310 }
311
312 /+
313 match subexpression against input,
314 results are stored in matches
315 +/
316 int matchImpl() pure
317 {
318 if (nativeFn)
319 {
320 debug(std_regex_ctr) writeln("using C-T matcher");
321 return nativeFn(this);
322 }
323 else
324 {
325 pc = 0;
326 counter = 0;
327 lastState = 0;
328 infiniteNesting = 0;
329 matches[] = Group!DataIndex.init;
330 auto start = s._index;
331 debug(std_regex_matcher)
332 writeln("Try match starting at ", s[index .. s.lastIndex]);
333 for (;;)
334 {
335 debug(std_regex_matcher)
336 writefln("PC: %s\tCNT: %s\t%s \tfront: %s src: %s",
337 pc, counter, disassemble(re.ir, pc, re.dict),
338 front, s._index);
339 switch (re.ir[pc].code)
340 {
341 case IR.OrChar://assumes IRL!(OrChar) == 1
342 if (atEnd)
343 goto L_backtrack;
344 uint len = re.ir[pc].sequence;
345 uint end = pc + len;
346 if (re.ir[pc].data != front && re.ir[pc+1].data != front)
347 {
348 for (pc = pc+2; pc < end; pc++)
349 if (re.ir[pc].data == front)
350 break;
351 if (pc == end)
352 goto L_backtrack;
353 }
354 pc = end;
355 next();
356 break;
357 case IR.Char:
358 if (atEnd || front != re.ir[pc].data)
359 goto L_backtrack;
360 pc += IRL!(IR.Char);
361 next();
362 break;
363 case IR.Any:
364 if (atEnd)
365 goto L_backtrack;
366 pc += IRL!(IR.Any);
367 next();
368 break;
369 case IR.CodepointSet:
370 if (atEnd || !re.charsets[re.ir[pc].data].scanFor(front))
371 goto L_backtrack;
372 next();
373 pc += IRL!(IR.CodepointSet);
374 break;
375 case IR.Trie:
376 if (atEnd || !re.matchers[re.ir[pc].data][front])
377 goto L_backtrack;
378 next();
379 pc += IRL!(IR.Trie);
380 break;
381 case IR.Wordboundary:
382 dchar back;
383 DataIndex bi;
384 //at start & end of input
385 if (atStart && wordMatcher[front])
386 {
387 pc += IRL!(IR.Wordboundary);
388 break;
389 }
390 else if (atEnd && s.loopBack(index).nextChar(back, bi)
391 && wordMatcher[back])
392 {
393 pc += IRL!(IR.Wordboundary);
394 break;
395 }
396 else if (s.loopBack(index).nextChar(back, bi))
397 {
398 immutable af = wordMatcher[front];
399 immutable ab = wordMatcher[back];
400 if (af ^ ab)
401 {
402 pc += IRL!(IR.Wordboundary);
403 break;
404 }
405 }
406 goto L_backtrack;
407 case IR.Notwordboundary:
408 dchar back;
409 DataIndex bi;
410 //at start & end of input
411 if (atStart && wordMatcher[front])
412 goto L_backtrack;
413 else if (atEnd && s.loopBack(index).nextChar(back, bi)
414 && wordMatcher[back])
415 goto L_backtrack;
416 else if (s.loopBack(index).nextChar(back, bi))
417 {
418 immutable af = wordMatcher[front];
419 immutable ab = wordMatcher[back];
420 if (af ^ ab)
421 goto L_backtrack;
422 }
423 pc += IRL!(IR.Wordboundary);
424 break;
425 case IR.Bof:
426 if (atStart)
427 pc += IRL!(IR.Bol);
428 else
429 goto L_backtrack;
430 break;
431 case IR.Bol:
432 dchar back;
433 DataIndex bi;
434 if (atStart)
435 pc += IRL!(IR.Bol);
436 else if (s.loopBack(index).nextChar(back,bi)
437 && endOfLine(back, front == '\n'))
438 {
439 pc += IRL!(IR.Bol);
440 }
441 else
442 goto L_backtrack;
443 break;
444 case IR.Eof:
445 if (atEnd)
446 pc += IRL!(IR.Eol);
447 else
448 goto L_backtrack;
449 break;
450 case IR.Eol:
451 dchar back;
452 DataIndex bi;
453 debug(std_regex_matcher) writefln("EOL (front 0x%x) %s", front, s[index .. s.lastIndex]);
454 //no matching inside \r\n
455 if (atEnd || (endOfLine(front, s.loopBack(index).nextChar(back,bi)
456 && back == '\r')))
457 {
458 pc += IRL!(IR.Eol);
459 }
460 else
461 goto L_backtrack;
462 break;
463 case IR.InfiniteStart, IR.InfiniteQStart:
464 pc += re.ir[pc].data + IRL!(IR.InfiniteStart);
465 //now pc is at end IR.Infinite(Q)End
466 uint len = re.ir[pc].data;
467 if (re.ir[pc].code == IR.InfiniteEnd)
468 {
469 pushState(pc+IRL!(IR.InfiniteEnd), counter);
470 pc -= len;
471 }
472 else
473 {
474 pushState(pc - len, counter);
475 pc += IRL!(IR.InfiniteEnd);
476 }
477 break;
478 case IR.InfiniteBloomStart:
479 pc += re.ir[pc].data + IRL!(IR.InfiniteBloomStart);
480 //now pc is at end IR.InfiniteBloomEnd
481 immutable len = re.ir[pc].data;
482 immutable filterIdx = re.ir[pc+2].raw;
483 if (re.filters[filterIdx][front])
484 pushState(pc+IRL!(IR.InfiniteBloomEnd), counter);
485 pc -= len;
486 break;
487 case IR.RepeatStart, IR.RepeatQStart:
488 pc += re.ir[pc].data + IRL!(IR.RepeatStart);
489 break;
490 case IR.RepeatEnd:
491 case IR.RepeatQEnd:
492 if (merge[re.ir[pc + 1].raw+counter].mark(index))
493 {
494 // merged!
495 goto L_backtrack;
496 }
497 //len, step, min, max
498 immutable len = re.ir[pc].data;
499 immutable step = re.ir[pc+2].raw;
500 immutable min = re.ir[pc+3].raw;
501 immutable max = re.ir[pc+4].raw;
502 if (counter < min)
503 {
504 counter += step;
505 pc -= len;
506 }
507 else if (counter < max)
508 {
509 if (re.ir[pc].code == IR.RepeatEnd)
510 {
511 pushState(pc + IRL!(IR.RepeatEnd), counter%step);
512 counter += step;
513 pc -= len;
514 }
515 else
516 {
517 pushState(pc - len, counter + step);
518 counter = counter%step;
519 pc += IRL!(IR.RepeatEnd);
520 }
521 }
522 else
523 {
524 counter = counter%step;
525 pc += IRL!(IR.RepeatEnd);
526 }
527 break;
528 case IR.InfiniteEnd:
529 case IR.InfiniteQEnd:
530 debug(std_regex_matcher) writeln("Infinited nesting:", infiniteNesting);
531 if (merge[re.ir[pc + 1].raw+counter].mark(index))
532 {
533 // merged!
534 goto L_backtrack;
535 }
536 immutable len = re.ir[pc].data;
537 if (re.ir[pc].code == IR.InfiniteEnd)
538 {
539 pushState(pc + IRL!(IR.InfiniteEnd), counter);
540 pc -= len;
541 }
542 else
543 {
544 pushState(pc-len, counter);
545 pc += IRL!(IR.InfiniteEnd);
546 }
547 break;
548 case IR.InfiniteBloomEnd:
549 debug(std_regex_matcher) writeln("Infinited nesting:", infiniteNesting);
550 if (merge[re.ir[pc + 1].raw+counter].mark(index))
551 {
552 // merged!
553 goto L_backtrack;
554 }
555 immutable len = re.ir[pc].data;
556 immutable filterIdx = re.ir[pc+2].raw;
557 if (re.filters[filterIdx][front])
558 {
559 infiniteNesting--;
560 pushState(pc + IRL!(IR.InfiniteBloomEnd), counter);
561 infiniteNesting++;
562 }
563 pc -= len;
564 break;
565 case IR.OrEnd:
566 if (merge[re.ir[pc + 1].raw+counter].mark(index))
567 {
568 // merged!
569 goto L_backtrack;
570 }
571 pc += IRL!(IR.OrEnd);
572 break;
573 case IR.OrStart:
574 pc += IRL!(IR.OrStart);
575 goto case;
576 case IR.Option:
577 immutable len = re.ir[pc].data;
578 if (re.ir[pc+len].code == IR.GotoEndOr)//not a last one
579 {
580 pushState(pc + len + IRL!(IR.Option), counter); //remember 2nd branch
581 }
582 pc += IRL!(IR.Option);
583 break;
584 case IR.GotoEndOr:
585 pc = pc + re.ir[pc].data + IRL!(IR.GotoEndOr);
586 break;
587 case IR.GroupStart:
588 immutable n = re.ir[pc].data;
589 matches[n].begin = index;
590 debug(std_regex_matcher) writefln("IR group #%u starts at %u", n, index);
591 pc += IRL!(IR.GroupStart);
592 break;
593 case IR.GroupEnd:
594 immutable n = re.ir[pc].data;
595 matches[n].end = index;
596 debug(std_regex_matcher) writefln("IR group #%u ends at %u", n, index);
597 pc += IRL!(IR.GroupEnd);
598 break;
599 case IR.LookaheadStart:
600 case IR.NeglookaheadStart:
601 immutable len = re.ir[pc].data;
602 auto save = index;
603 immutable ms = re.ir[pc+1].raw, me = re.ir[pc+2].raw;
604 auto mem = pureMalloc(initialMemory(re))[0 .. initialMemory(re)];
605 scope(exit) pureFree(mem.ptr);
606 auto slicedRe = re.withCode(re.ir[
607 pc+IRL!(IR.LookaheadStart) .. pc+IRL!(IR.LookaheadStart)+len+IRL!(IR.LookaheadEnd)
608 ]);
609 static if (Stream.isLoopback)
610 {
611 auto matcher = bwdMatcher(slicedRe, mem);
612 }
613 else
614 {
615 auto matcher = fwdMatcher(slicedRe, mem);
616 }
617 matcher.matches = matches[ms .. me];
618 matcher.backrefed = backrefed.empty ? matches : backrefed;
619 immutable match = (matcher.matchImpl() != 0) ^ (re.ir[pc].code == IR.NeglookaheadStart);
620 s.reset(save);
621 next();
622 if (!match)
623 goto L_backtrack;
624 else
625 {
626 pc += IRL!(IR.LookaheadStart)+len+IRL!(IR.LookaheadEnd);
627 }
628 break;
629 case IR.LookbehindStart:
630 case IR.NeglookbehindStart:
631 immutable len = re.ir[pc].data;
632 immutable ms = re.ir[pc+1].raw, me = re.ir[pc+2].raw;
633 auto mem = pureMalloc(initialMemory(re))[0 .. initialMemory(re)];
634 scope(exit) pureFree(mem.ptr);
635 auto slicedRe = re.withCode(re.ir[
636 pc + IRL!(IR.LookbehindStart) .. pc + IRL!(IR.LookbehindStart) + len + IRL!(IR.LookbehindEnd)
637 ]);
638 static if (Stream.isLoopback)
639 {
640 alias Matcher = BacktrackingMatcher!(Char, Stream);
641 auto matcher = new Matcher(slicedRe, s, mem, front, index);
642 }
643 else
644 {
645 alias Matcher = BacktrackingMatcher!(Char, typeof(s.loopBack(index)));
646 auto matcher = new Matcher(slicedRe, s.loopBack(index), mem);
647 }
648 matcher.matches = matches[ms .. me];
649 matcher.backrefed = backrefed.empty ? matches : backrefed;
650 immutable match = (matcher.matchImpl() != 0) ^ (re.ir[pc].code == IR.NeglookbehindStart);
651 if (!match)
652 goto L_backtrack;
653 else
654 {
655 pc += IRL!(IR.LookbehindStart)+len+IRL!(IR.LookbehindEnd);
656 }
657 break;
658 case IR.Backref:
659 immutable n = re.ir[pc].data;
660 auto referenced = re.ir[pc].localRef
661 ? s[matches[n].begin .. matches[n].end]
662 : s[backrefed[n].begin .. backrefed[n].end];
663 while (!atEnd && !referenced.empty && front == referenced.front)
664 {
665 next();
666 referenced.popFront();
667 }
668 if (referenced.empty)
669 pc++;
670 else
671 goto L_backtrack;
672 break;
673 case IR.Nop:
674 pc += IRL!(IR.Nop);
675 break;
676 case IR.LookaheadEnd:
677 case IR.NeglookaheadEnd:
678 case IR.LookbehindEnd:
679 case IR.NeglookbehindEnd:
680 case IR.End:
681 // cleanup stale stack blocks if any
682 while (prevStack()) {}
683 return re.ir[pc].data;
684 default:
685 debug(std_regex_debug) printBytecode(re.ir[0..$]);
686 assert(0);
687 L_backtrack:
688 if (!popState())
689 {
690 s.reset(start);
691 return 0;
692 }
693 }
694 }
695 }
696 assert(0);
697 }
698
699 @property size_t stackAvail()
700 {
701 return memory.length - lastState;
702 }
703
704 void stackPush(T)(T val)
705 if (!isDynamicArray!T)
706 {
707 *cast(T*)&memory[lastState] = val;
708 enum delta = (T.sizeof+size_t.sizeof/2)/size_t.sizeof;
709 lastState += delta;
710 debug(std_regex_matcher) writeln("push element SP= ", lastState);
711 }
712
713 void stackPush(T)(T[] val)
714 {
715 static assert(T.sizeof % size_t.sizeof == 0);
716 (cast(T*)&memory[lastState])[0 .. val.length]
717 = val[0..$];
718 lastState += val.length*(T.sizeof/size_t.sizeof);
719 debug(std_regex_matcher) writeln("push array SP= ", lastState);
720 }
721
722 void stackPop(T)(ref T val)
723 if (!isDynamicArray!T)
724 {
725 enum delta = (T.sizeof+size_t.sizeof/2)/size_t.sizeof;
726 lastState -= delta;
727 val = *cast(T*)&memory[lastState];
728 debug(std_regex_matcher) writeln("pop element SP= ", lastState);
729 }
730
731 void stackPop(T)(T[] val)
732 {
733 stackPop(val); // call ref version
734 }
735 void stackPop(T)(ref T[] val)
736 {
737 lastState -= val.length*(T.sizeof/size_t.sizeof);
738 val[0..$] = (cast(T*)&memory[lastState])[0 .. val.length];
739 debug(std_regex_matcher) writeln("pop array SP= ", lastState);
740 }
741 //helper function, saves engine state
742 void pushState(uint pc, uint counter)
743 {
744 if (stateSize + 2 * matches.length > stackAvail)
745 {
746 newStack();
747 }
748 *cast(State*)&memory[lastState] =
749 State(index, pc, counter, infiniteNesting);
750 lastState += stateSize;
751 memory[lastState .. lastState + 2 * matches.length] = (cast(size_t[]) matches)[];
752 lastState += 2*matches.length;
753 debug(std_regex_matcher)
754 writefln("Saved(pc=%s) front: %s src: %s",
755 pc, front, s[index .. s.lastIndex]);
756 }
757
758 //helper function, restores engine state
759 bool popState()
760 {
761 if (!lastState && !prevStack())
762 return false;
763 lastState -= 2*matches.length;
764 auto pm = cast(size_t[]) matches;
765 pm[] = memory[lastState .. lastState + 2 * matches.length];
766 lastState -= stateSize;
767 State* state = cast(State*)&memory[lastState];
768 index = state.index;
769 pc = state.pc;
770 counter = state.counter;
771 infiniteNesting = state.infiniteNesting;
772 debug(std_regex_matcher)
773 {
774 writefln("Restored matches", front, s[index .. s.lastIndex]);
775 foreach (i, m; matches)
776 writefln("Sub(%d) : %s..%s", i, m.begin, m.end);
777 }
778 s.reset(index);
779 next();
780 debug(std_regex_matcher)
781 writefln("Backtracked (pc=%s) front: %s src: %s",
782 pc, front, s[index .. s.lastIndex]);
783 return true;
784 }
785 }
786
787 //very shitty string formatter, $$ replaced with next argument converted to string
788 @trusted string ctSub( U...)(string format, U args)
789 {
790 import std.conv : to;
791 bool seenDollar;
792 foreach (i, ch; format)
793 {
794 if (ch == '$')
795 {
796 if (seenDollar)
797 {
798 static if (args.length > 0)
799 {
800 return format[0 .. i - 1] ~ to!string(args[0])
801 ~ ctSub(format[i + 1 .. $], args[1 .. $]);
802 }
803 else
804 assert(0);
805 }
806 else
807 seenDollar = true;
808 }
809 else
810 seenDollar = false;
811
812 }
813 return format;
814 }
815
816 struct CtContext
817 {
818 import std.conv : to, text;
819 //dirty flags
820 bool counter;
821 //to mark the portion of matches to save
822 int match, total_matches;
823 int reserved;
824 const(CodepointInterval)[][] charsets;
825
826
827 //state of codegenerator
828 static struct CtState
829 {
830 string code;
831 int addr;
832 }
833
834 this(Char)(ref const Regex!Char re)
835 {
836 match = 1;
837 reserved = 1; //first match is skipped
838 total_matches = re.ngroup;
839 foreach (ref set; re.charsets)
840 {
841 charsets ~= set.intervals;
842 }
843 }
844
845 CtContext lookaround(uint s, uint e)
846 {
847 CtContext ct;
848 ct.total_matches = e - s;
849 ct.match = 1;
850 return ct;
851 }
852
853 //restore state having current context
854 string restoreCode()
855 {
856 string text;
857 //stack is checked in L_backtrack
858 text ~= counter
859 ? "
860 stackPop(counter);"
861 : "
862 counter = 0;";
863 if (match < total_matches)
864 {
865 text ~= ctSub("
866 stackPop(matches[$$..$$]);", reserved, match);
867 text ~= ctSub("
868 matches[$$..$] = typeof(matches[0]).init;", match);
869 }
870 else
871 text ~= ctSub("
872 stackPop(matches[$$..$]);", reserved);
873 return text;
874 }
875
876 //save state having current context
877 string saveCode(uint pc, string count_expr="counter")
878 {
879 string text = ctSub("
880 if (stackAvail < $$*(Group!(DataIndex)).sizeof/size_t.sizeof + $$)
881 {
882 newStack();
883 }", match - reserved, cast(int) counter + 2);
884 if (match < total_matches)
885 text ~= ctSub("
886 stackPush(matches[$$..$$]);", reserved, match);
887 else
888 text ~= ctSub("
889 stackPush(matches[$$..$]);", reserved);
890 text ~= counter ? ctSub("
891 stackPush($$);", count_expr) : "";
892 text ~= ctSub("
893 stackPush(index); stackPush($$); \n", pc);
894 return text;
895 }
896
897 //
898 CtState ctGenBlock(const(Bytecode)[] ir, int addr)
899 {
900 CtState result;
901 result.addr = addr;
902 while (!ir.empty)
903 {
904 auto n = ctGenGroup(ir, result.addr);
905 result.code ~= n.code;
906 result.addr = n.addr;
907 }
908 return result;
909 }
910
911 //
912 CtState ctGenGroup(ref const(Bytecode)[] ir, int addr)
913 {
914 import std.algorithm.comparison : max;
915 auto bailOut = "goto L_backtrack;";
916 auto nextInstr = ctSub("goto case $$;", addr+1);
917 CtState r;
918 assert(!ir.empty);
919 switch (ir[0].code)
920 {
921 case IR.InfiniteStart, IR.InfiniteBloomStart,IR.InfiniteQStart, IR.RepeatStart, IR.RepeatQStart:
922 immutable infLoop =
923 ir[0].code == IR.InfiniteStart || ir[0].code == IR.InfiniteQStart ||
924 ir[0].code == IR.InfiniteBloomStart;
925
926 counter = counter ||
927 ir[0].code == IR.RepeatStart || ir[0].code == IR.RepeatQStart;
928 immutable len = ir[0].data;
929 auto nir = ir[ir[0].length .. ir[0].length+len];
930 r = ctGenBlock(nir, addr+1);
931 //start/end codegen
932 //r.addr is at last test+ jump of loop, addr+1 is body of loop
933 nir = ir[ir[0].length + len .. $];
934 r.code = ctGenFixupCode(ir[0 .. ir[0].length], addr, r.addr) ~ r.code;
935 r.code ~= ctGenFixupCode(nir, r.addr, addr+1);
936 r.addr += 2; //account end instruction + restore state
937 ir = nir;
938 break;
939 case IR.OrStart:
940 immutable len = ir[0].data;
941 auto nir = ir[ir[0].length .. ir[0].length+len];
942 r = ctGenAlternation(nir, addr);
943 ir = ir[ir[0].length + len .. $];
944 assert(ir[0].code == IR.OrEnd);
945 ir = ir[ir[0].length..$];
946 break;
947 case IR.LookaheadStart:
948 case IR.NeglookaheadStart:
949 case IR.LookbehindStart:
950 case IR.NeglookbehindStart:
951 immutable len = ir[0].data;
952 immutable behind = ir[0].code == IR.LookbehindStart || ir[0].code == IR.NeglookbehindStart;
953 immutable negative = ir[0].code == IR.NeglookaheadStart || ir[0].code == IR.NeglookbehindStart;
954 string fwdType = "typeof(fwdMatcher(re, []))";
955 string bwdType = "typeof(bwdMatcher(re, []))";
956 string fwdCreate = "fwdMatcher(re, mem)";
957 string bwdCreate = "bwdMatcher(re, mem)";
958 immutable start = IRL!(IR.LookbehindStart);
959 immutable end = IRL!(IR.LookbehindStart)+len+IRL!(IR.LookaheadEnd);
960 CtContext context = lookaround(ir[1].raw, ir[2].raw); //split off new context
961 auto slice = ir[start .. end];
962 r.code ~= ctSub(`
963 case $$: //fake lookaround "atom"
964 static if (typeof(matcher.s).isLoopback)
965 alias Lookaround = $$;
966 else
967 alias Lookaround = $$;
968 static bool matcher_$$(Lookaround matcher) @trusted
969 {
970 //(neg)lookaround piece start
971 $$
972 //(neg)lookaround piece ends
973 }
974 auto save = index;
975 auto mem = pureMalloc(initialMemory(re))[0 .. initialMemory(re)];
976 scope(exit) pureFree(mem.ptr);
977 static if (typeof(matcher.s).isLoopback)
978 auto lookaround = $$;
979 else
980 auto lookaround = $$;
981 lookaround.matches = matches[$$..$$];
982 lookaround.backrefed = backrefed.empty ? matches : backrefed;
983 lookaround.nativeFn = &matcher_$$; //hookup closure's binary code
984 int match = $$;
985 s.reset(save);
986 next();
987 if (match)
988 $$
989 else
990 $$`, addr,
991 behind ? fwdType : bwdType, behind ? bwdType : fwdType,
992 addr, context.ctGenRegEx(slice),
993 behind ? fwdCreate : bwdCreate, behind ? bwdCreate : fwdCreate,
994 ir[1].raw, ir[2].raw, //start - end of matches slice
995 addr,
996 negative ? "!lookaround.matchImpl()" : "lookaround.matchImpl()",
997 nextInstr, bailOut);
998 ir = ir[end .. $];
999 r.addr = addr + 1;
1000 break;
1001 case IR.LookaheadEnd: case IR.NeglookaheadEnd:
1002 case IR.LookbehindEnd: case IR.NeglookbehindEnd:
1003 ir = ir[IRL!(IR.LookaheadEnd) .. $];
1004 r.addr = addr;
1005 break;
1006 default:
1007 assert(ir[0].isAtom, text(ir[0].mnemonic));
1008 r = ctGenAtom(ir, addr);
1009 }
1010 return r;
1011 }
1012
1013 //generate source for bytecode contained in OrStart ... OrEnd
1014 CtState ctGenAlternation(const(Bytecode)[] ir, int addr)
1015 {
1016 CtState[] pieces;
1017 CtState r;
1018 enum optL = IRL!(IR.Option);
1019 for (;;)
1020 {
1021 assert(ir[0].code == IR.Option);
1022 auto len = ir[0].data;
1023 if (optL+len < ir.length && ir[optL+len].code == IR.Option)//not a last option
1024 {
1025 auto nir = ir[optL .. optL+len-IRL!(IR.GotoEndOr)];
1026 r = ctGenBlock(nir, addr+2);//space for Option + restore state
1027 //r.addr+1 to account GotoEndOr at end of branch
1028 r.code = ctGenFixupCode(ir[0 .. ir[0].length], addr, r.addr+1) ~ r.code;
1029 addr = r.addr+1;//leave space for GotoEndOr
1030 pieces ~= r;
1031 ir = ir[optL + len .. $];
1032 }
1033 else
1034 {
1035 pieces ~= ctGenBlock(ir[optL..$], addr);
1036 addr = pieces[$-1].addr;
1037 break;
1038 }
1039 }
1040 r = pieces[0];
1041 for (uint i = 1; i < pieces.length; i++)
1042 {
1043 r.code ~= ctSub(`
1044 case $$:
1045 goto case $$; `, pieces[i-1].addr, addr);
1046 r.code ~= pieces[i].code;
1047 }
1048 r.addr = addr;
1049 return r;
1050 }
1051
1052 // generate fixup code for instruction in ir,
1053 // fixup means it has an alternative way for control flow
1054 string ctGenFixupCode(const(Bytecode)[] ir, int addr, int fixup)
1055 {
1056 return ctGenFixupCode(ir, addr, fixup); // call ref Bytecode[] version
1057 }
1058 string ctGenFixupCode(ref const(Bytecode)[] ir, int addr, int fixup)
1059 {
1060 string r;
1061 string testCode;
1062 r = ctSub(`
1063 case $$: debug(std_regex_matcher) writeln("#$$");`,
1064 addr, addr);
1065 switch (ir[0].code)
1066 {
1067 case IR.InfiniteStart, IR.InfiniteQStart, IR.InfiniteBloomStart:
1068 r ~= ctSub( `
1069 goto case $$;`, fixup);
1070 ir = ir[ir[0].length..$];
1071 break;
1072 case IR.InfiniteEnd:
1073 testCode = ctQuickTest(ir[IRL!(IR.InfiniteEnd) .. $],addr + 1);
1074 r ~= ctSub( `
1075 if (merge[$$+counter].mark(index))
1076 {
1077 // merged!
1078 goto L_backtrack;
1079 }
1080
1081 $$
1082 {
1083 $$
1084 }
1085 goto case $$;
1086 case $$: //restore state and go out of loop
1087 $$
1088 goto case;`, ir[1].raw, testCode, saveCode(addr+1), fixup,
1089 addr+1, restoreCode());
1090 ir = ir[ir[0].length..$];
1091 break;
1092 case IR.InfiniteBloomEnd:
1093 //TODO: check bloom filter and skip on failure
1094 testCode = ctQuickTest(ir[IRL!(IR.InfiniteBloomEnd) .. $],addr + 1);
1095 r ~= ctSub( `
1096 if (merge[$$+counter].mark(index))
1097 {
1098 // merged!
1099 goto L_backtrack;
1100 }
1101
1102 $$
1103 {
1104 $$
1105 }
1106 goto case $$;
1107 case $$: //restore state and go out of loop
1108 $$
1109 goto case;`, ir[1].raw, testCode, saveCode(addr+1), fixup,
1110 addr+1, restoreCode());
1111 ir = ir[ir[0].length..$];
1112 break;
1113 case IR.InfiniteQEnd:
1114 testCode = ctQuickTest(ir[IRL!(IR.InfiniteEnd) .. $],addr + 1);
1115 auto altCode = testCode.length ? ctSub("else goto case $$;", fixup) : "";
1116 r ~= ctSub( `
1117 if (merge[$$+counter].mark(index))
1118 {
1119 // merged!
1120 goto L_backtrack;
1121 }
1122
1123 $$
1124 {
1125 $$
1126 goto case $$;
1127 }
1128 $$
1129 case $$://restore state and go inside loop
1130 $$
1131 goto case $$;`, ir[1].raw,
1132 testCode, saveCode(addr+1), addr+2, altCode,
1133 addr+1, restoreCode(), fixup);
1134 ir = ir[ir[0].length..$];
1135 break;
1136 case IR.RepeatStart, IR.RepeatQStart:
1137 r ~= ctSub( `
1138 goto case $$;`, fixup);
1139 ir = ir[ir[0].length..$];
1140 break;
1141 case IR.RepeatEnd, IR.RepeatQEnd:
1142 //len, step, min, max
1143 immutable len = ir[0].data;
1144 immutable step = ir[2].raw;
1145 immutable min = ir[3].raw;
1146 immutable max = ir[4].raw;
1147 r ~= ctSub(`
1148 if (merge[$$+counter].mark(index))
1149 {
1150 // merged!
1151 goto L_backtrack;
1152 }
1153 if (counter < $$)
1154 {
1155 debug(std_regex_matcher) writeln("RepeatEnd min case pc=", $$);
1156 counter += $$;
1157 goto case $$;
1158 }`, ir[1].raw, min, addr, step, fixup);
1159 if (ir[0].code == IR.RepeatEnd)
1160 {
1161 string counter_expr = ctSub("counter % $$", step);
1162 r ~= ctSub(`
1163 else if (counter < $$)
1164 {
1165 $$
1166 counter += $$;
1167 goto case $$;
1168 }`, max, saveCode(addr+1, counter_expr), step, fixup);
1169 }
1170 else
1171 {
1172 string counter_expr = ctSub("counter % $$", step);
1173 r ~= ctSub(`
1174 else if (counter < $$)
1175 {
1176 $$
1177 counter = counter % $$;
1178 goto case $$;
1179 }`, max, saveCode(addr+1,counter_expr), step, addr+2);
1180 }
1181 r ~= ctSub(`
1182 else
1183 {
1184 counter = counter % $$;
1185 goto case $$;
1186 }
1187 case $$: //restore state
1188 $$
1189 goto case $$;`, step, addr+2, addr+1, restoreCode(),
1190 ir[0].code == IR.RepeatEnd ? addr+2 : fixup );
1191 ir = ir[ir[0].length..$];
1192 break;
1193 case IR.Option:
1194 r ~= ctSub( `
1195 {
1196 $$
1197 }
1198 goto case $$;
1199 case $$://restore thunk to go to the next group
1200 $$
1201 goto case $$;`, saveCode(addr+1), addr+2,
1202 addr+1, restoreCode(), fixup);
1203 ir = ir[ir[0].length..$];
1204 break;
1205 default:
1206 assert(0, text(ir[0].mnemonic));
1207 }
1208 return r;
1209 }
1210
1211
1212 string ctQuickTest(const(Bytecode)[] ir, int id)
1213 {
1214 uint pc = 0;
1215 while (pc < ir.length && ir[pc].isAtom)
1216 {
1217 if (ir[pc].code == IR.GroupStart || ir[pc].code == IR.GroupEnd)
1218 {
1219 pc++;
1220 }
1221 else if (ir[pc].code == IR.Backref)
1222 break;
1223 else
1224 {
1225 auto code = ctAtomCode(ir[pc..$], -1);
1226 return ctSub(`
1227 int test_$$()
1228 {
1229 $$ //$$
1230 }
1231 if (test_$$() >= 0)`, id, code.ptr ? code : "return 0;",
1232 ir[pc].mnemonic, id);
1233 }
1234 }
1235 return "";
1236 }
1237
1238 //process & generate source for simple bytecodes at front of ir using address addr
1239 CtState ctGenAtom(ref const(Bytecode)[] ir, int addr)
1240 {
1241 CtState result;
1242 result.code = ctAtomCode(ir, addr);
1243 ir.popFrontN(ir[0].code == IR.OrChar ? ir[0].sequence : ir[0].length);
1244 result.addr = addr + 1;
1245 return result;
1246 }
1247
1248 //D code for atom at ir using address addr, addr < 0 means quickTest
1249 string ctAtomCode(const(Bytecode)[] ir, int addr)
1250 {
1251 string code;
1252 string bailOut, nextInstr;
1253 if (addr < 0)
1254 {
1255 bailOut = "return -1;";
1256 nextInstr = "return 0;";
1257 }
1258 else
1259 {
1260 bailOut = "goto L_backtrack;";
1261 nextInstr = ctSub("goto case $$;", addr+1);
1262 code ~= ctSub( `
1263 case $$: debug(std_regex_matcher) writeln("#$$");
1264 `, addr, addr);
1265 }
1266 switch (ir[0].code)
1267 {
1268 case IR.OrChar://assumes IRL!(OrChar) == 1
1269 code ~= ctSub(`
1270 if (atEnd)
1271 $$`, bailOut);
1272 immutable len = ir[0].sequence;
1273 for (uint i = 0; i < len; i++)
1274 {
1275 code ~= ctSub( `
1276 if (front == $$)
1277 {
1278 $$
1279 $$
1280 }`, ir[i].data, addr >= 0 ? "next();" :"", nextInstr);
1281 }
1282 code ~= ctSub( `
1283 $$`, bailOut);
1284 break;
1285 case IR.Char:
1286 code ~= ctSub( `
1287 if (atEnd || front != $$)
1288 $$
1289 $$
1290 $$`, ir[0].data, bailOut, addr >= 0 ? "next();" :"", nextInstr);
1291 break;
1292 case IR.Any:
1293 code ~= ctSub( `
1294 if (atEnd || (!(re.flags & RegexOption.singleline)
1295 && (front == '\r' || front == '\n')))
1296 $$
1297 $$
1298 $$`, bailOut, addr >= 0 ? "next();" :"",nextInstr);
1299 break;
1300 case IR.CodepointSet:
1301 if (charsets.length)
1302 {
1303 string name = `func_`~to!string(addr+1);
1304 string funcCode = CodepointSet.toSourceCode(charsets[ir[0].data], name);
1305 code ~= ctSub( `
1306 static $$
1307 if (atEnd || !$$(front))
1308 $$
1309 $$
1310 $$`, funcCode, name, bailOut, addr >= 0 ? "next();" :"", nextInstr);
1311 }
1312 else
1313 code ~= ctSub( `
1314 if (atEnd || !re.charsets[$$].scanFor(front))
1315 $$
1316 $$
1317 $$`, ir[0].data, bailOut, addr >= 0 ? "next();" :"", nextInstr);
1318 break;
1319 case IR.Trie:
1320 if (charsets.length && charsets[ir[0].data].length <= 8)
1321 goto case IR.CodepointSet;
1322 code ~= ctSub( `
1323 if (atEnd || !re.matchers[$$][front])
1324 $$
1325 $$
1326 $$`, ir[0].data, bailOut, addr >= 0 ? "next();" :"", nextInstr);
1327 break;
1328 case IR.Wordboundary:
1329 code ~= ctSub( `
1330 dchar back;
1331 DataIndex bi;
1332 if (atStart && wordMatcher[front])
1333 {
1334 $$
1335 }
1336 else if (atEnd && s.loopBack(index).nextChar(back, bi)
1337 && wordMatcher[back])
1338 {
1339 $$
1340 }
1341 else if (s.loopBack(index).nextChar(back, bi))
1342 {
1343 bool af = wordMatcher[front];
1344 bool ab = wordMatcher[back];
1345 if (af ^ ab)
1346 {
1347 $$
1348 }
1349 }
1350 $$`, nextInstr, nextInstr, nextInstr, bailOut);
1351 break;
1352 case IR.Notwordboundary:
1353 code ~= ctSub( `
1354 dchar back;
1355 DataIndex bi;
1356 //at start & end of input
1357 if (atStart && wordMatcher[front])
1358 $$
1359 else if (atEnd && s.loopBack(index).nextChar(back, bi)
1360 && wordMatcher[back])
1361 $$
1362 else if (s.loopBack(index).nextChar(back, bi))
1363 {
1364 bool af = wordMatcher[front];
1365 bool ab = wordMatcher[back];
1366 if (af ^ ab)
1367 $$
1368 }
1369 $$`, bailOut, bailOut, bailOut, nextInstr);
1370
1371 break;
1372 case IR.Bol:
1373 code ~= ctSub(`
1374 dchar back;
1375 DataIndex bi;
1376 if (atStart || (s.loopBack(index).nextChar(back,bi)
1377 && endOfLine(back, front == '\n')))
1378 {
1379 debug(std_regex_matcher) writeln("BOL matched");
1380 $$
1381 }
1382 else
1383 $$`, nextInstr, bailOut);
1384
1385 break;
1386 case IR.Bof:
1387 code ~= ctSub(`
1388 if (atStart)
1389 {
1390 debug(std_regex_matcher) writeln("BOF matched");
1391 $$
1392 }
1393 else
1394 $$`, nextInstr, bailOut);
1395 break;
1396 case IR.Eol:
1397 code ~= ctSub(`
1398 dchar back;
1399 DataIndex bi;
1400 debug(std_regex_matcher) writefln("EOL (front 0x%x) %s", front, s[index .. s.lastIndex]);
1401 //no matching inside \r\n
1402 if (atEnd || (endOfLine(front, s.loopBack(index).nextChar(back,bi)
1403 && back == '\r')))
1404 {
1405 debug(std_regex_matcher) writeln("EOL matched");
1406 $$
1407 }
1408 else
1409 $$`, nextInstr, bailOut);
1410 break;
1411 case IR.Eof:
1412 code ~= ctSub(`
1413 if (atEnd)
1414 {
1415 debug(std_regex_matcher) writeln("BOF matched");
1416 $$
1417 }
1418 else
1419 $$`, nextInstr, bailOut);
1420 break;
1421 case IR.GroupStart:
1422 code ~= ctSub(`
1423 matches[$$].begin = index;
1424 $$`, ir[0].data, nextInstr);
1425 match = ir[0].data+1;
1426 break;
1427 case IR.GroupEnd:
1428 code ~= ctSub(`
1429 matches[$$].end = index;
1430 $$`, ir[0].data, nextInstr);
1431 break;
1432 case IR.Backref:
1433 string mStr = "auto referenced = ";
1434 mStr ~= ir[0].localRef
1435 ? ctSub("s[matches[$$].begin .. matches[$$].end];",
1436 ir[0].data, ir[0].data)
1437 : ctSub("s[backrefed[$$].begin .. backrefed[$$].end];",
1438 ir[0].data, ir[0].data);
1439 code ~= ctSub( `
1440 $$
1441 while (!atEnd && !referenced.empty && front == referenced.front)
1442 {
1443 next();
1444 referenced.popFront();
1445 }
1446 if (referenced.empty)
1447 $$
1448 else
1449 $$`, mStr, nextInstr, bailOut);
1450 break;
1451 case IR.Nop:
1452 case IR.End:
1453 break;
1454 default:
1455 assert(0, text(ir[0].mnemonic, " is not supported yet"));
1456 }
1457 return code;
1458 }
1459
1460 //generate D code for the whole regex
1461 public string ctGenRegEx(const(Bytecode)[] ir)
1462 {
1463 auto bdy = ctGenBlock(ir, 0);
1464 auto r = `
1465 import core.memory : pureMalloc, pureFree;
1466 with(matcher)
1467 {
1468 pc = 0;
1469 counter = 0;
1470 lastState = 0;
1471 matches[] = Group!DataIndex.init;
1472 auto start = s._index;`;
1473 r ~= `
1474 goto StartLoop;
1475 debug(std_regex_matcher) writeln("Try CT matching starting at ",s[index .. s.lastIndex]);
1476 L_backtrack:
1477 if (lastState || prevStack())
1478 {
1479 stackPop(pc);
1480 stackPop(index);
1481 s.reset(index);
1482 next();
1483 }
1484 else
1485 {
1486 s.reset(start);
1487 return false;
1488 }
1489 StartLoop:
1490 switch (pc)
1491 {
1492 `;
1493 r ~= bdy.code;
1494 r ~= ctSub(`
1495 case $$: break;`,bdy.addr);
1496 r ~= `
1497 default:
1498 assert(0);
1499 }
1500 // cleanup stale stack blocks
1501 while (prevStack()) {}
1502 return true;
1503 }
1504 `;
1505 return r;
1506 }
1507
1508 }
1509
1510 string ctGenRegExCode(Char)(const Regex!Char re)
1511 {
1512 auto context = CtContext(re);
1513 return context.ctGenRegEx(re.ir);
1514 }