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
use self::MatchKind::*;
use self::StepState::*;
use std::cmp::{self, Ordering};
use std::mem;
use std::iter::repeat;
use std::slice::SliceExt;
use compile::Program;
use compile::Inst::{Match, OneChar, CharClass, Any, EmptyBegin, EmptyEnd, EmptyWordBoundary,
Save, Jump, Split};
use parse::{FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_NEGATED};
use unicode::regex::PERLW;
pub type CaptureLocs = Vec<Option<usize>>;
pub enum MatchKind {
Exists,
Location,
Submatches,
}
impl Copy for MatchKind {}
pub fn run<'r, 't>(which: MatchKind, prog: &'r Program, input: &'t str,
start: usize, end: usize) -> CaptureLocs {
Nfa {
which: which,
prog: prog,
input: input,
start: start,
end: end,
ic: 0,
chars: CharReader::new(input),
}.run()
}
struct Nfa<'r, 't> {
which: MatchKind,
prog: &'r Program,
input: &'t str,
start: usize,
end: usize,
ic: usize,
chars: CharReader<'t>,
}
pub enum StepState {
StepMatchEarlyReturn,
StepMatch,
StepContinue,
}
impl Copy for StepState {}
impl<'r, 't> Nfa<'r, 't> {
fn run(&mut self) -> CaptureLocs {
let ncaps = match self.which {
Exists => 0,
Location => 1,
Submatches => self.prog.num_captures(),
};
let mut matched = false;
let ninsts = self.prog.insts.len();
let mut clist = &mut Threads::new(self.which, ninsts, ncaps);
let mut nlist = &mut Threads::new(self.which, ninsts, ncaps);
let mut groups = repeat(None).take(ncaps * 2).collect::<Vec<_>>();
let prefix_anchor =
match self.prog.insts[1] {
EmptyBegin(flags) if flags & FLAG_MULTI == 0 => true,
_ => false,
};
self.ic = self.start;
let mut next_ic = self.chars.set(self.start);
while self.ic <= self.end {
if clist.size == 0 {
if matched {
break
}
if self.prog.prefix.len() > 0 && clist.size == 0 {
let needle = self.prog.prefix.as_bytes();
let haystack = &self.input.as_bytes()[self.ic..];
match find_prefix(needle, haystack) {
None => break,
Some(i) => {
self.ic += i;
next_ic = self.chars.set(self.ic);
}
}
}
}
if clist.size == 0 || (!prefix_anchor && !matched) {
self.add(clist, 0, groups.as_mut_slice())
}
self.ic = next_ic;
next_ic = self.chars.advance();
for i in range(0, clist.size) {
let pc = clist.pc(i);
let step_state = self.step(groups.as_mut_slice(), nlist,
clist.groups(i), pc);
match step_state {
StepMatchEarlyReturn => return vec![Some(0), Some(0)],
StepMatch => { matched = true; break },
StepContinue => {},
}
}
mem::swap(&mut clist, &mut nlist);
nlist.empty();
}
match self.which {
Exists if matched => vec![Some(0), Some(0)],
Exists => vec![None, None],
Location | Submatches => groups,
}
}
fn step(&self, groups: &mut [Option<usize>], nlist: &mut Threads,
caps: &mut [Option<usize>], pc: usize)
-> StepState {
match self.prog.insts[pc] {
Match => {
match self.which {
Exists => {
return StepMatchEarlyReturn
}
Location => {
groups[0] = caps[0];
groups[1] = caps[1];
return StepMatch
}
Submatches => {
for (slot, val) in groups.iter_mut().zip(caps.iter()) {
*slot = *val;
}
return StepMatch
}
}
}
OneChar(c, flags) => {
if self.char_eq(flags & FLAG_NOCASE > 0, self.chars.prev, c) {
self.add(nlist, pc+1, caps);
}
}
CharClass(ref ranges, flags) => {
if self.chars.prev.is_some() {
let c = self.chars.prev.unwrap();
let negate = flags & FLAG_NEGATED > 0;
let casei = flags & FLAG_NOCASE > 0;
let found = ranges.as_slice();
let found = found.binary_search_by(|&rc| class_cmp(casei, c, rc))
.ok().is_some();
if found ^ negate {
self.add(nlist, pc+1, caps);
}
}
}
Any(flags) => {
if flags & FLAG_DOTNL > 0
|| !self.char_eq(false, self.chars.prev, '\n') {
self.add(nlist, pc+1, caps)
}
}
EmptyBegin(_) | EmptyEnd(_) | EmptyWordBoundary(_)
| Save(_) | Jump(_) | Split(_, _) => {},
}
StepContinue
}
fn add(&self, nlist: &mut Threads, pc: usize, groups: &mut [Option<usize>]) {
if nlist.contains(pc) {
return
}
match self.prog.insts[pc] {
EmptyBegin(flags) => {
let multi = flags & FLAG_MULTI > 0;
nlist.add(pc, groups, true);
if self.chars.is_begin()
|| (multi && self.char_is(self.chars.prev, '\n')) {
self.add(nlist, pc + 1, groups)
}
}
EmptyEnd(flags) => {
let multi = flags & FLAG_MULTI > 0;
nlist.add(pc, groups, true);
if self.chars.is_end()
|| (multi && self.char_is(self.chars.cur, '\n')) {
self.add(nlist, pc + 1, groups)
}
}
EmptyWordBoundary(flags) => {
nlist.add(pc, groups, true);
if self.chars.is_word_boundary() == !(flags & FLAG_NEGATED > 0) {
self.add(nlist, pc + 1, groups)
}
}
Save(slot) => {
nlist.add(pc, groups, true);
match self.which {
Location if slot <= 1 => {
let old = groups[slot];
groups[slot] = Some(self.ic);
self.add(nlist, pc + 1, groups);
groups[slot] = old;
}
Submatches => {
let old = groups[slot];
groups[slot] = Some(self.ic);
self.add(nlist, pc + 1, groups);
groups[slot] = old;
}
Exists | Location => self.add(nlist, pc + 1, groups),
}
}
Jump(to) => {
nlist.add(pc, groups, true);
self.add(nlist, to, groups)
}
Split(x, y) => {
nlist.add(pc, groups, true);
self.add(nlist, x, groups);
self.add(nlist, y, groups);
}
Match | OneChar(_, _) | CharClass(_, _) | Any(_) => {
nlist.add(pc, groups, false);
}
}
}
#[inline]
fn char_eq(&self, casei: bool, textc: Option<char>, regc: char) -> bool {
match textc {
None => false,
Some(textc) => {
regc == textc
|| (casei && regc.to_uppercase() == textc.to_uppercase())
}
}
}
#[inline]
fn char_is(&self, textc: Option<char>, regc: char) -> bool {
textc == Some(regc)
}
}
pub struct CharReader<'t> {
pub prev: Option<char>,
pub cur: Option<char>,
input: &'t str,
next: usize,
}
impl<'t> CharReader<'t> {
pub fn new(input: &'t str) -> CharReader<'t> {
CharReader {
prev: None,
cur: None,
input: input,
next: 0,
}
}
#[inline]
pub fn set(&mut self, ic: usize) -> usize {
self.prev = None;
self.cur = None;
self.next = 0;
if self.input.len() == 0 {
return 1
}
if ic > 0 {
let i = cmp::min(ic, self.input.len());
let prev = self.input.char_range_at_reverse(i);
self.prev = Some(prev.ch);
}
if ic < self.input.len() {
let cur = self.input.char_range_at(ic);
self.cur = Some(cur.ch);
self.next = cur.next;
self.next
} else {
self.input.len() + 1
}
}
#[inline]
pub fn advance(&mut self) -> usize {
self.prev = self.cur;
if self.next < self.input.len() {
let cur = self.input.char_range_at(self.next);
self.cur = Some(cur.ch);
self.next = cur.next;
} else {
self.cur = None;
self.next = self.input.len() + 1;
}
self.next
}
#[inline]
pub fn is_begin(&self) -> bool { self.prev.is_none() }
#[inline]
pub fn is_end(&self) -> bool { self.cur.is_none() }
pub fn is_word_boundary(&self) -> bool {
if self.is_begin() {
return is_word(self.cur)
}
if self.is_end() {
return is_word(self.prev)
}
(is_word(self.cur) && !is_word(self.prev))
|| (is_word(self.prev) && !is_word(self.cur))
}
}
struct Thread {
pc: usize,
groups: Vec<Option<usize>>,
}
struct Threads {
which: MatchKind,
queue: Vec<Thread>,
sparse: Vec<usize>,
size: usize,
}
impl Threads {
fn new(which: MatchKind, num_insts: usize, ncaps: usize) -> Threads {
Threads {
which: which,
queue: range(0, num_insts).map(|_| {
Thread {pc: 0, groups: repeat(None).take(ncaps * 2).collect() }
}).collect(),
sparse: repeat(0).take(num_insts).collect(),
size: 0,
}
}
fn add(&mut self, pc: usize, groups: &[Option<usize>], empty: bool) {
let t = &mut self.queue[self.size];
t.pc = pc;
match (empty, self.which) {
(_, Exists) | (true, _) => {},
(false, Location) => {
t.groups[0] = groups[0];
t.groups[1] = groups[1];
}
(false, Submatches) => {
for (slot, val) in t.groups.iter_mut().zip(groups.iter()) {
*slot = *val;
}
}
}
self.sparse[pc] = self.size;
self.size += 1;
}
#[inline]
fn contains(&self, pc: usize) -> bool {
let s = self.sparse[pc];
s < self.size && self.queue[s].pc == pc
}
#[inline]
fn empty(&mut self) {
self.size = 0;
}
#[inline]
fn pc(&self, i: usize) -> usize {
self.queue[i].pc
}
#[inline]
fn groups(&mut self, i: usize) -> &mut [Option<usize>] {
self.queue[i].groups.as_mut_slice()
}
}
pub fn is_word(c: Option<char>) -> bool {
let c = match c {
None => return false,
Some(c) => c,
};
match c {
'_' | '0' ... '9' | 'a' ... 'z' | 'A' ... 'Z' => true,
_ => PERLW.binary_search_by(|&(start, end)| {
if c >= start && c <= end {
Ordering::Equal
} else if start > c {
Ordering::Greater
} else {
Ordering::Less
}
}).ok().is_some()
}
}
#[inline]
fn class_cmp(casei: bool, mut textc: char,
(mut start, mut end): (char, char)) -> Ordering {
if casei {
textc = textc.to_uppercase();
start = start.to_uppercase();
end = end.to_uppercase();
}
if textc >= start && textc <= end {
Ordering::Equal
} else if start > textc {
Ordering::Greater
} else {
Ordering::Less
}
}
#[inline]
pub fn find_prefix(needle: &[u8], haystack: &[u8]) -> Option<usize> {
let (hlen, nlen) = (haystack.len(), needle.len());
if nlen > hlen || nlen == 0 {
return None
}
for (offset, window) in haystack.windows(nlen).enumerate() {
if window == needle {
return Some(offset)
}
}
None
}