use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::ops::Index;
use std::str::FromStr;
use std::sync::Arc;
use syntax;
use exec::{Exec, ExecBuilder};
use error::Error;
use params::{Params, Slot};
pub fn quote(text: &str) -> String {
syntax::quote(text)
}
pub fn is_match(regex: &str, text: &str) -> Result<bool, Error> {
Regex::new(regex).map(|r| r.is_match(text))
}
#[derive(Clone)]
pub struct Regex(#[doc(hidden)] pub _Regex);
#[derive(Clone)]
#[doc(hidden)]
pub enum _Regex {
#[doc(hidden)]
Dynamic(Exec),
#[doc(hidden)]
Native(ExNative),
}
#[doc(hidden)]
pub struct ExNative {
#[doc(hidden)]
pub original: &'static str,
#[doc(hidden)]
pub names: &'static &'static [Option<&'static str>],
#[doc(hidden)]
pub groups: &'static &'static [(&'static str, usize)],
#[doc(hidden)]
pub prog: fn(&mut [Option<usize>], &str, usize) -> bool,
}
impl Copy for ExNative {}
impl Clone for ExNative {
fn clone(&self) -> ExNative {
*self
}
}
impl fmt::Display for Regex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Debug for Regex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[doc(hidden)]
impl From<Exec> for Regex {
fn from(exec: Exec) -> Regex {
Regex(_Regex::Dynamic(exec))
}
}
impl PartialEq for Regex {
fn eq(&self, other: &Regex) -> bool {
self.as_str() == other.as_str()
}
}
impl Eq for Regex {}
impl FromStr for Regex {
type Err = Error;
fn from_str(s: &str) -> Result<Regex, Error> {
Regex::new(s)
}
}
impl Regex {
pub fn new(re: &str) -> Result<Regex, Error> {
Regex::with_size_limit(10 * (1 << 20), re)
}
pub fn with_size_limit(size: usize, re: &str) -> Result<Regex, Error> {
ExecBuilder::new(re).size_limit(size).build().map(Regex::from)
}
pub fn is_match(&self, text: &str) -> bool {
self.exec(&mut [], text, 0)
}
pub fn find(&self, text: &str) -> Option<(usize, usize)> {
let mut caps = [None, None];
if !self.exec(&mut caps, text, 0) {
None
} else {
Some((caps[0].unwrap(), caps[1].unwrap()))
}
}
pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
FindMatches {
re: self,
text: text,
last_end: 0,
last_match: None,
}
}
pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
let mut caps = Params::alloc_captures(self.captures_len());
if !self.exec(&mut caps, text, 0) {
None
} else {
Some(Captures {
text: text,
caps: caps,
named_groups: NamedGroups::from_regex(self)
})
}
}
pub fn captures_iter<'r, 't>(
&'r self,
text: &'t str,
) -> FindCaptures<'r, 't> {
FindCaptures {
re: self,
text: text,
last_end: 0,
last_match: None,
}
}
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: usize)
-> RegexSplitsN<'r, 't> {
RegexSplitsN {
splits: self.split(text),
n: 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: usize,
mut rep: R,
) -> String {
if let Some(rep) = rep.no_expand() {
let mut new = String::with_capacity(text.len());
let mut last_match = 0;
for (i, (s, e)) in self.find_iter(text).enumerate() {
if limit > 0 && i >= limit {
break
}
new.push_str(&text[last_match..s]);
new.push_str(&rep);
last_match = e;
}
new.push_str(&text[last_match..]);
return new;
}
let mut new = String::with_capacity(text.len());
let mut last_match = 0;
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[last_match..s]);
new.push_str(&rep.reg_replace(&cap));
last_match = e;
}
new.push_str(&text[last_match..]);
new
}
pub fn shortest_match(&self, text: &str) -> Option<usize> {
let mut caps = [None, None];
let mut _matched = [false];
let mut params =
Params::new(&mut caps, &mut _matched).set_match_short(true);
if !self.execp(&mut params, text, 0) {
None
} else {
params.captures()[1]
}
}
pub fn as_str(&self) -> &str {
match self.0 {
_Regex::Dynamic(ref exec) => &exec.regex_strings()[0],
_Regex::Native(ExNative { ref original, .. }) => original,
}
}
pub fn capture_names(&self) -> CaptureNames {
CaptureNames(match self.0 {
_Regex::Native(ref n) => _CaptureNames::Native(n.names.iter()),
_Regex::Dynamic(ref d) => {
_CaptureNames::Dynamic(d.captures().iter())
}
})
}
pub fn captures_len(&self) -> usize {
match self.0 {
_Regex::Native(ref n) => n.names.len(),
_Regex::Dynamic(ref d) => d.captures().len()
}
}
fn exec(&self, caps: &mut [Slot], text: &str, start: usize) -> bool {
let mut _matches = [false];
let mut params = Params::new(caps, &mut _matches);
self.execp(&mut params, text, start)
}
fn execp(&self, params: &mut Params, text: &str, start: usize) -> bool {
match self.0 {
_Regex::Native(ExNative { ref prog, .. }) => {
(*prog)(params.captures_mut(), text, start)
}
_Regex::Dynamic(ref exec) => {
exec.exec(params, text.as_bytes(), start)
}
}
}
}
pub struct CaptureNames<'r>(_CaptureNames<'r>);
enum _CaptureNames<'r> {
#[doc(hidden)]
Native(::std::slice::Iter<'r, Option<&'static str>>),
#[doc(hidden)]
Dynamic(::std::slice::Iter<'r, Option<String>>)
}
impl<'r> Iterator for CaptureNames<'r> {
type Item = Option<&'r str>;
fn next(&mut self) -> Option<Option<&'r str>> {
match self.0 {
_CaptureNames::Native(ref mut i) => i.next().cloned(),
_CaptureNames::Dynamic(ref mut i) => {
i.next().as_ref().map(|o| o.as_ref().map(|s| s.as_ref()))
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self.0 {
_CaptureNames::Native(ref i) => i.size_hint(),
_CaptureNames::Dynamic(ref i) => i.size_hint(),
}
}
}
pub struct NoExpand<'t>(pub &'t str);
pub trait Replacer {
fn reg_replace(&mut self, caps: &Captures) -> Cow<str>;
fn no_expand(&mut self) -> Option<Cow<str>> { None }
}
impl<'t> Replacer for NoExpand<'t> {
fn reg_replace(&mut self, _: &Captures) -> Cow<str> {
self.0.into()
}
fn no_expand(&mut self) -> Option<Cow<str>> {
Some(self.0.into())
}
}
impl<'t> Replacer for &'t str {
fn reg_replace<'a>(&'a mut self, caps: &Captures) -> Cow<'a, str> {
caps.expand(*self).into()
}
fn no_expand(&mut self) -> Option<Cow<str>> {
match self.find('$') {
Some(_) => None,
None => Some((*self).into()),
}
}
}
impl<F> Replacer for F where F: FnMut(&Captures) -> String {
fn reg_replace<'a>(&'a mut self, caps: &Captures) -> Cow<'a, str> {
(*self)(caps).into()
}
}
pub struct RegexSplits<'r, 't> {
finder: FindMatches<'r, 't>,
last: usize,
}
impl<'r, 't> Iterator for RegexSplits<'r, 't> {
type Item = &'t str;
fn next(&mut self) -> Option<&'t str> {
let text = self.finder.text;
match self.finder.next() {
None => {
if self.last >= text.len() {
None
} else {
let s = &text[self.last..];
self.last = text.len();
Some(s)
}
}
Some((s, e)) => {
let matched = &text[self.last..s];
self.last = e;
Some(matched)
}
}
}
}
pub struct RegexSplitsN<'r, 't> {
splits: RegexSplits<'r, 't>,
n: usize,
}
impl<'r, 't> Iterator for RegexSplitsN<'r, 't> {
type Item = &'t str;
fn next(&mut self) -> Option<&'t str> {
if self.n == 0 {
return None
}
self.n -= 1;
if self.n == 0 {
let text = self.splits.finder.text;
Some(&text[self.splits.last..])
} else {
self.splits.next()
}
}
}
enum NamedGroups {
Native(&'static [(&'static str, usize)]),
Dynamic(Arc<HashMap<String, usize>>),
}
impl NamedGroups {
fn from_regex(regex: &Regex) -> NamedGroups {
match regex.0 {
_Regex::Native(ExNative { ref groups, .. }) => {
NamedGroups::Native(groups)
}
_Regex::Dynamic(ref exec) => {
NamedGroups::Dynamic(exec.capture_name_idx().clone())
}
}
}
fn pos(&self, name: &str) -> Option<usize> {
match *self {
NamedGroups::Native(groups) => {
groups.binary_search_by(|&(n, _)| n.cmp(name))
.ok().map(|i| groups[i].1)
},
NamedGroups::Dynamic(ref groups) => {
groups.get(name).map(|i| *i)
},
}
}
fn iter<'n>(&'n self) -> NamedGroupsIter<'n> {
match *self {
NamedGroups::Native(g) => NamedGroupsIter::Native(g.iter()),
NamedGroups::Dynamic(ref g) => NamedGroupsIter::Dynamic(g.iter()),
}
}
}
enum NamedGroupsIter<'n> {
Native(::std::slice::Iter<'static, (&'static str, usize)>),
Dynamic(::std::collections::hash_map::Iter<'n, String, usize>),
}
impl<'n> Iterator for NamedGroupsIter<'n> {
type Item = (&'n str, usize);
fn next(&mut self) -> Option<Self::Item> {
match *self {
NamedGroupsIter::Native(ref mut it) => it.next().map(|&v| v),
NamedGroupsIter::Dynamic(ref mut it) => {
it.next().map(|(s, i)| (s.as_ref(), *i))
}
}
}
}
pub struct Captures<'t> {
text: &'t str,
caps: Vec<Option<usize>>,
named_groups: NamedGroups,
}
impl<'t> Captures<'t> {
pub fn pos(&self, i: usize) -> Option<(usize, usize)> {
let (s, e) = (i * 2, i * 2 + 1);
match (self.caps.get(s), self.caps.get(e)) {
(Some(&Some(s)), Some(&Some(e))) => Some((s, e)),
_ => None,
}
}
pub fn at(&self, i: usize) -> Option<&'t str> {
match self.pos(i) {
None => None,
Some((s, e)) => Some(&self.text[s..e])
}
}
pub fn name(&self, name: &str) -> Option<&'t str> {
self.named_groups.pos(name).and_then(|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.caps }
}
pub fn iter_named(&'t self) -> SubCapturesNamed<'t> {
SubCapturesNamed {
caps: self,
names: self.named_groups.iter()
}
}
pub fn expand(&self, text: &str) -> String {
const REPLACE_EXPAND: &'static str = r"(?x)
(?P<before>^|\b|[^$]) # Ignore `$$name`.
\$
(?P<name> # Match the actual capture name. Can be...
[0-9]+ # A sequence of digits (for indexed captures), or...
|
[_a-zA-Z][_0-9a-zA-Z]* # A name for named captures.
)
";
let re = Regex::new(REPLACE_EXPAND).unwrap();
let text = re.replace_all(text, |refs: &Captures| -> String {
let before = refs.name("before").unwrap_or("");
let name = refs.name("name").unwrap_or("");
format!("{}{}", before, match name.parse::<usize>() {
Err(_) => self.name(name).unwrap_or("").to_owned(),
Ok(i) => self.at(i).unwrap_or("").to_owned(),
})
});
let re = Regex::new(r"\$\$").unwrap();
re.replace_all(&text, NoExpand("$"))
}
#[inline]
pub fn len(&self) -> usize {
self.caps.len() / 2
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'t> Index<usize> for Captures<'t> {
type Output = str;
fn index(&self, i: usize) -> &str {
self.at(i).unwrap_or_else(|| panic!("no group at index '{}'", i))
}
}
impl<'t, 'i> Index<&'i str> for Captures<'t> {
type Output = str;
fn index<'a>(&'a self, name: &'i str) -> &'a str {
self.name(name).unwrap_or_else(|| panic!("no group named '{}'", name))
}
}
pub struct SubCaptures<'c> {
idx: usize,
caps: &'c Captures<'c>,
}
impl<'c> Iterator for SubCaptures<'c> {
type Item = Option<&'c str>;
fn next(&mut self) -> Option<Option<&'c str>> {
if self.idx < self.caps.len() {
self.idx += 1;
Some(self.caps.at(self.idx - 1))
} else {
None
}
}
}
pub struct SubCapturesPos<'c> {
idx: usize,
caps: &'c [Option<usize>]
}
impl<'c> Iterator for SubCapturesPos<'c> {
type Item = Option<(usize, usize)>;
fn next(&mut self) -> Option<Option<(usize, usize)>> {
if self.idx >= self.caps.len() {
return None
}
let r = match (self.caps[self.idx], self.caps[self.idx + 1]) {
(Some(s), Some(e)) => Some((s, e)),
(None, None) => None,
_ => unreachable!()
};
self.idx += 2;
Some(r)
}
}
pub struct SubCapturesNamed<'c> {
caps: &'c Captures<'c>,
names: NamedGroupsIter<'c>,
}
impl<'c> Iterator for SubCapturesNamed<'c> {
type Item = (&'c str, Option<&'c str>);
fn next(&mut self) -> Option<(&'c str, Option<&'c str>)> {
self.names.next().map(|(name, pos)| (name, self.caps.at(pos)))
}
}
pub struct FindCaptures<'r, 't> {
re: &'r Regex,
text: &'t str,
last_end: usize,
last_match: Option<usize>,
}
impl<'r, 't> Iterator for FindCaptures<'r, 't> {
type Item = Captures<'t>;
fn next(&mut self) -> Option<Captures<'t>> {
if self.last_end > self.text.len() {
return None
}
let mut caps = Params::alloc_captures(self.re.captures_len());
if !self.re.exec(&mut caps, self.text, self.last_end) {
return None
}
let (s, e) = (caps[0].unwrap(), caps[1].unwrap());
if e == s && Some(self.last_end) == self.last_match {
if self.last_end >= self.text.len() {
return None;
}
self.last_end += self.text[self.last_end..].chars()
.next().unwrap().len_utf8();
return self.next();
}
self.last_end = e;
self.last_match = Some(self.last_end);
Some(Captures {
text: self.text,
caps: caps,
named_groups: NamedGroups::from_regex(self.re),
})
}
}
pub struct FindMatches<'r, 't> {
re: &'r Regex,
text: &'t str,
last_end: usize,
last_match: Option<usize>,
}
impl<'r, 't> Iterator for FindMatches<'r, 't> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
if self.last_end > self.text.len() {
return None
}
let mut caps = [None, None];
if !self.re.exec(&mut caps, self.text, self.last_end) {
return None;
}
let (s, e) = (caps[0].unwrap(), caps[1].unwrap());
if e == s && Some(self.last_end) == self.last_match {
if self.last_end >= self.text.len() {
return None;
}
self.last_end += self.text[self.last_end..].chars()
.next().unwrap().len_utf8();
return self.next();
}
self.last_end = e;
self.last_match = Some(self.last_end);
Some((s, e))
}
}