pub use self::NamesIter::*;
pub use self::Regex::*;
use std::collections::HashMap;
use std::fmt;
use std::str::CowString;
use compile::Program;
use parse;
use vm;
use vm::{CaptureLocs, MatchKind, Exists, Location, Submatches};
pub fn quote(text: &str) -> String {
let mut quoted = String::with_capacity(text.len());
for c in text.chars() {
if parse::is_punct(c) {
quoted.push('\\')
}
quoted.push(c);
}
quoted
}
pub fn is_match(regex: &str, text: &str) -> Result<bool, parse::Error> {
Regex::new(regex).map(|r| r.is_match(text))
}
#[deriving(Clone)]
pub enum Regex {
#[doc(hidden)]
Dynamic(ExDynamic),
#[doc(hidden)]
Native(ExNative),
}
#[deriving(Clone)]
#[doc(hidden)]
pub struct ExDynamic {
original: String,
names: Vec<Option<String>>,
#[doc(hidden)]
pub prog: Program
}
#[doc(hidden)]
pub struct ExNative {
#[doc(hidden)]
pub original: &'static str,
#[doc(hidden)]
pub names: &'static &'static [Option<&'static str>],
#[doc(hidden)]
pub prog: fn(MatchKind, &str, uint, uint) -> Vec<Option<uint>>
}
impl Copy for ExNative {}
impl Clone for ExNative {
fn clone(&self) -> ExNative {
*self
}
}
impl fmt::Show for Regex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl Regex {
pub fn new(re: &str) -> Result<Regex, parse::Error> {
let ast = try!(parse::parse(re));
let (prog, names) = Program::new(ast);
Ok(Dynamic(ExDynamic {
original: re.to_string(),
names: names,
prog: prog,
}))
}
pub fn is_match(&self, text: &str) -> bool {
has_match(&exec(self, Exists, text))
}
pub fn find(&self, text: &str) -> Option<(uint, uint)> {
let caps = exec(self, Location, text);
if has_match(&caps) {
Some((caps[0].unwrap(), caps[1].unwrap()))
} else {
None
}
}
pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
FindMatches {
re: self,
search: text,
last_end: 0,
last_match: None,
}
}
pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
let caps = exec(self, Submatches, text);
Captures::new(self, text, caps)
}
pub fn captures_iter<'r, 't>(&'r self, text: &'t str)
-> FindCaptures<'r, 't> {
FindCaptures {
re: self,
search: text,
last_match: None,
last_end: 0,
}
}
pub fn split<'r, 't>(&'r self, text: &'t str) -> RegexSplits<'r, 't> {
RegexSplits {
finder: self.find_iter(text),
last: 0,
}
}
pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: uint)
-> RegexSplitsN<'r, 't> {
RegexSplitsN {
splits: self.split(text),
cur: 0,
limit: limit,
}
}
pub fn replace<R: Replacer>(&self, text: &str, rep: R) -> String {
self.replacen(text, 1, rep)
}
pub fn replace_all<R: Replacer>(&self, text: &str, rep: R) -> String {
self.replacen(text, 0, rep)
}
pub fn replacen<R: Replacer>
(&self, text: &str, limit: uint, mut rep: R) -> String {
let mut new = String::with_capacity(text.len());
let mut last_match = 0u;
for (i, cap) in self.captures_iter(text).enumerate() {
if limit > 0 && i >= limit {
break
}
let (s, e) = cap.pos(0).unwrap(); new.push_str(text.slice(last_match, s));
new.push_str(rep.reg_replace(&cap).as_slice());
last_match = e;
}
new.push_str(text.slice(last_match, text.len()));
return new;
}
pub fn as_str<'a>(&'a self) -> &'a str {
match *self {
Dynamic(ExDynamic { ref original, .. }) => original.as_slice(),
Native(ExNative { ref original, .. }) => original.as_slice(),
}
}
#[doc(hidden)]
#[experimental]
pub fn names_iter<'a>(&'a self) -> NamesIter<'a> {
match *self {
Native(ref n) => NamesIterNative(n.names.iter()),
Dynamic(ref d) => NamesIterDynamic(d.names.iter())
}
}
fn names_len(&self) -> uint {
match *self {
Native(ref n) => n.names.len(),
Dynamic(ref d) => d.names.len()
}
}
}
pub enum NamesIter<'a> {
NamesIterNative(::std::slice::Items<'a, Option<&'static str>>),
NamesIterDynamic(::std::slice::Items<'a, Option<String>>)
}
impl<'a> Iterator<Option<String>> for NamesIter<'a> {
fn next(&mut self) -> Option<Option<String>> {
match *self {
NamesIterNative(ref mut i) => i.next().map(|x| x.map(|s| s.to_string())),
NamesIterDynamic(ref mut i) => i.next().map(|x| x.as_ref().map(|s| s.to_string())),
}
}
}
pub struct NoExpand<'t>(pub &'t str);
pub trait Replacer {
fn reg_replace<'a>(&'a mut self, caps: &Captures) -> CowString<'a>;
}
impl<'t> Replacer for NoExpand<'t> {
fn reg_replace<'a>(&'a mut self, _: &Captures) -> CowString<'a> {
let NoExpand(s) = *self;
s.into_cow()
}
}
impl<'t> Replacer for &'t str {
fn reg_replace<'a>(&'a mut self, caps: &Captures) -> CowString<'a> {
caps.expand(*self).into_cow()
}
}
impl<'t> Replacer for |&Captures|: 't -> String {
fn reg_replace<'a>(&'a mut self, caps: &Captures) -> CowString<'a> {
(*self)(caps).into_cow()
}
}
pub struct RegexSplits<'r, 't> {
finder: FindMatches<'r, 't>,
last: uint,
}
impl<'r, 't> Iterator<&'t str> for RegexSplits<'r, 't> {
fn next(&mut self) -> Option<&'t str> {
let text = self.finder.search;
match self.finder.next() {
None => {
if self.last >= text.len() {
None
} else {
let s = text.slice(self.last, text.len());
self.last = text.len();
Some(s)
}
}
Some((s, e)) => {
let matched = text.slice(self.last, s);
self.last = e;
Some(matched)
}
}
}
}
pub struct RegexSplitsN<'r, 't> {
splits: RegexSplits<'r, 't>,
cur: uint,
limit: uint,
}
impl<'r, 't> Iterator<&'t str> for RegexSplitsN<'r, 't> {
fn next(&mut self) -> Option<&'t str> {
let text = self.splits.finder.search;
if self.cur >= self.limit {
None
} else {
self.cur += 1;
if self.cur >= self.limit {
Some(text.slice(self.splits.last, text.len()))
} else {
self.splits.next()
}
}
}
}
pub struct Captures<'t> {
text: &'t str,
locs: CaptureLocs,
named: Option<HashMap<String, uint>>,
}
impl<'t> Captures<'t> {
#[allow(experimental)]
fn new(re: &Regex, search: &'t str, locs: CaptureLocs)
-> Option<Captures<'t>> {
if !has_match(&locs) {
return None
}
let named =
if re.names_len() == 0 {
None
} else {
let mut named = HashMap::new();
for (i, name) in re.names_iter().enumerate() {
match name {
None => {},
Some(name) => {
named.insert(name, i);
}
}
}
Some(named)
};
Some(Captures {
text: search,
locs: locs,
named: named,
})
}
pub fn pos(&self, i: uint) -> Option<(uint, uint)> {
let (s, e) = (i * 2, i * 2 + 1);
if e >= self.locs.len() || self.locs[s].is_none() {
return None
}
Some((self.locs[s].unwrap(), self.locs[e].unwrap()))
}
pub fn at(&self, i: uint) -> &'t str {
match self.pos(i) {
None => "",
Some((s, e)) => {
self.text.slice(s, e)
}
}
}
pub fn name(&self, name: &str) -> &'t str {
match self.named {
None => "",
Some(ref h) => {
match h.get(name) {
None => "",
Some(i) => self.at(*i),
}
}
}
}
pub fn iter(&'t self) -> SubCaptures<'t> {
SubCaptures { idx: 0, caps: self, }
}
pub fn iter_pos(&'t self) -> SubCapturesPos<'t> {
SubCapturesPos { idx: 0, caps: self, }
}
pub fn expand(&self, text: &str) -> String {
let re = Regex::new(r"(^|[^$]|\b)\$(\w+)").unwrap();
let text = re.replace_all(text, |refs: &Captures| -> String {
let (pre, name) = (refs.at(1), refs.at(2));
format!("{}{}", pre,
match from_str::<uint>(name.as_slice()) {
None => self.name(name).to_string(),
Some(i) => self.at(i).to_string(),
})
});
let re = Regex::new(r"\$\$").unwrap();
re.replace_all(text.as_slice(), NoExpand("$"))
}
#[inline]
pub fn len(&self) -> uint { self.locs.len() / 2 }
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
}
pub struct SubCaptures<'t> {
idx: uint,
caps: &'t Captures<'t>,
}
impl<'t> Iterator<&'t str> for SubCaptures<'t> {
fn next(&mut self) -> Option<&'t str> {
if self.idx < self.caps.len() {
self.idx += 1;
Some(self.caps.at(self.idx - 1))
} else {
None
}
}
}
pub struct SubCapturesPos<'t> {
idx: uint,
caps: &'t Captures<'t>,
}
impl<'t> Iterator<Option<(uint, uint)>> for SubCapturesPos<'t> {
fn next(&mut self) -> Option<Option<(uint, uint)>> {
if self.idx < self.caps.len() {
self.idx += 1;
Some(self.caps.pos(self.idx - 1))
} else {
None
}
}
}
pub struct FindCaptures<'r, 't> {
re: &'r Regex,
search: &'t str,
last_match: Option<uint>,
last_end: uint,
}
impl<'r, 't> Iterator<Captures<'t>> for FindCaptures<'r, 't> {
fn next(&mut self) -> Option<Captures<'t>> {
if self.last_end > self.search.len() {
return None
}
let caps = exec_slice(self.re, Submatches, self.search,
self.last_end, self.search.len());
let (s, e) =
if !has_match(&caps) {
return None
} else {
(caps[0].unwrap(), caps[1].unwrap())
};
if e == s && Some(self.last_end) == self.last_match {
self.last_end += 1;
return self.next()
}
self.last_end = e;
self.last_match = Some(self.last_end);
Captures::new(self.re, self.search, caps)
}
}
pub struct FindMatches<'r, 't> {
re: &'r Regex,
search: &'t str,
last_match: Option<uint>,
last_end: uint,
}
impl<'r, 't> Iterator<(uint, uint)> for FindMatches<'r, 't> {
fn next(&mut self) -> Option<(uint, uint)> {
if self.last_end > self.search.len() {
return None
}
let caps = exec_slice(self.re, Location, self.search,
self.last_end, self.search.len());
let (s, e) =
if !has_match(&caps) {
return None
} else {
(caps[0].unwrap(), caps[1].unwrap())
};
if e == s && Some(self.last_end) == self.last_match {
self.last_end += 1;
return self.next()
}
self.last_end = e;
self.last_match = Some(self.last_end);
Some((s, e))
}
}
fn exec(re: &Regex, which: MatchKind, input: &str) -> CaptureLocs {
exec_slice(re, which, input, 0, input.len())
}
fn exec_slice(re: &Regex, which: MatchKind,
input: &str, s: uint, e: uint) -> CaptureLocs {
match *re {
Dynamic(ExDynamic { ref prog, .. }) => vm::run(which, prog, input, s, e),
Native(ExNative { ref prog, .. }) => (*prog)(which, input, s, e),
}
}
#[inline]
fn has_match(caps: &CaptureLocs) -> bool {
caps.len() >= 2 && caps[0].is_some() && caps[1].is_some()
}