pub use self::MatchKind::*;
pub use self::StepState::*;
use std::cmp;
use std::mem;
use compile::{
Program,
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<uint>>;
pub enum MatchKind {
Exists,
Location,
Submatches,
}
impl Copy for MatchKind {}
pub fn run<'r, 't>(which: MatchKind, prog: &'r Program, input: &'t str,
start: uint, end: uint) -> 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: uint,
end: uint,
ic: uint,
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 = Vec::from_elem(ncaps * 2, None);
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<uint>], nlist: &mut Threads,
caps: &mut [Option<uint>], pc: uint)
-> 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(|&rc| class_cmp(casei, c, rc))
.found().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: uint, groups: &mut [Option<uint>]) {
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: uint,
}
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: uint) -> uint {
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) -> uint {
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: uint,
groups: Vec<Option<uint>>,
}
struct Threads {
which: MatchKind,
queue: Vec<Thread>,
sparse: Vec<uint>,
size: uint,
}
impl Threads {
fn new(which: MatchKind, num_insts: uint, ncaps: uint) -> Threads {
Threads {
which: which,
queue: Vec::from_fn(num_insts, |_| {
Thread { pc: 0, groups: Vec::from_elem(ncaps * 2, None) }
}),
sparse: Vec::from_elem(num_insts, 0u),
size: 0,
}
}
fn add(&mut self, pc: uint, groups: &[Option<uint>], 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: uint) -> 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: uint) -> uint {
self.queue[i].pc
}
#[inline]
fn groups<'r>(&'r mut self, i: uint) -> &'r mut [Option<uint>] {
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(|&(start, end)| {
if c >= start && c <= end {
Equal
} else if start > c {
Greater
} else {
Less
}
}).found().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 {
Equal
} else if start > textc {
Greater
} else {
Less
}
}
#[inline]
pub fn find_prefix(needle: &[u8], haystack: &[u8]) -> Option<uint> {
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
}