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 error::Error;
use exec::{Exec, ExecNoSyncStr};
use re_builder::unicode::RegexBuilder;
use re_plugin::Plugin;
use re_trait::{self, RegularExpression, 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)]
Plugin(Plugin),
}
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> {
RegexBuilder::new(re).size_limit(size).compile()
}
pub fn is_match(&self, text: &str) -> bool {
self.is_match_at(text, 0)
}
#[doc(hidden)]
pub fn is_match_at(&self, text: &str, start: usize) -> bool {
self.shortest_match_at(text, start).is_some()
}
pub fn find(&self, text: &str) -> Option<(usize, usize)> {
self.find_at(text, 0)
}
#[doc(hidden)]
pub fn find_at(&self, text: &str, start: usize) -> Option<(usize, usize)> {
match self.0 {
_Regex::Dynamic(ref exec) => {
exec.searcher_str().find_at(text, start)
}
_Regex::Plugin(ref plug) => plug.find_at(text, start),
}
}
pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> FindMatches<'r, 't> {
match self.0 {
_Regex::Dynamic(ref exec) => {
let it = exec.searcher_str().find_iter(text);
FindMatches(FindMatchesInner::Dynamic(it))
}
_Regex::Plugin(ref plug) => {
let it = plug.find_iter(text);
FindMatches(FindMatchesInner::Plugin(it))
}
}
}
pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> {
let mut slots = vec![None; 2 * self.captures_len()];
self.read_captures_at(&mut slots, text, 0).map(|_| Captures {
text: text,
slots: slots,
named_groups: NamedGroups::from_regex(self)
})
}
#[doc(hidden)]
pub fn read_captures_at(
&self,
slots: &mut [Slot],
text: &str,
start: usize,
) -> Option<(usize, usize)> {
match self.0 {
_Regex::Dynamic(ref exec) => {
exec.searcher_str().read_captures_at(slots, text, start)
}
_Regex::Plugin(ref plug) => {
plug.read_captures_at(slots, text, start)
}
}
}
pub fn captures_iter<'r, 't>(
&'r self,
text: &'t str,
) -> FindCaptures<'r, 't> {
match self.0 {
_Regex::Dynamic(ref exec) => {
let it = exec.searcher_str().captures_iter(text);
FindCaptures(FindCapturesInner::Dynamic(it))
}
_Regex::Plugin(ref plug) => {
let it = plug.captures_iter(text);
FindCaptures(FindCapturesInner::Plugin(it))
}
}
}
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> {
self.shortest_match_at(text, 0)
}
#[doc(hidden)]
pub fn shortest_match_at(
&self,
text: &str,
start: usize,
) -> Option<usize> {
match self.0 {
_Regex::Dynamic(ref exec) => {
exec.searcher_str().shortest_match_at(text, start)
}
_Regex::Plugin(ref plug) => plug.shortest_match_at(text, start),
}
}
pub fn as_str(&self) -> &str {
match self.0 {
_Regex::Dynamic(ref exec) => &exec.regex_strings()[0],
_Regex::Plugin(ref plug) => &plug.original,
}
}
pub fn capture_names(&self) -> CaptureNames {
CaptureNames(match self.0 {
_Regex::Plugin(ref n) => _CaptureNames::Plugin(n.names.iter()),
_Regex::Dynamic(ref d) => {
_CaptureNames::Dynamic(d.capture_names().iter())
}
})
}
pub fn captures_len(&self) -> usize {
match self.0 {
_Regex::Plugin(ref n) => n.names.len(),
_Regex::Dynamic(ref d) => d.capture_names().len()
}
}
}
pub struct CaptureNames<'r>(_CaptureNames<'r>);
enum _CaptureNames<'r> {
#[doc(hidden)]
Plugin(::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::Plugin(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::Plugin(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 {
Plugin(&'static [(&'static str, usize)]),
Dynamic(Arc<HashMap<String, usize>>),
}
impl NamedGroups {
fn from_regex(regex: &Regex) -> NamedGroups {
match regex.0 {
_Regex::Plugin(ref plug) => NamedGroups::Plugin(&plug.groups),
_Regex::Dynamic(ref exec) => {
NamedGroups::Dynamic(exec.capture_name_idx().clone())
}
}
}
fn pos(&self, name: &str) -> Option<usize> {
match *self {
NamedGroups::Plugin(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::Plugin(g) => NamedGroupsIter::Plugin(g.iter()),
NamedGroups::Dynamic(ref g) => NamedGroupsIter::Dynamic(g.iter()),
}
}
}
enum NamedGroupsIter<'n> {
Plugin(::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::Plugin(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,
slots: 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.slots.get(s), self.slots.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, slots: &self.slots }
}
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.slots.len() / 2
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl<'t> fmt::Debug for Captures<'t> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Captures").field(&CapturesDebug(self)).finish()
}
}
struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>);
impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let slot_to_name: HashMap<usize, &str> =
self.0.named_groups.iter().map(|(a, b)| (b, a)).collect();
let mut map = f.debug_map();
for (slot, m) in self.0.iter_pos().enumerate() {
let m = m.map(|(s, e)| &self.0.text[s..e]);
if let Some(ref name) = slot_to_name.get(&slot) {
map.entry(&name, &m);
} else {
map.entry(&slot, &m);
}
}
map.finish()
}
}
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,
slots: &'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.slots.len() {
return None
}
let r = match (self.slots[self.idx], self.slots[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>(FindCapturesInner<'r, 't>);
enum FindCapturesInner<'r, 't> {
Dynamic(re_trait::FindCaptures<'t, ExecNoSyncStr<'r>>),
Plugin(re_trait::FindCaptures<'t, Plugin>),
}
impl<'r, 't> Iterator for FindCaptures<'r, 't> {
type Item = Captures<'t>;
fn next(&mut self) -> Option<Captures<'t>> {
match self.0 {
FindCapturesInner::Dynamic(ref mut it) => {
let named = it.regex().capture_name_idx().clone();
it.next().map(|slots| Captures {
text: it.text(),
slots: slots,
named_groups: NamedGroups::Dynamic(named),
})
}
FindCapturesInner::Plugin(ref mut it) => {
it.next().map(|slots| Captures {
text: it.text(),
slots: slots,
named_groups: NamedGroups::Plugin(it.regex().groups),
})
}
}
}
}
pub struct FindMatches<'r, 't>(FindMatchesInner<'r, 't>);
enum FindMatchesInner<'r, 't> {
Dynamic(re_trait::FindMatches<'t, ExecNoSyncStr<'r>>),
Plugin(re_trait::FindMatches<'t, Plugin>),
}
impl<'r, 't> FindMatches<'r, 't> {
fn text(&self) -> &'t str {
match self.0 {
FindMatchesInner::Dynamic(ref it) => it.text(),
FindMatchesInner::Plugin(ref it) => it.text(),
}
}
}
impl<'r, 't> Iterator for FindMatches<'r, 't> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
match self.0 {
FindMatchesInner::Dynamic(ref mut it) => it.next(),
FindMatchesInner::Plugin(ref mut it) => it.next(),
}
}
}