| 1 |
// Copyright 2016 The Fancy Regex Authors. |
| 2 |
// |
| 3 |
// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 |
// of this software and associated documentation files (the "Software"), to deal |
| 5 |
// in the Software without restriction, including without limitation the rights |
| 6 |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 |
// copies of the Software, and to permit persons to whom the Software is |
| 8 |
// furnished to do so, subject to the following conditions: |
| 9 |
// |
| 10 |
// The above copyright notice and this permission notice shall be included in |
| 11 |
// all copies or substantial portions of the Software. |
| 12 |
// |
| 13 |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 |
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 |
// THE SOFTWARE. |
| 20 |
|
| 21 |
//! A regex parser yielding an AST. |
| 22 |
|
| 23 |
use alloc::boxed::Box; |
| 24 |
use alloc::string::{String, ToString}; |
| 25 |
use alloc::sync::Arc; |
| 26 |
use alloc::vec::Vec; |
| 27 |
use alloc::{format, vec}; |
| 28 |
|
| 29 |
use bit_set::BitSet; |
| 30 |
use regex_syntax::escape_into; |
| 31 |
|
| 32 |
use crate::parse_flags::*; |
| 33 |
use crate::{codepoint_len, Error, Expr, ParseError, Result, MAX_RECURSION}; |
| 34 |
use crate::{ |
| 35 |
Absent, Assertion, AstNode, BacktrackingControlVerb, CaptureGroupTarget, LookAround::*, |
| 36 |
}; |
| 37 |
|
| 38 |
#[cfg(not(feature = "std"))] |
| 39 |
pub(crate) type NamedGroups = alloc::collections::BTreeMap<String, usize>; |
| 40 |
#[cfg(feature = "std")] |
| 41 |
pub(crate) type NamedGroups = std::collections::HashMap<String, usize>; |
| 42 |
|
| 43 |
#[derive(Debug, Clone)] |
| 44 |
pub struct ExprTree { |
| 45 |
pub expr: Expr, |
| 46 |
pub backrefs: BitSet, |
| 47 |
pub named_groups: NamedGroups, |
| 48 |
pub(crate) numeric_capture_group_references: bool, |
| 49 |
pub contains_subroutines: bool, |
| 50 |
pub(crate) self_recursive: bool, |
| 51 |
/// Total number of capture groups in the pattern, as counted by the resolver. |
| 52 |
/// Used by the analyzer to validate that backreferences refer to groups that exist. |
| 53 |
pub(crate) total_groups: usize, |
| 54 |
/// The first backreference group number that exceeds `total_groups`, if any. |
| 55 |
/// Such numbers are not inserted into `backrefs` (to avoid allocating memory proportional |
| 56 |
/// to an arbitrarily large value); the analyzer reads this field instead to report the error. |
| 57 |
pub(crate) out_of_range_backref: Option<usize>, |
| 58 |
/// Whether numbered groups were ignored (treated as non-capturing) during parsing |
| 59 |
pub(crate) numbered_groups_ignored: bool, |
| 60 |
} |
| 61 |
|
| 62 |
#[derive(Debug)] |
| 63 |
pub(crate) struct Parser<'a> { |
| 64 |
re: &'a str, // source |
| 65 |
flags: u32, |
| 66 |
numeric_capture_group_references: bool, |
| 67 |
contains_subroutines: bool, |
| 68 |
self_recursive: bool, |
| 69 |
has_named_groups: bool, |
| 70 |
} |
| 71 |
|
| 72 |
/// anything which involves a capture group name will be parsed into an AstNode |
| 73 |
/// which will then get resolved into a standard Expr variant after parsing is otherwise complete. |
| 74 |
/// This allows us to only have to handle numbered capture groups internally during analysis and compilation. |
| 75 |
impl<'a> Parser<'a> { |
| 76 |
pub(crate) fn parse_with_flags(re: &str, flags: u32) -> Result<ExprTree> { |
| 77 |
let mut p = Parser::new(re, flags); |
| 78 |
let (ix, mut expr) = p.parse_re(0, 0)?; |
| 79 |
if ix < re.len() { |
| 80 |
return Err(Error::ParseError( |
| 81 |
ix, |
| 82 |
ParseError::GeneralParseError("end of string not reached".to_string()), |
| 83 |
)); |
| 84 |
} |
| 85 |
|
| 86 |
let mut resolver = Resolver { |
| 87 |
named_groups: NamedGroups::default(), |
| 88 |
named_group_positions: NamedGroups::default(), |
| 89 |
ignore_numbered_groups: p.flag(FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST) |
| 90 |
&& p.has_named_groups, |
| 91 |
next_group_index: 1, |
| 92 |
total_groups: 0, |
| 93 |
out_of_range_backref: None, |
| 94 |
curr_group: 0, |
| 95 |
backrefs: Default::default(), |
| 96 |
}; |
| 97 |
resolver.resolve_groups(&mut expr); |
| 98 |
resolver.total_groups = resolver.next_group_index - 1; |
| 99 |
resolver.next_group_index = 1; |
| 100 |
resolver.curr_group = 0; |
| 101 |
resolver.resolve_capture_group_targets(&mut expr)?; |
| 102 |
|
| 103 |
Ok(ExprTree { |
| 104 |
expr, |
| 105 |
backrefs: resolver.backrefs, |
| 106 |
named_groups: resolver.named_groups, |
| 107 |
numeric_capture_group_references: p.numeric_capture_group_references, |
| 108 |
contains_subroutines: p.contains_subroutines, |
| 109 |
self_recursive: p.self_recursive, |
| 110 |
total_groups: resolver.total_groups, |
| 111 |
out_of_range_backref: resolver.out_of_range_backref, |
| 112 |
numbered_groups_ignored: resolver.ignore_numbered_groups, |
| 113 |
}) |
| 114 |
} |
| 115 |
|
| 116 |
fn new(re: &str, flags: u32) -> Parser<'_> { |
| 117 |
Parser { |
| 118 |
re, |
| 119 |
numeric_capture_group_references: false, |
| 120 |
flags, |
| 121 |
contains_subroutines: false, |
| 122 |
self_recursive: false, |
| 123 |
has_named_groups: false, |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
fn parse_re(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 128 |
let (ix, child) = self.parse_branch(ix, depth)?; |
| 129 |
let mut ix = self.optional_whitespace(ix)?; |
| 130 |
if self.re[ix..].starts_with('|') { |
| 131 |
let mut children = vec![child]; |
| 132 |
while self.re[ix..].starts_with('|') { |
| 133 |
ix += 1; |
| 134 |
let (next, child) = self.parse_branch(ix, depth)?; |
| 135 |
children.push(child); |
| 136 |
ix = self.optional_whitespace(next)?; |
| 137 |
} |
| 138 |
return Ok((ix, Expr::Alt(children))); |
| 139 |
} |
| 140 |
Ok((ix, child)) |
| 141 |
} |
| 142 |
|
| 143 |
fn parse_branch(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 144 |
let mut children = Vec::new(); |
| 145 |
let mut ix = ix; |
| 146 |
while ix < self.re.len() { |
| 147 |
let (next, child) = self.parse_piece(ix, depth)?; |
| 148 |
if next == ix { |
| 149 |
break; |
| 150 |
} |
| 151 |
if child != Expr::Empty { |
| 152 |
children.push(child); |
| 153 |
} |
| 154 |
ix = next; |
| 155 |
} |
| 156 |
match children.len() { |
| 157 |
0 => Ok((ix, Expr::Empty)), |
| 158 |
1 => Ok((ix, children.pop().unwrap())), |
| 159 |
_ => Ok((ix, Expr::Concat(children))), |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
fn parse_quantifier( |
| 164 |
&mut self, |
| 165 |
ix: usize, |
| 166 |
start_ix: usize, |
| 167 |
child: Expr, |
| 168 |
) -> Result<(usize, Expr)> { |
| 169 |
let mut ix = self.optional_whitespace(ix)?; |
| 170 |
if ix < self.re.len() { |
| 171 |
let (mut lo, mut hi, user_specified) = match self.re.as_bytes()[ix] { |
| 172 |
b'?' => (0, 1, false), |
| 173 |
b'*' => (0, usize::MAX, false), |
| 174 |
b'+' => (1, usize::MAX, false), |
| 175 |
b'{' => { |
| 176 |
match self.parse_repeat(ix) { |
| 177 |
Ok((next, lo, hi)) => { |
| 178 |
ix = next - 1; |
| 179 |
(lo, hi, true) |
| 180 |
} |
| 181 |
Err(_) => { |
| 182 |
// Invalid repeat syntax, which results in `{` being treated as a literal |
| 183 |
return Ok((ix, child)); |
| 184 |
} |
| 185 |
} |
| 186 |
} |
| 187 |
_ => return Ok((ix, child)), |
| 188 |
}; |
| 189 |
let mut skip = false; |
| 190 |
if !self.is_repeatable(&child) { |
| 191 |
// In Oniguruma mode, `(?:)` followed by a quantifier is a |
| 192 |
// zero-width no-op that Oniguruma silently accepts. Skip |
| 193 |
// past the quantifier and its modifiers, returning Empty. |
| 194 |
// We check `ix > start_ix` to ensure the atom actually consumed |
| 195 |
// input (e.g. a `(?:)` group), as opposed to a bare |
| 196 |
// quantifier with no preceding atom. |
| 197 |
if child == Expr::Empty && ix > start_ix && self.flag(FLAG_ONIGURUMA_MODE) { |
| 198 |
skip = true; |
| 199 |
} else { |
| 200 |
return Err(Error::ParseError(ix, ParseError::TargetNotRepeatable)); |
| 201 |
} |
| 202 |
} |
| 203 |
ix = self.optional_whitespace(ix + 1)?; |
| 204 |
let mut greedy = true; |
| 205 |
if ix < self.re.len() && self.re.as_bytes()[ix] == b'?' { |
| 206 |
greedy = false; |
| 207 |
ix += 1; |
| 208 |
} |
| 209 |
greedy ^= self.flag(FLAG_SWAP_GREED); |
| 210 |
let mut atomic_group = false; |
| 211 |
if self.flag(FLAG_ONIGURUMA_MODE) { |
| 212 |
if hi < lo { |
| 213 |
(lo, hi) = (hi, lo); |
| 214 |
atomic_group = true; |
| 215 |
} else if !user_specified && ix < self.re.len() && self.re.as_bytes()[ix] == b'+' { |
| 216 |
ix += 1; |
| 217 |
atomic_group = true; |
| 218 |
} |
| 219 |
} else if ix < self.re.len() && self.re.as_bytes()[ix] == b'+' { |
| 220 |
ix += 1; |
| 221 |
atomic_group = true; |
| 222 |
} |
| 223 |
if skip { |
| 224 |
return Ok((ix, child)); |
| 225 |
} else { |
| 226 |
let mut node = Expr::Repeat { |
| 227 |
child: Box::new(child), |
| 228 |
lo, |
| 229 |
hi, |
| 230 |
greedy, |
| 231 |
}; |
| 232 |
if atomic_group { |
| 233 |
node = Expr::AtomicGroup(Box::new(node)); |
| 234 |
} |
| 235 |
return Ok((ix, node)); |
| 236 |
} |
| 237 |
} |
| 238 |
Ok((ix, child)) |
| 239 |
} |
| 240 |
|
| 241 |
fn parse_piece(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 242 |
let start = ix; |
| 243 |
let (ix, child) = self.parse_atom(ix, depth)?; |
| 244 |
let (mut ix, mut repeat) = self.parse_quantifier(ix, start, child)?; |
| 245 |
if self.flag(FLAG_ONIGURUMA_MODE) { |
| 246 |
// Oniguruma allows expressions like `\s{1,2}{0,1}` to mean `(?:\s{1,2})?`. |
| 247 |
// Each additional adjacent quantifier wraps the previous result in |
| 248 |
// another `Expr::Repeat` (and `Expr::AtomicGroup` if a possessive |
| 249 |
// `+` modifier follows), increasing AST depth. We count them |
| 250 |
// against the parse recursion budget AND enforce a tighter |
| 251 |
// per-piece cap, because the AST depth interacts multiplicatively |
| 252 |
// with subroutine-call inlining (`\g<...>`) during compile and |
| 253 |
// can otherwise blow the stack on adversarial inputs like |
| 254 |
// Oniguruma test #139. |
| 255 |
const MAX_ADJACENT_QUANTIFIERS: usize = 4; |
| 256 |
let mut depth = depth; |
| 257 |
let mut adjacent = 0; |
| 258 |
loop { |
| 259 |
let before = ix; |
| 260 |
let (next_ix, next_repeat) = self.parse_quantifier(ix, before, repeat)?; |
| 261 |
ix = next_ix; |
| 262 |
repeat = next_repeat; |
| 263 |
if ix == before { |
| 264 |
break; |
| 265 |
} |
| 266 |
adjacent += 1; |
| 267 |
depth += 1; |
| 268 |
if adjacent > MAX_ADJACENT_QUANTIFIERS || depth >= MAX_RECURSION { |
| 269 |
return Err(Error::ParseError(ix, ParseError::RecursionExceeded)); |
| 270 |
} |
| 271 |
} |
| 272 |
} |
| 273 |
Ok((ix, repeat)) |
| 274 |
} |
| 275 |
|
| 276 |
fn is_repeatable(&self, child: &Expr) -> bool { |
| 277 |
match child { |
| 278 |
Expr::LookAround(_, _) => false, |
| 279 |
Expr::Empty => false, |
| 280 |
// In Oniguruma mode, repetition after assertions is not allowed |
| 281 |
Expr::Assertion(_) => !self.flag(FLAG_ONIGURUMA_MODE), |
| 282 |
Expr::KeepOut => false, |
| 283 |
Expr::ContinueFromPreviousMatchEnd => false, |
| 284 |
Expr::BackrefExistsCondition { .. } => false, |
| 285 |
Expr::BacktrackingControlVerb(_) => false, |
| 286 |
_ => true, |
| 287 |
} |
| 288 |
} |
| 289 |
|
| 290 |
// ix, lo, hi |
| 291 |
fn parse_repeat(&self, ix: usize) -> Result<(usize, usize, usize)> { |
| 292 |
let ix = self.optional_whitespace(ix + 1)?; // skip opening '{' |
| 293 |
let bytes = self.re.as_bytes(); |
| 294 |
if ix == self.re.len() { |
| 295 |
return Err(Error::ParseError(ix, ParseError::InvalidRepeat)); |
| 296 |
} |
| 297 |
let mut end = ix; |
| 298 |
let lo = if bytes[ix] == b',' { |
| 299 |
0 |
| 300 |
} else if let Some((next, lo)) = parse_usize(self.re, ix) { |
| 301 |
end = next; |
| 302 |
lo |
| 303 |
} else { |
| 304 |
return Err(Error::ParseError(ix, ParseError::InvalidRepeat)); |
| 305 |
}; |
| 306 |
let ix = self.optional_whitespace(end)?; // past lo number |
| 307 |
if ix == self.re.len() { |
| 308 |
return Err(Error::ParseError(ix, ParseError::InvalidRepeat)); |
| 309 |
} |
| 310 |
end = ix; |
| 311 |
let hi = match bytes[ix] { |
| 312 |
b'}' => lo, |
| 313 |
b',' => { |
| 314 |
end = self.optional_whitespace(ix + 1)?; // past ',' |
| 315 |
if let Some((next, hi)) = parse_usize(self.re, end) { |
| 316 |
end = next; |
| 317 |
hi |
| 318 |
} else { |
| 319 |
usize::MAX |
| 320 |
} |
| 321 |
} |
| 322 |
_ => return Err(Error::ParseError(ix, ParseError::InvalidRepeat)), |
| 323 |
}; |
| 324 |
let ix = self.optional_whitespace(end)?; // past hi number |
| 325 |
if ix == self.re.len() || bytes[ix] != b'}' { |
| 326 |
return Err(Error::ParseError(ix, ParseError::InvalidRepeat)); |
| 327 |
} |
| 328 |
Ok((ix + 1, lo, hi)) |
| 329 |
} |
| 330 |
|
| 331 |
fn parse_atom(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 332 |
let ix = self.optional_whitespace(ix)?; |
| 333 |
if ix == self.re.len() { |
| 334 |
return Ok((ix, Expr::Empty)); |
| 335 |
} |
| 336 |
match self.re.as_bytes()[ix] { |
| 337 |
b'.' => Ok(( |
| 338 |
ix + 1, |
| 339 |
Expr::Any { |
| 340 |
newline: self.flag(FLAG_DOTNL), |
| 341 |
crlf: self.flag(FLAG_CRLF), |
| 342 |
}, |
| 343 |
)), |
| 344 |
b'^' => Ok(( |
| 345 |
ix + 1, |
| 346 |
if self.flag(FLAG_MULTI) { |
| 347 |
if self.flag(FLAG_ONIGURUMA_MODE) { |
| 348 |
Expr::Assertion(Assertion::StartLineOniguruma { |
| 349 |
crlf: self.flag(FLAG_CRLF), |
| 350 |
}) |
| 351 |
} else { |
| 352 |
Expr::Assertion(Assertion::StartLine { |
| 353 |
crlf: self.flag(FLAG_CRLF), |
| 354 |
}) |
| 355 |
} |
| 356 |
} else { |
| 357 |
Expr::Assertion(Assertion::StartText) |
| 358 |
}, |
| 359 |
)), |
| 360 |
b'$' => Ok(( |
| 361 |
ix + 1, |
| 362 |
if self.flag(FLAG_MULTI) { |
| 363 |
Expr::Assertion(Assertion::EndLine { |
| 364 |
crlf: self.flag(FLAG_CRLF), |
| 365 |
}) |
| 366 |
} else { |
| 367 |
Expr::Assertion(Assertion::EndText) |
| 368 |
}, |
| 369 |
)), |
| 370 |
b'(' => self.parse_group(ix, depth), |
| 371 |
b'\\' => self.parse_escape(ix, false), |
| 372 |
b'+' | b'*' | b'?' | b'|' | b')' => Ok((ix, Expr::Empty)), |
| 373 |
b'[' => self.parse_class(ix), |
| 374 |
b => { |
| 375 |
// TODO: maybe want to match multiple codepoints? |
| 376 |
let next = ix + codepoint_len(b); |
| 377 |
Ok(( |
| 378 |
next, |
| 379 |
Expr::Literal { |
| 380 |
val: String::from(&self.re[ix..next]), |
| 381 |
casei: self.flag(FLAG_CASEI), |
| 382 |
}, |
| 383 |
)) |
| 384 |
} |
| 385 |
} |
| 386 |
} |
| 387 |
|
| 388 |
fn parse_delimited_backref( |
| 389 |
&mut self, |
| 390 |
ix: usize, |
| 391 |
open: &str, |
| 392 |
close: &str, |
| 393 |
allow_relative: bool, |
| 394 |
) -> Result<(usize, Expr)> { |
| 395 |
if let Some(ParsedId { id, relative, skip }) = |
| 396 |
parse_id(&self.re[ix..], open, close, allow_relative) |
| 397 |
{ |
| 398 |
let (target, relative_recursion_level) = match (id.is_empty(), relative) { |
| 399 |
// backref with nothing before the + or -, so it is purely a relative group backref |
| 400 |
(true, Some(relative)) => (CaptureGroupTarget::Relative(relative), None), |
| 401 |
(_, relative) => ( |
| 402 |
if let Ok(num) = id.parse::<usize>() { |
| 403 |
CaptureGroupTarget::ByNumber(num) |
| 404 |
} else { |
| 405 |
CaptureGroupTarget::ByName(id.to_string()) |
| 406 |
}, |
| 407 |
relative, |
| 408 |
), |
| 409 |
}; |
| 410 |
|
| 411 |
Ok(( |
| 412 |
ix + skip, |
| 413 |
Expr::AstNode( |
| 414 |
AstNode::Backref { |
| 415 |
target, |
| 416 |
casei: self.flag(FLAG_CASEI), |
| 417 |
relative_recursion_level, |
| 418 |
}, |
| 419 |
ix, |
| 420 |
), |
| 421 |
)) |
| 422 |
} else { |
| 423 |
Err(Error::ParseError(ix, ParseError::InvalidGroupName)) |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
fn parse_delimited_subroutine_call( |
| 428 |
&mut self, |
| 429 |
ix: usize, |
| 430 |
open: &str, |
| 431 |
close: &str, |
| 432 |
allow_relative: bool, |
| 433 |
) -> Result<(usize, Expr)> { |
| 434 |
// First: try unrestricted name (no relative suffix) |
| 435 |
if let Some((name, skip)) = parse_unrestricted_name(&self.re[ix..], open, close) { |
| 436 |
// Check it's not a +N/-N or bare +/- (those should go through the relative path) |
| 437 |
let is_pure_relative = name == "+" |
| 438 |
|| name == "-" |
| 439 |
|| ((name.starts_with('+') || name.starts_with('-')) |
| 440 |
&& name[1..].parse::<usize>().is_ok()); |
| 441 |
|
| 442 |
if !is_pure_relative { |
| 443 |
let target = if let Ok(num) = name.parse::<usize>() { |
| 444 |
self.numeric_capture_group_references = true; |
| 445 |
if num == 0 { |
| 446 |
self.self_recursive = true; |
| 447 |
} |
| 448 |
CaptureGroupTarget::ByNumber(num) |
| 449 |
} else { |
| 450 |
CaptureGroupTarget::ByName(name.to_string()) |
| 451 |
}; |
| 452 |
self.contains_subroutines = true; |
| 453 |
return Ok(( |
| 454 |
ix + skip, |
| 455 |
Expr::AstNode(AstNode::SubroutineCall(target), ix), |
| 456 |
)); |
| 457 |
} |
| 458 |
} |
| 459 |
|
| 460 |
// Second: try as relative reference (+N / -N) |
| 461 |
if allow_relative { |
| 462 |
if let Some(ParsedId { |
| 463 |
id, |
| 464 |
relative: Some(rel), |
| 465 |
skip, |
| 466 |
}) = parse_id(&self.re[ix..], open, close, true) |
| 467 |
{ |
| 468 |
if id.is_empty() { |
| 469 |
let target = CaptureGroupTarget::Relative(rel); |
| 470 |
self.contains_subroutines = true; |
| 471 |
return Ok(( |
| 472 |
ix + skip, |
| 473 |
Expr::AstNode(AstNode::SubroutineCall(target), ix), |
| 474 |
)); |
| 475 |
} |
| 476 |
} |
| 477 |
} |
| 478 |
|
| 479 |
Err(Error::ParseError(ix, ParseError::InvalidGroupName)) |
| 480 |
} |
| 481 |
|
| 482 |
fn parse_unrestricted_subroutine_call( |
| 483 |
&mut self, |
| 484 |
ix: usize, |
| 485 |
open: &str, |
| 486 |
close: &str, |
| 487 |
) -> Result<(usize, Expr)> { |
| 488 |
if let Some((name, skip)) = parse_unrestricted_name(&self.re[ix..], open, close) { |
| 489 |
let target = if let Ok(num) = name.parse::<usize>() { |
| 490 |
self.numeric_capture_group_references = true; |
| 491 |
if num == 0 { |
| 492 |
self.self_recursive = true; |
| 493 |
} |
| 494 |
CaptureGroupTarget::ByNumber(num) |
| 495 |
} else { |
| 496 |
CaptureGroupTarget::ByName(name.to_string()) |
| 497 |
}; |
| 498 |
self.contains_subroutines = true; |
| 499 |
Ok(( |
| 500 |
ix + skip, |
| 501 |
Expr::AstNode(AstNode::SubroutineCall(target), ix), |
| 502 |
)) |
| 503 |
} else { |
| 504 |
Err(Error::ParseError(ix, ParseError::InvalidGroupName)) |
| 505 |
} |
| 506 |
} |
| 507 |
|
| 508 |
fn parse_numbered_backref(&mut self, ix: usize) -> Result<(usize, Expr)> { |
| 509 |
let (end, group) = self.parse_numbered_backref_or_subroutine_call(ix)?; |
| 510 |
self.numeric_capture_group_references = true; |
| 511 |
Ok(( |
| 512 |
end, |
| 513 |
Expr::AstNode( |
| 514 |
AstNode::Backref { |
| 515 |
target: CaptureGroupTarget::ByNumber(group), |
| 516 |
casei: self.flag(FLAG_CASEI), |
| 517 |
relative_recursion_level: None, |
| 518 |
}, |
| 519 |
ix, |
| 520 |
), |
| 521 |
)) |
| 522 |
} |
| 523 |
|
| 524 |
fn parse_numbered_subroutine_call(&mut self, ix: usize) -> Result<(usize, Expr)> { |
| 525 |
let (end, group) = self.parse_numbered_backref_or_subroutine_call(ix)?; |
| 526 |
self.numeric_capture_group_references = true; |
| 527 |
self.contains_subroutines = true; |
| 528 |
if group == 0 { |
| 529 |
self.self_recursive = true; |
| 530 |
} |
| 531 |
Ok((end, Expr::SubroutineCall(group))) |
| 532 |
} |
| 533 |
|
| 534 |
fn parse_numbered_backref_or_subroutine_call(&self, ix: usize) -> Result<(usize, usize)> { |
| 535 |
parse_usize(self.re, ix).ok_or(Error::ParseError(ix, ParseError::InvalidBackref)) |
| 536 |
} |
| 537 |
|
| 538 |
// ix points to \ character |
| 539 |
fn parse_escape(&mut self, ix: usize, in_class: bool) -> Result<(usize, Expr)> { |
| 540 |
let bytes = self.re.as_bytes(); |
| 541 |
let Some(b) = bytes.get(ix + 1).copied() else { |
| 542 |
return Err(Error::ParseError(ix, ParseError::TrailingBackslash)); |
| 543 |
}; |
| 544 |
let end = ix + 1 + codepoint_len(b); |
| 545 |
Ok(if b.is_ascii_digit() { |
| 546 |
return self.parse_numbered_backref(ix + 1); |
| 547 |
} else if matches!(b, b'k') && !in_class { |
| 548 |
// Named backref: \k<name> |
| 549 |
if bytes.get(end) == Some(&b'\'') { |
| 550 |
return self.parse_delimited_backref(end, "'", "'", true); |
| 551 |
} else { |
| 552 |
return self.parse_delimited_backref(end, "<", ">", true); |
| 553 |
} |
| 554 |
} else if b == b'A' && !in_class { |
| 555 |
(end, Expr::Assertion(Assertion::StartText)) |
| 556 |
} else if b == b'z' && !in_class { |
| 557 |
(end, Expr::Assertion(Assertion::EndText)) |
| 558 |
} else if b == b'Z' && !in_class { |
| 559 |
// \Z matches at the end of the string, or before any number of newlines at the end |
| 560 |
( |
| 561 |
end, |
| 562 |
Expr::Assertion(Assertion::EndTextIgnoreTrailingNewlines { |
| 563 |
crlf: self.flag(FLAG_CRLF), |
| 564 |
}), |
| 565 |
) |
| 566 |
} else if (b == b'b' || b == b'B') && !in_class { |
| 567 |
let check_pos = self.optional_whitespace(end)?; |
| 568 |
if bytes.get(check_pos) == Some(&b'{') { |
| 569 |
let next_open_brace_pos = self.optional_whitespace(check_pos + 1)?; |
| 570 |
let is_repetition = matches!( |
| 571 |
bytes.get(next_open_brace_pos), |
| 572 |
Some(&ch) if ch.is_ascii_digit() || ch == b',' |
| 573 |
); |
| 574 |
if !is_repetition { |
| 575 |
return self.parse_word_boundary_brace(ix); |
| 576 |
} |
| 577 |
} |
| 578 |
let expr = if b == b'b' { |
| 579 |
Expr::Assertion(Assertion::WordBoundary) |
| 580 |
} else { |
| 581 |
Expr::Assertion(Assertion::NotWordBoundary) |
| 582 |
}; |
| 583 |
(end, expr) |
| 584 |
} else if b == b'<' && !in_class { |
| 585 |
let expr = if self.flag(FLAG_ONIGURUMA_MODE) { |
| 586 |
make_literal("<") |
| 587 |
} else { |
| 588 |
Expr::Assertion(Assertion::LeftWordBoundary) |
| 589 |
}; |
| 590 |
(end, expr) |
| 591 |
} else if b == b'>' && !in_class { |
| 592 |
let expr = if self.flag(FLAG_ONIGURUMA_MODE) { |
| 593 |
make_literal(">") |
| 594 |
} else { |
| 595 |
Expr::Assertion(Assertion::RightWordBoundary) |
| 596 |
}; |
| 597 |
(end, expr) |
| 598 |
} else if matches!(b | 32, b'd' | b's' | b'w') { |
| 599 |
( |
| 600 |
end, |
| 601 |
Expr::Delegate { |
| 602 |
inner: String::from(&self.re[ix..end]), |
| 603 |
casei: self.flag(FLAG_CASEI), |
| 604 |
}, |
| 605 |
) |
| 606 |
} else if (b | 32) == b'h' { |
| 607 |
let s = if b == b'h' { |
| 608 |
"[0-9A-Fa-f]" |
| 609 |
} else { |
| 610 |
"[^0-9A-Fa-f]" |
| 611 |
}; |
| 612 |
( |
| 613 |
end, |
| 614 |
Expr::Delegate { |
| 615 |
inner: String::from(s), |
| 616 |
casei: false, |
| 617 |
}, |
| 618 |
) |
| 619 |
} else if b == b'x' { |
| 620 |
let end = self.optional_whitespace(end)?; |
| 621 |
return self.parse_hex(end, 2); |
| 622 |
} else if b == b'u' { |
| 623 |
let end = self.optional_whitespace(end)?; |
| 624 |
return self.parse_hex(end, 4); |
| 625 |
} else if b == b'U' { |
| 626 |
let end = self.optional_whitespace(end)?; |
| 627 |
return self.parse_hex(end, 8); |
| 628 |
} else if (b | 32) == b'p' && end != bytes.len() { |
| 629 |
let mut end = end; |
| 630 |
let b = bytes[end]; |
| 631 |
end += codepoint_len(b); |
| 632 |
if b == b'{' { |
| 633 |
loop { |
| 634 |
if end == self.re.len() { |
| 635 |
return Err(Error::ParseError(ix, ParseError::UnclosedUnicodeName)); |
| 636 |
} |
| 637 |
let b = bytes[end]; |
| 638 |
if b == b'}' { |
| 639 |
end += 1; |
| 640 |
break; |
| 641 |
} |
| 642 |
end += codepoint_len(b); |
| 643 |
} |
| 644 |
} |
| 645 |
( |
| 646 |
end, |
| 647 |
Expr::Delegate { |
| 648 |
inner: remap_unicode_property_if_necessary( |
| 649 |
&self.re[ix..end], |
| 650 |
self.flag(FLAG_UNICODE), |
| 651 |
in_class, |
| 652 |
), |
| 653 |
casei: self.flag(FLAG_CASEI), |
| 654 |
}, |
| 655 |
) |
| 656 |
} else if b == b'K' && !in_class { |
| 657 |
(end, Expr::KeepOut) |
| 658 |
} else if b == b'G' && !in_class { |
| 659 |
(end, Expr::ContinueFromPreviousMatchEnd) |
| 660 |
} else if b == b'R' && !in_class { |
| 661 |
( |
| 662 |
end, |
| 663 |
Expr::GeneralNewline { |
| 664 |
unicode: self.flag(FLAG_UNICODE), |
| 665 |
}, |
| 666 |
) |
| 667 |
} else if b == b'O' && !in_class { |
| 668 |
( |
| 669 |
end, |
| 670 |
Expr::Any { |
| 671 |
newline: true, |
| 672 |
crlf: true, |
| 673 |
}, |
| 674 |
) |
| 675 |
} else if b == b'N' && !in_class { |
| 676 |
// \N always means "not a newline" regardless of dot mode flags |
| 677 |
// - just like \n is a literal, this is the inverse |
| 678 |
( |
| 679 |
end, |
| 680 |
Expr::Any { |
| 681 |
newline: false, |
| 682 |
crlf: false, |
| 683 |
}, |
| 684 |
) |
| 685 |
} else if b == b'g' && !in_class { |
| 686 |
if end == self.re.len() { |
| 687 |
return Err(Error::ParseError( |
| 688 |
ix, |
| 689 |
ParseError::InvalidEscape("\\g".to_string()), |
| 690 |
)); |
| 691 |
} |
| 692 |
let b = bytes[end]; |
| 693 |
if b.is_ascii_digit() { |
| 694 |
self.parse_numbered_subroutine_call(end)? |
| 695 |
} else if b == b'\'' { |
| 696 |
self.parse_delimited_subroutine_call(end, "'", "'", true)? |
| 697 |
} else { |
| 698 |
self.parse_delimited_subroutine_call(end, "<", ">", true)? |
| 699 |
} |
| 700 |
} else { |
| 701 |
// printable ASCII (including space, see issue #29) |
| 702 |
( |
| 703 |
end, |
| 704 |
make_literal(match b { |
| 705 |
b'a' => "\x07", // BEL |
| 706 |
b'b' => "\x08", // BS |
| 707 |
b'f' => "\x0c", // FF |
| 708 |
b'n' => "\n", // LF |
| 709 |
b'r' => "\r", // CR |
| 710 |
b't' => "\t", // TAB |
| 711 |
b'v' => "\x0b", // VT |
| 712 |
b'e' => "\x1b", // ESC |
| 713 |
b' ' => " ", |
| 714 |
b => { |
| 715 |
let s = &self.re[ix + 1..end]; |
| 716 |
if b.is_ascii_alphabetic() |
| 717 |
&& !matches!( |
| 718 |
b, |
| 719 |
b'k' | b'A' | b'z' | b'b' | b'B' | b'<' | b'>' | b'K' | b'G' | b'R' |
| 720 |
) |
| 721 |
{ |
| 722 |
return Err(Error::ParseError( |
| 723 |
ix, |
| 724 |
ParseError::InvalidEscape(format!("\\{}", s)), |
| 725 |
)); |
| 726 |
} else { |
| 727 |
s |
| 728 |
} |
| 729 |
} |
| 730 |
}), |
| 731 |
) |
| 732 |
}) |
| 733 |
} |
| 734 |
|
| 735 |
// ix points after '\x', eg to 'A0' or '{12345}', or after `\u` or `\U` |
| 736 |
fn parse_hex(&self, ix: usize, digits: usize) -> Result<(usize, Expr)> { |
| 737 |
if ix >= self.re.len() { |
| 738 |
// Incomplete escape sequence |
| 739 |
return Err(Error::ParseError(ix, ParseError::InvalidHex)); |
| 740 |
} |
| 741 |
let bytes = self.re.as_bytes(); |
| 742 |
let b = bytes[ix]; |
| 743 |
// Parse fixed-width hex (e.g., \xAB) |
| 744 |
if ix + digits <= self.re.len() && bytes[ix..ix + digits].iter().all(|&b| is_hex_digit(b)) { |
| 745 |
let hex_str = &self.re[ix..ix + digits]; |
| 746 |
return self.hex_to_literal(ix, ix + digits, hex_str); |
| 747 |
} |
| 748 |
// Parse brace-enclosed hex (e.g., \u{00AB}) |
| 749 |
if b == b'{' { |
| 750 |
let mut pos = ix + 1; |
| 751 |
let mut hex_chars = String::new(); |
| 752 |
while pos < self.re.len() { |
| 753 |
// Skip whitespace/comments if FLAG_IGNORE_SPACE is set |
| 754 |
pos = self.optional_whitespace(pos)?; |
| 755 |
if pos >= self.re.len() { |
| 756 |
return Err(Error::ParseError(ix, ParseError::InvalidHex)); |
| 757 |
} |
| 758 |
let b = bytes[pos]; |
| 759 |
if b == b'}' && !hex_chars.is_empty() { |
| 760 |
return self.hex_to_literal(ix, pos + 1, &hex_chars); |
| 761 |
} |
| 762 |
if is_hex_digit(b) && hex_chars.len() < 8 { |
| 763 |
hex_chars.push(b as char); |
| 764 |
pos += 1; |
| 765 |
} else { |
| 766 |
return Err(Error::ParseError(ix, ParseError::InvalidHex)); |
| 767 |
} |
| 768 |
} |
| 769 |
} |
| 770 |
Err(Error::ParseError(ix, ParseError::InvalidHex)) |
| 771 |
} |
| 772 |
|
| 773 |
fn hex_to_literal(&self, ix: usize, end: usize, hex_str: &str) -> Result<(usize, Expr)> { |
| 774 |
let codepoint = u32::from_str_radix(hex_str, 16).unwrap(); |
| 775 |
if let Some(c) = char::from_u32(codepoint) { |
| 776 |
Ok(( |
| 777 |
end, |
| 778 |
Expr::Literal { |
| 779 |
val: c.to_string(), |
| 780 |
casei: self.flag(FLAG_CASEI), |
| 781 |
}, |
| 782 |
)) |
| 783 |
} else { |
| 784 |
Err(Error::ParseError(ix, ParseError::InvalidCodepointValue)) |
| 785 |
} |
| 786 |
} |
| 787 |
|
| 788 |
// ix points before '\b' or '\B' |
| 789 |
fn parse_word_boundary_brace(&self, ix: usize) -> Result<(usize, Expr)> { |
| 790 |
let bytes = self.re.as_bytes(); |
| 791 |
|
| 792 |
// Verify that we have '\b' or '\B' |
| 793 |
if !matches!(bytes.get(ix..ix + 2), Some([b'\\', b'b' | b'B'])) { |
| 794 |
return Err(Error::ParseError( |
| 795 |
ix, |
| 796 |
ParseError::InvalidEscape("\\b{...}".to_string()), |
| 797 |
)); |
| 798 |
} |
| 799 |
// Skip whitespace/comments after \b or \B if FLAG_IGNORE_SPACE is set |
| 800 |
let brace_start = self.optional_whitespace(ix + 2)?; |
| 801 |
// Verify we have '{' |
| 802 |
if bytes.get(brace_start) != Some(&b'{') { |
| 803 |
return Err(Error::ParseError( |
| 804 |
ix, |
| 805 |
ParseError::InvalidEscape("\\b{...}".to_string()), |
| 806 |
)); |
| 807 |
} |
| 808 |
// Extract content between braces |
| 809 |
let mut pos = brace_start + 1; |
| 810 |
let mut content = String::new(); |
| 811 |
while pos < self.re.len() { |
| 812 |
let b = bytes[pos]; |
| 813 |
if b == b'}' { |
| 814 |
break; |
| 815 |
} |
| 816 |
// Skip whitespace/comments if FLAG_IGNORE_SPACE is set |
| 817 |
let next_pos = self.optional_whitespace(pos)?; |
| 818 |
if next_pos > pos { |
| 819 |
// Whitespace was skipped |
| 820 |
pos = next_pos; |
| 821 |
if pos >= self.re.len() || bytes[pos] == b'}' { |
| 822 |
break; |
| 823 |
} |
| 824 |
} |
| 825 |
// Add non-whitespace character to content |
| 826 |
let b = bytes[pos]; |
| 827 |
if b != b'}' { |
| 828 |
content.push(b as char); |
| 829 |
pos += codepoint_len(b); |
| 830 |
} |
| 831 |
} |
| 832 |
|
| 833 |
let end_brace = pos; |
| 834 |
if end_brace >= self.re.len() || bytes[end_brace] != b'}' { |
| 835 |
return Err(Error::ParseError( |
| 836 |
ix, |
| 837 |
ParseError::InvalidEscape("\\b{...}".to_string()), |
| 838 |
)); |
| 839 |
} |
| 840 |
|
| 841 |
// \B{...} is not supported |
| 842 |
if bytes[ix + 1] == b'B' { |
| 843 |
return Err(Error::ParseError( |
| 844 |
ix, |
| 845 |
ParseError::InvalidEscape(format!("\\B{{{}}}", content)), |
| 846 |
)); |
| 847 |
} |
| 848 |
|
| 849 |
let expr = match content.as_str() { |
| 850 |
"start" => Expr::Assertion(Assertion::LeftWordBoundary), |
| 851 |
"end" => Expr::Assertion(Assertion::RightWordBoundary), |
| 852 |
"start-half" => Expr::Assertion(Assertion::LeftWordHalfBoundary), |
| 853 |
"end-half" => Expr::Assertion(Assertion::RightWordHalfBoundary), |
| 854 |
_ => { |
| 855 |
return Err(Error::ParseError( |
| 856 |
ix, |
| 857 |
ParseError::InvalidEscape(format!("\\b{{{}}}", content)), |
| 858 |
)); |
| 859 |
} |
| 860 |
}; |
| 861 |
|
| 862 |
Ok((end_brace + 1, expr)) |
| 863 |
} |
| 864 |
|
| 865 |
fn parse_class(&mut self, ix: usize) -> Result<(usize, Expr)> { |
| 866 |
let bytes = self.re.as_bytes(); |
| 867 |
let mut ix = ix + 1; // skip opening '[' |
| 868 |
let mut class = String::new(); |
| 869 |
let mut nest = 1; |
| 870 |
let mut seen_negated_property = false; |
| 871 |
class.push('['); |
| 872 |
|
| 873 |
// Negated character class |
| 874 |
if bytes.get(ix) == Some(&b'^') { |
| 875 |
class.push('^'); |
| 876 |
ix += 1; |
| 877 |
} |
| 878 |
|
| 879 |
// `]` does not have to be escaped after opening `[` or `[^` |
| 880 |
if bytes.get(ix) == Some(&b']') { |
| 881 |
class.push(']'); |
| 882 |
ix += 1; |
| 883 |
} |
| 884 |
|
| 885 |
loop { |
| 886 |
if ix == self.re.len() { |
| 887 |
return Err(Error::ParseError(ix, ParseError::InvalidClass)); |
| 888 |
} |
| 889 |
let end = match bytes[ix] { |
| 890 |
b'\\' => { |
| 891 |
// We support more escapes than regex, so parse it ourselves before delegating. |
| 892 |
let (end, expr) = self.parse_escape(ix, true)?; |
| 893 |
match expr { |
| 894 |
Expr::Literal { val, .. } => { |
| 895 |
debug_assert_eq!(val.chars().count(), 1); |
| 896 |
escape_into(&val, &mut class); |
| 897 |
} |
| 898 |
Expr::Delegate { inner, .. } => { |
| 899 |
// Check if this is a negated property that needs && prefix |
| 900 |
// A negated property is a nested character class that starts with [^ and contains |
| 901 |
// Unicode property patterns or POSIX classes |
| 902 |
let is_negated_prop = inner.starts_with("[^") |
| 903 |
&& (inner.contains(r"\p{") |
| 904 |
|| inner.contains(r"\P{") |
| 905 |
|| inner.contains("[:")); |
| 906 |
if is_negated_prop { |
| 907 |
if seen_negated_property { |
| 908 |
// This is not the first negated property, add && |
| 909 |
class.push_str("&&"); |
| 910 |
} |
| 911 |
// Mark that we've seen a negated property |
| 912 |
seen_negated_property = true; |
| 913 |
} |
| 914 |
class.push_str(&inner); |
| 915 |
} |
| 916 |
_ => { |
| 917 |
return Err(Error::ParseError(ix, ParseError::InvalidClass)); |
| 918 |
} |
| 919 |
} |
| 920 |
end |
| 921 |
} |
| 922 |
b'[' => { |
| 923 |
nest += 1; |
| 924 |
class.push('['); |
| 925 |
let mut end = ix + 1; |
| 926 |
|
| 927 |
// Handle `]` after `[` or `[^` in nested classes |
| 928 |
// Check for negated character class |
| 929 |
if bytes.get(end) == Some(&b'^') { |
| 930 |
class.push('^'); |
| 931 |
end += 1; |
| 932 |
} |
| 933 |
|
| 934 |
// `]` does not have to be escaped after opening `[` or `[^` |
| 935 |
if bytes.get(end) == Some(&b']') { |
| 936 |
class.push(']'); |
| 937 |
end += 1; |
| 938 |
} |
| 939 |
|
| 940 |
end |
| 941 |
} |
| 942 |
b']' => { |
| 943 |
nest -= 1; |
| 944 |
class.push(']'); |
| 945 |
if nest == 0 { |
| 946 |
break; |
| 947 |
} |
| 948 |
ix + 1 |
| 949 |
} |
| 950 |
b => { |
| 951 |
let end = ix + codepoint_len(b); |
| 952 |
class.push_str(&self.re[ix..end]); |
| 953 |
end |
| 954 |
} |
| 955 |
}; |
| 956 |
ix = end; |
| 957 |
} |
| 958 |
let class = Expr::Delegate { |
| 959 |
inner: class, |
| 960 |
casei: self.flag(FLAG_CASEI), |
| 961 |
}; |
| 962 |
let ix = ix + 1; // skip closing ']' |
| 963 |
Ok((ix, class)) |
| 964 |
} |
| 965 |
|
| 966 |
fn parse_group(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 967 |
let depth = depth + 1; |
| 968 |
if depth >= MAX_RECURSION { |
| 969 |
return Err(Error::ParseError(ix, ParseError::RecursionExceeded)); |
| 970 |
} |
| 971 |
let open_paren_ix = ix; // position of the opening `(` |
| 972 |
let ix = self.optional_whitespace(ix + 1)?; |
| 973 |
let mut group_name = None; |
| 974 |
let (la, skip) = if self.re[ix..].starts_with("?=") { |
| 975 |
(Some(LookAhead), 2) |
| 976 |
} else if self.re[ix..].starts_with("?!") { |
| 977 |
(Some(LookAheadNeg), 2) |
| 978 |
} else if self.re[ix..].starts_with("?<=") { |
| 979 |
(Some(LookBehind), 3) |
| 980 |
} else if self.re[ix..].starts_with("?<!") { |
| 981 |
(Some(LookBehindNeg), 3) |
| 982 |
} else if self.re[ix..].starts_with("?<") || self.re[ix..].starts_with("?'") { |
| 983 |
// Named capture group using Oniguruma syntax: (?<name>...) or (?'name'...) |
| 984 |
let (open, close) = if self.re[ix..].starts_with("?<") { |
| 985 |
("<", ">") |
| 986 |
} else { |
| 987 |
("'", "'") |
| 988 |
}; |
| 989 |
if let Some((name, skip)) = parse_unrestricted_name(&self.re[ix + 1..], open, close) { |
| 990 |
group_name = Some(name.to_string()); |
| 991 |
self.has_named_groups = true; |
| 992 |
(None, skip + 1) |
| 993 |
} else { |
| 994 |
return Err(Error::ParseError(ix, ParseError::InvalidGroupName)); |
| 995 |
} |
| 996 |
} else if self.re[ix..].starts_with("?P<") { |
| 997 |
// Named capture group using Python syntax: (?P<name>...) |
| 998 |
if let Some((name, skip)) = parse_unrestricted_name(&self.re[ix + 2..], "<", ">") { |
| 999 |
group_name = Some(name.to_string()); |
| 1000 |
self.has_named_groups = true; |
| 1001 |
(None, skip + 2) |
| 1002 |
} else { |
| 1003 |
return Err(Error::ParseError(ix, ParseError::InvalidGroupName)); |
| 1004 |
} |
| 1005 |
} else if self.re[ix..].starts_with("?P=") { |
| 1006 |
// Backref using Python syntax: (?P=name) |
| 1007 |
return self.parse_delimited_backref(ix + 3, "", ")", false); |
| 1008 |
} else if self.re[ix..].starts_with("?~") { |
| 1009 |
return self.parse_absent(ix + 1, depth); |
| 1010 |
} else if self.re[ix..].starts_with("?>") { |
| 1011 |
(None, 2) |
| 1012 |
} else if self.re[ix..].starts_with("?(") { |
| 1013 |
return self.parse_conditional(ix + 2, depth); |
| 1014 |
} else if self.re[ix..].starts_with("?P>") { |
| 1015 |
return self.parse_unrestricted_subroutine_call(ix + 3, "", ")"); |
| 1016 |
} else if self.re[ix..].starts_with("*") { |
| 1017 |
return self.parse_backtracking_control_verb(ix); |
| 1018 |
} else if self.re[ix..].starts_with('?') { |
| 1019 |
return self.parse_flags(ix, depth); |
| 1020 |
} else { |
| 1021 |
(None, 0) |
| 1022 |
}; |
| 1023 |
let ix = ix + skip; |
| 1024 |
let (ix, child) = self.parse_re(ix, depth)?; |
| 1025 |
let ix = self.check_for_close_paren(ix)?; |
| 1026 |
let result = match (la, skip) { |
| 1027 |
(Some(la), _) => Expr::LookAround(Box::new(child), la), |
| 1028 |
(None, 2) => Expr::AtomicGroup(Box::new(child)), |
| 1029 |
_ => make_ast_group(child, group_name, open_paren_ix), |
| 1030 |
}; |
| 1031 |
Ok((ix, result)) |
| 1032 |
} |
| 1033 |
|
| 1034 |
fn check_for_close_paren(&self, ix: usize) -> Result<usize> { |
| 1035 |
let ix = self.optional_whitespace(ix)?; |
| 1036 |
if ix == self.re.len() { |
| 1037 |
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen)); |
| 1038 |
} else if self.re.as_bytes()[ix] != b')' { |
| 1039 |
return Err(Error::ParseError( |
| 1040 |
ix, |
| 1041 |
ParseError::GeneralParseError("expected close paren".to_string()), |
| 1042 |
)); |
| 1043 |
} |
| 1044 |
Ok(ix + 1) |
| 1045 |
} |
| 1046 |
|
| 1047 |
// ix points to `?` in `(?` |
| 1048 |
fn parse_flags(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 1049 |
let start = ix + 1; |
| 1050 |
|
| 1051 |
fn unknown_flag(re: &str, start: usize, end: usize) -> Error { |
| 1052 |
let after_end = end + codepoint_len(re.as_bytes()[end]); |
| 1053 |
let s = format!("(?{}", &re[start..after_end]); |
| 1054 |
Error::ParseError(start, ParseError::UnknownFlag(s)) |
| 1055 |
} |
| 1056 |
|
| 1057 |
let mut ix = start; |
| 1058 |
let mut neg = false; |
| 1059 |
let oldflags = self.flags; |
| 1060 |
loop { |
| 1061 |
ix = self.optional_whitespace(ix)?; |
| 1062 |
if ix == self.re.len() { |
| 1063 |
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen)); |
| 1064 |
} |
| 1065 |
let b = self.re.as_bytes()[ix]; |
| 1066 |
match b { |
| 1067 |
b'i' => self.update_flag(FLAG_CASEI, neg), |
| 1068 |
b'm' => self.update_flag(FLAG_MULTI, neg), |
| 1069 |
b'R' => self.update_flag(FLAG_CRLF, neg), |
| 1070 |
b's' => self.update_flag(FLAG_DOTNL, neg), |
| 1071 |
b'U' => self.update_flag(FLAG_SWAP_GREED, neg), |
| 1072 |
b'x' => self.update_flag(FLAG_IGNORE_SPACE, neg), |
| 1073 |
b'u' => { |
| 1074 |
if neg == self.flag(FLAG_UNICODE) { |
| 1075 |
return Err(Error::ParseError( |
| 1076 |
ix, |
| 1077 |
ParseError::ChangingUnicodeModeUnsupported, |
| 1078 |
)); |
| 1079 |
} |
| 1080 |
} |
| 1081 |
b'-' => { |
| 1082 |
if neg { |
| 1083 |
return Err(unknown_flag(self.re, start, ix)); |
| 1084 |
} |
| 1085 |
neg = true; |
| 1086 |
} |
| 1087 |
b')' => { |
| 1088 |
if ix == start || neg && ix == start + 1 { |
| 1089 |
return Err(unknown_flag(self.re, start, ix)); |
| 1090 |
} |
| 1091 |
return Ok((ix + 1, Expr::Empty)); |
| 1092 |
} |
| 1093 |
b':' => { |
| 1094 |
if neg && ix == start + 1 { |
| 1095 |
return Err(unknown_flag(self.re, start, ix)); |
| 1096 |
} |
| 1097 |
ix += 1; |
| 1098 |
let (ix, child) = self.parse_re(ix, depth)?; |
| 1099 |
if ix == self.re.len() { |
| 1100 |
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen)); |
| 1101 |
} else if self.re.as_bytes()[ix] != b')' { |
| 1102 |
return Err(Error::ParseError( |
| 1103 |
ix, |
| 1104 |
ParseError::GeneralParseError("expected close paren".to_string()), |
| 1105 |
)); |
| 1106 |
}; |
| 1107 |
self.flags = oldflags; |
| 1108 |
return Ok((ix + 1, child)); |
| 1109 |
} |
| 1110 |
_ => return Err(unknown_flag(self.re, start, ix)), |
| 1111 |
} |
| 1112 |
ix += 1; |
| 1113 |
} |
| 1114 |
} |
| 1115 |
|
| 1116 |
/// Parse the target of a backref-exists condition — e.g. `1`, `name`, `+1`, `-1` — from |
| 1117 |
/// the delimited form used in `(?(...)...)`. Returns an `AstNode::BackrefExistsCondition` |
| 1118 |
/// expression on success. |
| 1119 |
fn parse_condition_target( |
| 1120 |
&mut self, |
| 1121 |
ix: usize, |
| 1122 |
open: &str, |
| 1123 |
close: &str, |
| 1124 |
allow_relative: bool, |
| 1125 |
) -> Result<(usize, Expr)> { |
| 1126 |
if let Some(ParsedId { id, relative, skip }) = |
| 1127 |
parse_id(&self.re[ix..], open, close, allow_relative) |
| 1128 |
{ |
| 1129 |
let (target, relative_recursion_level) = match (id.is_empty(), relative) { |
| 1130 |
// purely relative group reference: `(?(-1)...)` or `(?(+2)...)` |
| 1131 |
(true, Some(relative)) => (CaptureGroupTarget::Relative(relative), None), |
| 1132 |
(_, relative) => { |
| 1133 |
if let Ok(num) = id.parse::<usize>() { |
| 1134 |
(CaptureGroupTarget::ByNumber(num), relative) |
| 1135 |
} else { |
| 1136 |
(CaptureGroupTarget::ByName(id.to_string()), relative) |
| 1137 |
} |
| 1138 |
} |
| 1139 |
}; |
| 1140 |
Ok(( |
| 1141 |
ix + skip, |
| 1142 |
Expr::AstNode( |
| 1143 |
AstNode::BackrefExistsCondition { |
| 1144 |
target, |
| 1145 |
relative_recursion_level, |
| 1146 |
}, |
| 1147 |
ix, |
| 1148 |
), |
| 1149 |
)) |
| 1150 |
} else { |
| 1151 |
Err(Error::ParseError(ix, ParseError::InvalidGroupName)) |
| 1152 |
} |
| 1153 |
} |
| 1154 |
|
| 1155 |
// ix points to after the last ( in (?( |
| 1156 |
fn parse_conditional(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 1157 |
if ix >= self.re.len() { |
| 1158 |
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen)); |
| 1159 |
} |
| 1160 |
let bytes = self.re.as_bytes(); |
| 1161 |
// get the character after the open paren |
| 1162 |
let b = bytes[ix]; |
| 1163 |
|
| 1164 |
// Check for DEFINE condition first - (?(DEFINE)...) |
| 1165 |
if self.re[ix..].starts_with("DEFINE)") { |
| 1166 |
let end = ix + "DEFINE)".len(); |
| 1167 |
let (end, definitions) = self.parse_re(end, depth)?; |
| 1168 |
let after = self.check_for_close_paren(end)?; |
| 1169 |
return Ok(( |
| 1170 |
after, |
| 1171 |
Expr::DefineGroup { |
| 1172 |
definitions: Box::new(definitions), |
| 1173 |
}, |
| 1174 |
)); |
| 1175 |
} |
| 1176 |
|
| 1177 |
let (next, condition) = if b == b'\'' { |
| 1178 |
self.parse_condition_target(ix, "'", "')", true)? |
| 1179 |
} else if b == b'<' { |
| 1180 |
self.parse_condition_target(ix, "<", ">)", true)? |
| 1181 |
} else if b == b'+' || b == b'-' || b.is_ascii_digit() { |
| 1182 |
self.parse_condition_target(ix, "", ")", true)? |
| 1183 |
} else if b == b'*' { |
| 1184 |
self.parse_backtracking_control_verb(ix)? |
| 1185 |
} else { |
| 1186 |
let (next, condition) = self.parse_re(ix, depth)?; |
| 1187 |
(self.check_for_close_paren(next)?, condition) |
| 1188 |
}; |
| 1189 |
let (end, child) = self.parse_re(next, depth)?; |
| 1190 |
if end == next { |
| 1191 |
// The condition had no branches, so it is a backref-exists-only condition |
| 1192 |
// (e.g. `(?(1))`). The delimited paths already produce AstNode::BackrefExistsCondition |
| 1193 |
// directly; for the general parse_re path we require an expression. |
| 1194 |
if matches!( |
| 1195 |
condition, |
| 1196 |
Expr::AstNode(AstNode::BackrefExistsCondition { .. }, _) |
| 1197 |
) { |
| 1198 |
let after = self.check_for_close_paren(end)?; |
| 1199 |
return Ok((after, condition)); |
| 1200 |
} else { |
| 1201 |
return Err(Error::ParseError( |
| 1202 |
end, |
| 1203 |
ParseError::GeneralParseError( |
| 1204 |
"expected conditional to be a backreference or at least an expression for when the condition is true".to_string() |
| 1205 |
) |
| 1206 |
)); |
| 1207 |
} |
| 1208 |
} |
| 1209 |
let if_true: Expr; |
| 1210 |
let mut if_false: Expr = Expr::Empty; |
| 1211 |
if let Expr::Alt(mut alternatives) = child { |
| 1212 |
// the truth branch will be the first alternative |
| 1213 |
if_true = alternatives.remove(0); |
| 1214 |
// if there is only one alternative left, take it out the Expr::Alt |
| 1215 |
if alternatives.len() == 1 { |
| 1216 |
if_false = alternatives.pop().expect("expected 2 alternatives"); |
| 1217 |
} else { |
| 1218 |
// otherwise the remaining branches become the false branch |
| 1219 |
if_false = Expr::Alt(alternatives); |
| 1220 |
} |
| 1221 |
} else { |
| 1222 |
// there is only one branch - the truth branch. i.e. "if" without "else" |
| 1223 |
if_true = child; |
| 1224 |
} |
| 1225 |
let inner_condition = condition; |
| 1226 |
|
| 1227 |
let after = self.check_for_close_paren(end)?; |
| 1228 |
Ok(( |
| 1229 |
after, |
| 1230 |
if if_true == Expr::Empty && if_false == Expr::Empty { |
| 1231 |
inner_condition |
| 1232 |
} else { |
| 1233 |
Expr::Conditional { |
| 1234 |
condition: Box::new(inner_condition), |
| 1235 |
true_branch: Box::new(if_true), |
| 1236 |
false_branch: Box::new(if_false), |
| 1237 |
} |
| 1238 |
}, |
| 1239 |
)) |
| 1240 |
} |
| 1241 |
|
| 1242 |
// ix points to * after ( |
| 1243 |
fn parse_backtracking_control_verb(&mut self, ix: usize) -> Result<(usize, Expr)> { |
| 1244 |
if self.re[ix..].starts_with("*FAIL)") { |
| 1245 |
Ok(( |
| 1246 |
ix + "*FAIL)".len(), |
| 1247 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Fail), |
| 1248 |
)) |
| 1249 |
} else if self.re[ix..].starts_with("*F)") { |
| 1250 |
Ok(( |
| 1251 |
ix + "*F)".len(), |
| 1252 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Fail), |
| 1253 |
)) |
| 1254 |
} else if self.re[ix..].starts_with("*ACCEPT)") { |
| 1255 |
Ok(( |
| 1256 |
ix + "*ACCEPT)".len(), |
| 1257 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Accept), |
| 1258 |
)) |
| 1259 |
} else if self.re[ix..].starts_with("*COMMIT)") { |
| 1260 |
Ok(( |
| 1261 |
ix + "*COMMIT)".len(), |
| 1262 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Commit), |
| 1263 |
)) |
| 1264 |
} else if self.re[ix..].starts_with("*SKIP)") { |
| 1265 |
Ok(( |
| 1266 |
ix + "*SKIP)".len(), |
| 1267 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Skip), |
| 1268 |
)) |
| 1269 |
} else if self.re[ix..].starts_with("*PRUNE)") { |
| 1270 |
Ok(( |
| 1271 |
ix + "*PRUNE)".len(), |
| 1272 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Prune), |
| 1273 |
)) |
| 1274 |
} else { |
| 1275 |
Err(Error::ParseError(ix, ParseError::TargetNotRepeatable)) |
| 1276 |
} |
| 1277 |
} |
| 1278 |
|
| 1279 |
// ix points to ~ after (? |
| 1280 |
fn parse_absent(&mut self, ix: usize, depth: usize) -> Result<(usize, Expr)> { |
| 1281 |
let ix = ix + 1; // skip `~` character |
| 1282 |
if ix >= self.re.len() { |
| 1283 |
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen)); |
| 1284 |
} |
| 1285 |
|
| 1286 |
if self.re[ix..].starts_with('|') { |
| 1287 |
// (?~|...) - either absent expression, absent stopper, or range clear |
| 1288 |
let ix = ix + 1; // skip `|` character |
| 1289 |
|
| 1290 |
// Parse the absent part (up to | or )) |
| 1291 |
let (ix, absent) = self.parse_branch(ix, depth)?; |
| 1292 |
|
| 1293 |
if ix >= self.re.len() { |
| 1294 |
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen)); |
| 1295 |
} |
| 1296 |
|
| 1297 |
if self.re.as_bytes()[ix] == b'|' { |
| 1298 |
// (?~|absent|exp) - absent expression |
| 1299 |
let ix = ix + 1; // skip | |
| 1300 |
let (ix, exp) = self.parse_branch(ix, depth)?; |
| 1301 |
let ix = self.check_for_close_paren(ix)?; |
| 1302 |
Ok(( |
| 1303 |
ix, |
| 1304 |
Expr::Absent(Absent::Expression { |
| 1305 |
absent: Box::new(absent), |
| 1306 |
exp: Box::new(exp), |
| 1307 |
}), |
| 1308 |
)) |
| 1309 |
} else if self.re.as_bytes()[ix] == b')' { |
| 1310 |
// (?~|absent) - absent stopper, or (?~|) - range clear |
| 1311 |
if absent == Expr::Empty { |
| 1312 |
Ok((ix + 1, Expr::Absent(Absent::Clear))) |
| 1313 |
} else { |
| 1314 |
Ok((ix + 1, Expr::Absent(Absent::Stopper(Box::new(absent))))) |
| 1315 |
} |
| 1316 |
} else { |
| 1317 |
Err(Error::ParseError( |
| 1318 |
ix, |
| 1319 |
ParseError::GeneralParseError( |
| 1320 |
"expected '|' or ')' in absent expression".to_string(), |
| 1321 |
), |
| 1322 |
)) |
| 1323 |
} |
| 1324 |
} else { |
| 1325 |
// (?~absent) - absent repeater |
| 1326 |
let (ix, absent) = self.parse_re(ix, depth)?; |
| 1327 |
let ix = self.check_for_close_paren(ix)?; |
| 1328 |
Ok((ix, Expr::Absent(Absent::Repeater(Box::new(absent))))) |
| 1329 |
} |
| 1330 |
} |
| 1331 |
|
| 1332 |
fn flag(&self, flag: u32) -> bool { |
| 1333 |
let v = self.flags & flag; |
| 1334 |
v == flag |
| 1335 |
} |
| 1336 |
|
| 1337 |
fn update_flag(&mut self, flag: u32, neg: bool) { |
| 1338 |
if neg { |
| 1339 |
self.flags &= !flag; |
| 1340 |
} else { |
| 1341 |
self.flags |= flag; |
| 1342 |
} |
| 1343 |
} |
| 1344 |
|
| 1345 |
fn optional_whitespace(&self, mut ix: usize) -> Result<usize> { |
| 1346 |
let bytes = self.re.as_bytes(); |
| 1347 |
loop { |
| 1348 |
if ix == self.re.len() { |
| 1349 |
return Ok(ix); |
| 1350 |
} |
| 1351 |
match bytes[ix] { |
| 1352 |
b'#' if self.flag(FLAG_IGNORE_SPACE) => { |
| 1353 |
match bytes[ix..].iter().position(|&c| c == b'\n') { |
| 1354 |
Some(x) => ix += x + 1, |
| 1355 |
None => return Ok(self.re.len()), |
| 1356 |
} |
| 1357 |
} |
| 1358 |
b' ' | b'\r' | b'\n' | b'\t' if self.flag(FLAG_IGNORE_SPACE) => ix += 1, |
| 1359 |
b'(' if bytes[ix..].starts_with(b"(?#") => { |
| 1360 |
ix += 3; |
| 1361 |
loop { |
| 1362 |
if ix >= self.re.len() { |
| 1363 |
return Err(Error::ParseError(ix, ParseError::UnclosedOpenParen)); |
| 1364 |
} |
| 1365 |
match bytes[ix] { |
| 1366 |
b')' => { |
| 1367 |
ix += 1; |
| 1368 |
break; |
| 1369 |
} |
| 1370 |
b'\\' => ix += 2, |
| 1371 |
_ => ix += 1, |
| 1372 |
} |
| 1373 |
} |
| 1374 |
} |
| 1375 |
_ => return Ok(ix), |
| 1376 |
} |
| 1377 |
} |
| 1378 |
} |
| 1379 |
} |
| 1380 |
|
| 1381 |
struct Resolver { |
| 1382 |
named_groups: NamedGroups, |
| 1383 |
backrefs: BitSet, |
| 1384 |
/// Maps each named group's name to the byte offset of its opening `(` in the pattern. |
| 1385 |
/// Used to enforce that named backrefs (`\k<name>`) cannot refer to groups that appear |
| 1386 |
/// later in the pattern (forward references by name are not supported for backrefs, |
| 1387 |
/// only for subroutine calls). |
| 1388 |
named_group_positions: NamedGroups, |
| 1389 |
ignore_numbered_groups: bool, |
| 1390 |
next_group_index: usize, |
| 1391 |
/// Total number of capture groups in the pattern, set after the first resolution pass. |
| 1392 |
/// Used to guard `backrefs` BitSet insertions against unreasonably large group numbers. |
| 1393 |
total_groups: usize, |
| 1394 |
/// The first backreference group number that exceeds `total_groups`, if any. Such numbers |
| 1395 |
/// are not inserted into `backrefs` to avoid allocating memory proportional to the raw value. |
| 1396 |
out_of_range_backref: Option<usize>, |
| 1397 |
/// The number of the most recently opened capture group, mirroring the old single-pass |
| 1398 |
/// parser's `curr_group` counter. It is updated each time a `Group` node is entered |
| 1399 |
/// during `resolve_capture_group_targets`, and never decremented, so that a relative |
| 1400 |
/// backref at any position sees the same value the old parser would have had at that |
| 1401 |
/// point in its left-to-right scan. |
| 1402 |
curr_group: usize, |
| 1403 |
} |
| 1404 |
|
| 1405 |
impl Resolver { |
| 1406 |
// resolving is a two step process. |
| 1407 |
// On pass 1, we resolve named and numbered groups. |
| 1408 |
// On pass 2, we resolve subroutine calls. |
| 1409 |
// We can't do this in one pass because they may be forward references by name, and we don't know what index |
| 1410 |
// that named group will be assigned yet in pass 1 |
| 1411 |
// It is okay if a backref or subroutine call is to a capture group index which doesn't exist |
| 1412 |
// - the analyzer will detect it |
| 1413 |
fn resolve_groups(&mut self, expr: &mut Expr) { |
| 1414 |
if let Expr::AstNode(AstNode::AstGroup { .. }, _) = expr { |
| 1415 |
// Move the AstNode out of `expr` by swapping in a sentinel, freeing the borrow so |
| 1416 |
// we can destructure and move the inner Box<Expr> without cloning. |
| 1417 |
let node = core::mem::replace(expr, Expr::Empty); |
| 1418 |
if let Expr::AstNode(AstNode::AstGroup { name, inner }, ix) = node { |
| 1419 |
let group_index = if let Some(name) = name { |
| 1420 |
self.named_groups |
| 1421 |
.insert(name.clone(), self.next_group_index); |
| 1422 |
self.named_group_positions.insert(name, ix); |
| 1423 |
Some(self.next_group_index) |
| 1424 |
} else if !self.ignore_numbered_groups { |
| 1425 |
Some(self.next_group_index) |
| 1426 |
} else { |
| 1427 |
None |
| 1428 |
}; |
| 1429 |
|
| 1430 |
if group_index.is_some() { |
| 1431 |
self.next_group_index += 1; |
| 1432 |
} |
| 1433 |
|
| 1434 |
let mut inner = inner; |
| 1435 |
self.resolve_groups(&mut inner); |
| 1436 |
|
| 1437 |
// If we have a group index, create a capturing group |
| 1438 |
// If not, just use the resolved inner expression directly |
| 1439 |
*expr = if group_index.is_some() { |
| 1440 |
Expr::Group(Arc::new(*inner)) |
| 1441 |
} else { |
| 1442 |
*inner // Use the inner expression directly |
| 1443 |
}; |
| 1444 |
} |
| 1445 |
} else if !expr.is_leaf_node() { |
| 1446 |
// recursively resolve in inner expressions |
| 1447 |
for child in expr.children_iter_mut() { |
| 1448 |
self.resolve_groups(child); |
| 1449 |
} |
| 1450 |
} |
| 1451 |
} |
| 1452 |
|
| 1453 |
/// Resolve a `CaptureGroupTarget` to a concrete group index using the groups seen so far. |
| 1454 |
/// |
| 1455 |
/// `backref_ix` should be `Some(ix)` for backreferences, which enforces that a by-name |
| 1456 |
/// target must have been defined *before* the backref's position in the pattern (forward |
| 1457 |
/// named backrefs are not permitted). Pass `None` for subroutine calls and backref-exists |
| 1458 |
/// conditions, which do support forward references by name. |
| 1459 |
/// |
| 1460 |
/// Returns `None` if the target cannot be resolved (unknown name, forward named backref, |
| 1461 |
/// or a relative offset that underflows before group 1). |
| 1462 |
fn resolve_target( |
| 1463 |
&self, |
| 1464 |
target: &CaptureGroupTarget, |
| 1465 |
backref_ix: Option<usize>, |
| 1466 |
) -> Option<usize> { |
| 1467 |
match target { |
| 1468 |
CaptureGroupTarget::ByNumber(group_index) => Some(*group_index), |
| 1469 |
CaptureGroupTarget::Relative(relative_group) => { |
| 1470 |
let relative_group = *relative_group; |
| 1471 |
self.curr_group.checked_add_signed(if relative_group < 0 { |
| 1472 |
relative_group + 1 |
| 1473 |
} else { |
| 1474 |
relative_group |
| 1475 |
}) |
| 1476 |
} |
| 1477 |
CaptureGroupTarget::ByName(name) => { |
| 1478 |
let group = self.named_groups.get(name.as_str()).copied(); |
| 1479 |
// For backrefs, reject forward references: the group's opening `(` must appear |
| 1480 |
// before the backref in the pattern. |
| 1481 |
if let (Some(backref_ix), Some(group_ix)) = ( |
| 1482 |
backref_ix, |
| 1483 |
self.named_group_positions.get(name.as_str()).copied(), |
| 1484 |
) { |
| 1485 |
if group_ix >= backref_ix { |
| 1486 |
return None; |
| 1487 |
} |
| 1488 |
} |
| 1489 |
group |
| 1490 |
} |
| 1491 |
} |
| 1492 |
} |
| 1493 |
|
| 1494 |
fn resolve_capture_group_targets(&mut self, expr: &mut Expr) -> Result<()> { |
| 1495 |
if let Expr::AstNode(astnode, ix) = expr { |
| 1496 |
match astnode { |
| 1497 |
AstNode::AstGroup { .. } => unreachable!(), |
| 1498 |
AstNode::Backref { |
| 1499 |
target, |
| 1500 |
casei, |
| 1501 |
relative_recursion_level, |
| 1502 |
} => { |
| 1503 |
// TODO: if multiple groups with the same name, ideally we would |
| 1504 |
// return an Expr::Alt with all the backrefs to be compatible with Oniguruma. |
| 1505 |
// but it is unclear how the priorities should work, it may need to be a separate VM instruction |
| 1506 |
// so for now, we could emit a FeatureNotSupported CompileError |
| 1507 |
// but as this is a parser, we could emit a new AstNode representing a multigroup backref. |
| 1508 |
// Then when the analyzer sees it, it could return the error |
| 1509 |
if let Some(resolved_group) = self.resolve_target(target, Some(*ix)) { |
| 1510 |
if resolved_group > self.total_groups { |
| 1511 |
// Don't insert into the BitSet: an out-of-range number could allocate |
| 1512 |
// memory proportional to its raw value. Record the first occurrence so |
| 1513 |
// the analyzer can report it. |
| 1514 |
self.out_of_range_backref.get_or_insert(resolved_group); |
| 1515 |
} else { |
| 1516 |
self.backrefs.insert(resolved_group); |
| 1517 |
} |
| 1518 |
*expr = if let Some(relative_recursion_level) = *relative_recursion_level { |
| 1519 |
Expr::BackrefWithRelativeRecursionLevel { |
| 1520 |
group: resolved_group, |
| 1521 |
casei: *casei, |
| 1522 |
relative_level: relative_recursion_level, |
| 1523 |
} |
| 1524 |
} else { |
| 1525 |
Expr::Backref { |
| 1526 |
group: resolved_group, |
| 1527 |
casei: *casei, |
| 1528 |
} |
| 1529 |
}; |
| 1530 |
} else { |
| 1531 |
// Distinguish: a name that exists but is forward → InvalidGroupNameBackref; |
| 1532 |
// anything else (unknown name, bad relative offset) → InvalidBackref. |
| 1533 |
let err = if let CaptureGroupTarget::ByName(name) = target { |
| 1534 |
if self.named_groups.contains_key(name.as_str()) { |
| 1535 |
ParseError::InvalidGroupNameBackref(name.clone()) |
| 1536 |
} else { |
| 1537 |
ParseError::InvalidBackref |
| 1538 |
} |
| 1539 |
} else { |
| 1540 |
ParseError::InvalidBackref |
| 1541 |
}; |
| 1542 |
return Err(Error::ParseError(*ix, err)); |
| 1543 |
} |
| 1544 |
} |
| 1545 |
AstNode::SubroutineCall(target) => { |
| 1546 |
// TODO: if multiple groups with this name, don't resolve |
| 1547 |
// and instead just leave it as an AstNode for the analyzer to complain about |
| 1548 |
if let Some(resolved_group) = self.resolve_target(target, None) { |
| 1549 |
*expr = Expr::SubroutineCall(resolved_group); |
| 1550 |
} |
| 1551 |
} |
| 1552 |
AstNode::BackrefExistsCondition { |
| 1553 |
target, |
| 1554 |
relative_recursion_level, |
| 1555 |
} => { |
| 1556 |
if let Some(resolved_group) = self.resolve_target(target, None) { |
| 1557 |
*expr = Expr::BackrefExistsCondition { |
| 1558 |
group: resolved_group, |
| 1559 |
relative_recursion_level: *relative_recursion_level, |
| 1560 |
}; |
| 1561 |
} else { |
| 1562 |
return Err(Error::ParseError(*ix, ParseError::InvalidBackref)); |
| 1563 |
} |
| 1564 |
} |
| 1565 |
} |
| 1566 |
} else { |
| 1567 |
match expr { |
| 1568 |
Expr::Group(_) => { |
| 1569 |
self.next_group_index += 1; |
| 1570 |
self.curr_group = self.next_group_index - 1; |
| 1571 |
} |
| 1572 |
Expr::Backref { group, .. } |
| 1573 |
| Expr::BackrefWithRelativeRecursionLevel { group, .. } => { |
| 1574 |
self.backrefs.insert(*group); |
| 1575 |
} |
| 1576 |
_ => {} |
| 1577 |
} |
| 1578 |
if !expr.is_leaf_node() { |
| 1579 |
// recursively resolve in inner expressions |
| 1580 |
for child in expr.children_iter_mut() { |
| 1581 |
self.resolve_capture_group_targets(child)?; |
| 1582 |
} |
| 1583 |
} |
| 1584 |
} |
| 1585 |
Ok(()) |
| 1586 |
} |
| 1587 |
} |
| 1588 |
|
| 1589 |
// return (ix, value) |
| 1590 |
pub(crate) fn parse_usize(s: &str, ix: usize) -> Option<(usize, usize)> { |
| 1591 |
let mut end = ix; |
| 1592 |
while end < s.len() && s.as_bytes()[end].is_ascii_digit() { |
| 1593 |
end += 1; |
| 1594 |
} |
| 1595 |
s[ix..end].parse::<usize>().ok().map(|val| (end, val)) |
| 1596 |
} |
| 1597 |
|
| 1598 |
#[derive(Debug, PartialEq)] |
| 1599 |
pub(crate) struct ParsedId<'a> { |
| 1600 |
pub id: &'a str, |
| 1601 |
pub relative: Option<isize>, |
| 1602 |
pub skip: usize, |
| 1603 |
} |
| 1604 |
|
| 1605 |
/// Attempts to parse an identifier, optionally followed by a relative number between the |
| 1606 |
/// specified opening and closing delimiters. On success, returns |
| 1607 |
/// `Some((id, relative, skip))`, where `skip` is how much of the string was used. |
| 1608 |
pub(crate) fn parse_id<'a>( |
| 1609 |
s: &'a str, |
| 1610 |
open: &'_ str, |
| 1611 |
close: &'_ str, |
| 1612 |
allow_relative: bool, |
| 1613 |
) -> Option<ParsedId<'a>> { |
| 1614 |
debug_assert!(!close.starts_with(is_id_char)); |
| 1615 |
|
| 1616 |
if !s.starts_with(open) || s.len() <= open.len() + close.len() { |
| 1617 |
return None; |
| 1618 |
} |
| 1619 |
|
| 1620 |
let id_start = open.len(); |
| 1621 |
let mut iter = s[id_start..].char_indices().peekable(); |
| 1622 |
let after_id = iter.find(|(_, ch)| !is_id_char(*ch)); |
| 1623 |
|
| 1624 |
let id_len = match after_id.map(|(i, _)| i) { |
| 1625 |
Some(id_len) => id_len, |
| 1626 |
None if close.is_empty() => s.len(), |
| 1627 |
_ => 0, |
| 1628 |
}; |
| 1629 |
|
| 1630 |
let id_end = id_start + id_len; |
| 1631 |
if id_len > 0 && s[id_end..].starts_with(close) { |
| 1632 |
return Some(ParsedId { |
| 1633 |
id: &s[id_start..id_end], |
| 1634 |
relative: None, |
| 1635 |
skip: id_end + close.len(), |
| 1636 |
}); |
| 1637 |
} else if !allow_relative { |
| 1638 |
return None; |
| 1639 |
} |
| 1640 |
let relative_sign = s.as_bytes()[id_end]; |
| 1641 |
if relative_sign == b'+' || relative_sign == b'-' { |
| 1642 |
if let Some((end, relative_amount)) = parse_usize(s, id_end + 1) { |
| 1643 |
if s[end..].starts_with(close) { |
| 1644 |
if relative_amount == 0 && id_len == 0 { |
| 1645 |
return None; |
| 1646 |
} |
| 1647 |
let relative_amount_signed = if relative_sign == b'-' { |
| 1648 |
-(relative_amount as isize) |
| 1649 |
} else { |
| 1650 |
relative_amount as isize |
| 1651 |
}; |
| 1652 |
return Some(ParsedId { |
| 1653 |
id: &s[id_start..id_end], |
| 1654 |
relative: Some(relative_amount_signed), |
| 1655 |
skip: end + close.len(), |
| 1656 |
}); |
| 1657 |
} |
| 1658 |
} |
| 1659 |
} |
| 1660 |
None |
| 1661 |
} |
| 1662 |
|
| 1663 |
/// Parse a group name that allows any characters except the closing delimiter. |
| 1664 |
/// The name must be non-empty. Returns `(name, total_bytes_consumed)` on success. |
| 1665 |
pub(crate) fn parse_unrestricted_name<'a>( |
| 1666 |
s: &'a str, |
| 1667 |
open: &str, |
| 1668 |
close: &str, |
| 1669 |
) -> Option<(&'a str, usize)> { |
| 1670 |
if !s.starts_with(open) || s.len() <= open.len() + close.len() { |
| 1671 |
return None; |
| 1672 |
} |
| 1673 |
let after_open = &s[open.len()..]; |
| 1674 |
// Find the close delimiter |
| 1675 |
let end = after_open.find(close)?; |
| 1676 |
if end == 0 { |
| 1677 |
return None; // empty name not allowed |
| 1678 |
} |
| 1679 |
let name = &after_open[..end]; |
| 1680 |
Some((name, open.len() + end + close.len())) |
| 1681 |
} |
| 1682 |
|
| 1683 |
fn is_id_char(c: char) -> bool { |
| 1684 |
c.is_alphanumeric() || c == '_' |
| 1685 |
} |
| 1686 |
|
| 1687 |
fn is_hex_digit(b: u8) -> bool { |
| 1688 |
b.is_ascii_digit() || (b'a' <= (b | 32) && (b | 32) <= b'f') |
| 1689 |
} |
| 1690 |
|
| 1691 |
pub(crate) fn make_literal(s: &str) -> Expr { |
| 1692 |
make_literal_case_insensitive(s, false) |
| 1693 |
} |
| 1694 |
|
| 1695 |
pub(crate) fn make_literal_case_insensitive(s: &str, case_insensitive: bool) -> Expr { |
| 1696 |
Expr::Literal { |
| 1697 |
val: String::from(s), |
| 1698 |
casei: case_insensitive, |
| 1699 |
} |
| 1700 |
} |
| 1701 |
|
| 1702 |
pub(crate) fn make_ast_group(inner: Expr, name: Option<String>, ix: usize) -> Expr { |
| 1703 |
Expr::AstNode( |
| 1704 |
AstNode::AstGroup { |
| 1705 |
name, |
| 1706 |
inner: Box::new(inner), |
| 1707 |
}, |
| 1708 |
ix, |
| 1709 |
) |
| 1710 |
} |
| 1711 |
|
| 1712 |
#[cfg(test)] |
| 1713 |
pub(crate) fn make_group(inner: Expr) -> Expr { |
| 1714 |
Expr::Group(Arc::new(inner)) |
| 1715 |
} |
| 1716 |
|
| 1717 |
fn remap_unicode_property_if_necessary( |
| 1718 |
property_name: &str, |
| 1719 |
unicode_flag: bool, |
| 1720 |
in_class: bool, |
| 1721 |
) -> String { |
| 1722 |
let (mut neg, prop) = if let Some(p) = property_name.strip_prefix(r"\p{") { |
| 1723 |
(false, p) |
| 1724 |
} else if let Some(p) = property_name.strip_prefix(r"\P{") { |
| 1725 |
(true, p) |
| 1726 |
} else { |
| 1727 |
return String::from(property_name); |
| 1728 |
}; |
| 1729 |
if let Some(mut p) = prop.strip_suffix('}') { |
| 1730 |
// Check if the property name starts with ^ for negation (Oniguruma syntax) |
| 1731 |
// e.g., \p{^Emoji} should become \P{emoji} |
| 1732 |
if let Some(stripped) = p.strip_prefix('^') { |
| 1733 |
neg = !neg; |
| 1734 |
p = stripped; |
| 1735 |
} |
| 1736 |
let apply_wrap = |inner: &str, in_c: bool, n: bool| { |
| 1737 |
if in_c { |
| 1738 |
if n { |
| 1739 |
format!("[^{}]", inner) |
| 1740 |
} else { |
| 1741 |
inner.to_string() |
| 1742 |
} |
| 1743 |
} else if n { |
| 1744 |
format!("[^{}]", inner) |
| 1745 |
} else { |
| 1746 |
format!("[{}]", inner) |
| 1747 |
} |
| 1748 |
}; |
| 1749 |
match (p.to_lowercase().as_ref(), unicode_flag, in_class, neg) { |
| 1750 |
("alnum", true, in_c, n) => apply_wrap(r"\p{alpha}\p{digit}", in_c, n), |
| 1751 |
("alnum", false, in_c, n) => apply_wrap(r"[:alnum:]", in_c, n), |
| 1752 |
("blank", true, in_c, n) => apply_wrap(r"\p{Zs}\x09", in_c, n), |
| 1753 |
("blank", false, in_c, n) => apply_wrap(r"\t ", in_c, n), |
| 1754 |
("cntrl", true, in_c, n) => apply_wrap(r"\x00-\x1F\x7F-\x9F", in_c, n), |
| 1755 |
("cntrl", false, in_c, n) => apply_wrap(r"[:cntrl:]", in_c, n), |
| 1756 |
(r"word", true, _, false) => r"\w".to_string(), |
| 1757 |
(r"word", true, _, true) => r"\W".to_string(), |
| 1758 |
(r"word", false, false, false) => r"[_[:alnum:]]".to_string(), |
| 1759 |
(r"word", false, false, true) => r"[^_[:alnum:]]".to_string(), |
| 1760 |
(r"word", false, true, false) => r"_[:alnum:]".to_string(), |
| 1761 |
(r"word", false, true, true) => r"[^_[:alnum:]]".to_string(), |
| 1762 |
// graph - graphical/visible characters (excludes whitespace, control chars, etc) |
| 1763 |
// For Unicode mode, we exclude White_Space and all Other category (\p{C}) |
| 1764 |
// Note: When used inside a character class, we return the full negated class |
| 1765 |
// because we can't easily represent a negation as positive content |
| 1766 |
(r"graph", true, _, false) => r"[^\p{White_Space}\p{C}]".to_string(), |
| 1767 |
(r"graph", true, _, true) => r"[\p{White_Space}\p{C}]".to_string(), |
| 1768 |
(r"graph", false, false, false) => r"[[:graph:]]".to_string(), |
| 1769 |
(r"graph", false, false, true) => r"[^[:graph:]]".to_string(), |
| 1770 |
(r"graph", false, true, false) => r"[:graph:]".to_string(), |
| 1771 |
(r"graph", false, true, true) => r"[^[:graph:]]".to_string(), |
| 1772 |
// print - printable characters (graph + space separator) |
| 1773 |
// For Unicode mode: exclude Other category and non-space whitespace |
| 1774 |
// Note: When used inside a character class, we return the full negated class |
| 1775 |
(r"print", true, _, false) => r"[^\p{C}\t\n\v\f\r]".to_string(), |
| 1776 |
(r"print", true, _, true) => r"[\p{C}\t\n\v\f\r]".to_string(), |
| 1777 |
(r"print", false, false, false) => r"[[:print:]]".to_string(), |
| 1778 |
(r"print", false, false, true) => r"[^[:print:]]".to_string(), |
| 1779 |
(r"print", false, true, false) => r"[:print:]".to_string(), |
| 1780 |
(r"print", false, true, true) => r"[^[:print:]]".to_string(), |
| 1781 |
// cs - surrogates (only applies to UTF-16, never matches in UTF-8) |
| 1782 |
("cs", _, _, false) => r"\P{any}".to_string(), |
| 1783 |
("cs", _, _, true) => r"\p{any}".to_string(), |
| 1784 |
// For other properties, convert to lowercase and reconstruct |
| 1785 |
_ => { |
| 1786 |
let lower = p.to_lowercase(); |
| 1787 |
if neg { |
| 1788 |
format!(r"\P{{{}}}", lower) |
| 1789 |
} else { |
| 1790 |
format!(r"\p{{{}}}", lower) |
| 1791 |
} |
| 1792 |
} |
| 1793 |
} |
| 1794 |
} else { |
| 1795 |
String::from(property_name) |
| 1796 |
} |
| 1797 |
} |
| 1798 |
|
| 1799 |
#[cfg(test)] |
| 1800 |
mod tests { |
| 1801 |
use alloc::boxed::Box; |
| 1802 |
use alloc::string::{String, ToString}; |
| 1803 |
use alloc::{format, vec}; |
| 1804 |
|
| 1805 |
use crate::parse::{ |
| 1806 |
make_group, make_literal, make_literal_case_insensitive, parse_id, parse_unrestricted_name, |
| 1807 |
remap_unicode_property_if_necessary, |
| 1808 |
}; |
| 1809 |
use crate::{Absent, Assertion, BacktrackingControlVerb, Expr}; |
| 1810 |
use crate::{LookAround::*, RegexOptions, SyntaxConfig}; |
| 1811 |
|
| 1812 |
fn p(s: &str) -> Expr { |
| 1813 |
Expr::parse_tree(s).unwrap().expr |
| 1814 |
} |
| 1815 |
|
| 1816 |
fn parse_oniguruma(s: &str) -> crate::Result<Expr> { |
| 1817 |
let mut options = RegexOptions::default(); |
| 1818 |
options.oniguruma_mode = true; |
| 1819 |
options.syntaxc = options.syntaxc.multi_line(true); |
| 1820 |
Expr::parse_tree_with_flags(s, options.compute_flags()).map(|tree| tree.expr) |
| 1821 |
} |
| 1822 |
|
| 1823 |
#[cfg_attr(feature = "track_caller", track_caller)] |
| 1824 |
fn fail(s: &str) { |
| 1825 |
assert!( |
| 1826 |
Expr::parse_tree(s).is_err(), |
| 1827 |
"Expected parse error, but was: {:?}", |
| 1828 |
Expr::parse_tree(s) |
| 1829 |
); |
| 1830 |
} |
| 1831 |
|
| 1832 |
#[cfg_attr(feature = "track_caller", track_caller)] |
| 1833 |
fn assert_error(re: &str, expected_error: &str) { |
| 1834 |
let result = Expr::parse_tree(re); |
| 1835 |
assert!( |
| 1836 |
result.is_err(), |
| 1837 |
"Expected parse error, but was: {:?}", |
| 1838 |
result |
| 1839 |
); |
| 1840 |
assert_eq!(&format!("{}", result.err().unwrap()), expected_error); |
| 1841 |
} |
| 1842 |
|
| 1843 |
#[cfg_attr(feature = "track_caller", track_caller)] |
| 1844 |
fn assert_error_oniguruma(re: &str, expected_error: &str) { |
| 1845 |
let result = parse_oniguruma(re); |
| 1846 |
assert!( |
| 1847 |
result.is_err(), |
| 1848 |
"Expected parse error in Oniguruma mode, but was: {:?}", |
| 1849 |
result |
| 1850 |
); |
| 1851 |
assert_eq!(&format!("{}", result.err().unwrap()), expected_error); |
| 1852 |
} |
| 1853 |
|
| 1854 |
#[test] |
| 1855 |
fn empty() { |
| 1856 |
assert_eq!(p(""), Expr::Empty); |
| 1857 |
} |
| 1858 |
|
| 1859 |
#[test] |
| 1860 |
fn any() { |
| 1861 |
assert_eq!( |
| 1862 |
p("."), |
| 1863 |
Expr::Any { |
| 1864 |
newline: false, |
| 1865 |
crlf: false |
| 1866 |
} |
| 1867 |
); |
| 1868 |
assert_eq!( |
| 1869 |
p("(?s:.)"), |
| 1870 |
Expr::Any { |
| 1871 |
newline: true, |
| 1872 |
crlf: false |
| 1873 |
} |
| 1874 |
); |
| 1875 |
} |
| 1876 |
|
| 1877 |
#[test] |
| 1878 |
fn start_text() { |
| 1879 |
assert_eq!(p("^"), Expr::Assertion(Assertion::StartText)); |
| 1880 |
} |
| 1881 |
|
| 1882 |
#[test] |
| 1883 |
fn end_text() { |
| 1884 |
assert_eq!(p("$"), Expr::Assertion(Assertion::EndText)); |
| 1885 |
} |
| 1886 |
|
| 1887 |
#[test] |
| 1888 |
fn end_text_before_empty_lines() { |
| 1889 |
assert_eq!( |
| 1890 |
p("\\Z"), |
| 1891 |
Expr::Assertion(Assertion::EndTextIgnoreTrailingNewlines { crlf: false }) |
| 1892 |
); |
| 1893 |
} |
| 1894 |
|
| 1895 |
#[test] |
| 1896 |
fn literal() { |
| 1897 |
assert_eq!(p("a"), make_literal("a")); |
| 1898 |
} |
| 1899 |
|
| 1900 |
#[test] |
| 1901 |
fn literal_special() { |
| 1902 |
assert_eq!(p("}"), make_literal("}")); |
| 1903 |
assert_eq!(p("]"), make_literal("]")); |
| 1904 |
} |
| 1905 |
|
| 1906 |
#[test] |
| 1907 |
fn parse_id_test() { |
| 1908 |
use crate::parse::ParsedId; |
| 1909 |
fn create_id(id: &str, relative: Option<isize>, skip: usize) -> Option<ParsedId<'_>> { |
| 1910 |
Some(ParsedId { id, relative, skip }) |
| 1911 |
} |
| 1912 |
assert_eq!(parse_id("foo.", "", "", true), create_id("foo", None, 3)); |
| 1913 |
assert_eq!(parse_id("1.", "", "", true), create_id("1", None, 1)); |
| 1914 |
assert_eq!(parse_id("{foo}", "{", "}", true), create_id("foo", None, 5)); |
| 1915 |
assert_eq!(parse_id("{foo.", "{", "}", true), None); |
| 1916 |
assert_eq!(parse_id("{foo", "{", "}", true), None); |
| 1917 |
assert_eq!(parse_id("{}", "{", "}", true), None); |
| 1918 |
assert_eq!(parse_id("", "", "", true), None); |
| 1919 |
assert_eq!(parse_id("{-1}", "{", "}", true), create_id("", Some(-1), 4)); |
| 1920 |
assert_eq!(parse_id("{-1}", "{", "}", false), None); |
| 1921 |
assert_eq!(parse_id("{-a}", "{", "}", true), None); |
| 1922 |
assert_eq!(parse_id("{-a}", "{", "}", false), None); |
| 1923 |
assert_eq!(parse_id("{+a}", "{", "}", false), None); |
| 1924 |
assert_eq!(parse_id("+a", "", "", false), None); |
| 1925 |
assert_eq!(parse_id("-a", "", "", false), None); |
| 1926 |
assert_eq!(parse_id("2+a", "", "", false), create_id("2", None, 1)); |
| 1927 |
assert_eq!(parse_id("2-a", "", "", false), create_id("2", None, 1)); |
| 1928 |
|
| 1929 |
assert_eq!(parse_id("<+1>", "<", ">", true), create_id("", Some(1), 4)); |
| 1930 |
assert_eq!(parse_id("<-3>", "<", ">", true), create_id("", Some(-3), 4)); |
| 1931 |
assert_eq!( |
| 1932 |
parse_id("<n+1>", "<", ">", true), |
| 1933 |
create_id("n", Some(1), 5) |
| 1934 |
); |
| 1935 |
assert_eq!( |
| 1936 |
parse_id("<n-1>", "<", ">", true), |
| 1937 |
create_id("n", Some(-1), 5) |
| 1938 |
); |
| 1939 |
assert_eq!(parse_id("<>", "<", ">", true), None); |
| 1940 |
assert_eq!(parse_id("<", "<", ">", true), None); |
| 1941 |
assert_eq!(parse_id("<+0>", "<", ">", true), None); |
| 1942 |
assert_eq!(parse_id("<-0>", "<", ">", true), None); |
| 1943 |
assert_eq!( |
| 1944 |
parse_id("<n+0>", "<", ">", true), |
| 1945 |
create_id("n", Some(0), 5) |
| 1946 |
); |
| 1947 |
assert_eq!( |
| 1948 |
parse_id("<n-0>", "<", ">", true), |
| 1949 |
create_id("n", Some(0), 5) |
| 1950 |
); |
| 1951 |
assert_eq!( |
| 1952 |
parse_id("<2-0>", "<", ">", true), |
| 1953 |
create_id("2", Some(0), 5) |
| 1954 |
); |
| 1955 |
assert_eq!( |
| 1956 |
parse_id("<2+0>", "<", ">", true), |
| 1957 |
create_id("2", Some(0), 5) |
| 1958 |
); |
| 1959 |
assert_eq!( |
| 1960 |
parse_id("<2+1>", "<", ">", true), |
| 1961 |
create_id("2", Some(1), 5) |
| 1962 |
); |
| 1963 |
assert_eq!( |
| 1964 |
parse_id("<2-1>", "<", ">", true), |
| 1965 |
create_id("2", Some(-1), 5) |
| 1966 |
); |
| 1967 |
} |
| 1968 |
|
| 1969 |
#[test] |
| 1970 |
fn parse_unrestricted_name_test() { |
| 1971 |
assert_eq!(parse_unrestricted_name("<foo>", "<", ">"), Some(("foo", 5))); |
| 1972 |
assert_eq!( |
| 1973 |
parse_unrestricted_name("<foo-bar>", "<", ">"), |
| 1974 |
Some(("foo-bar", 9)) |
| 1975 |
); |
| 1976 |
assert_eq!( |
| 1977 |
parse_unrestricted_name("<hello world>", "<", ">"), |
| 1978 |
Some(("hello world", 13)) |
| 1979 |
); |
| 1980 |
assert_eq!(parse_unrestricted_name("< >", "<", ">"), Some((" ", 3))); |
| 1981 |
assert_eq!(parse_unrestricted_name("<#!@>", "<", ">"), Some(("#!@", 5))); |
| 1982 |
assert_eq!( |
| 1983 |
parse_unrestricted_name("'foo-bar'", "'", "'"), |
| 1984 |
Some(("foo-bar", 9)) |
| 1985 |
); |
| 1986 |
// Empty name rejected |
| 1987 |
assert_eq!(parse_unrestricted_name("<>", "<", ">"), None); |
| 1988 |
assert_eq!(parse_unrestricted_name("''", "'", "'"), None); |
| 1989 |
// Missing close delimiter |
| 1990 |
assert_eq!(parse_unrestricted_name("<foo", "<", ">"), None); |
| 1991 |
// Too short |
| 1992 |
assert_eq!(parse_unrestricted_name("<", "<", ">"), None); |
| 1993 |
// Doesn't start with open |
| 1994 |
assert_eq!(parse_unrestricted_name("foo>", "<", ">"), None); |
| 1995 |
// No open/close delimiters (empty strings) |
| 1996 |
assert_eq!(parse_unrestricted_name("foo)", "", ")"), Some(("foo", 4))); |
| 1997 |
assert_eq!(parse_unrestricted_name(")", "", ")"), None); |
| 1998 |
} |
| 1999 |
|
| 2000 |
#[test] |
| 2001 |
fn literal_unescaped_opening_curly() { |
| 2002 |
// `{` in position where quantifier is not allowed results in literal `{` |
| 2003 |
assert_eq!(p("{"), make_literal("{")); |
| 2004 |
assert_eq!(p("({)"), make_group(make_literal("{"),)); |
| 2005 |
assert_eq!( |
| 2006 |
p("a|{"), |
| 2007 |
Expr::Alt(vec![make_literal("a"), make_literal("{"),]) |
| 2008 |
); |
| 2009 |
assert_eq!( |
| 2010 |
p("{{2}"), |
| 2011 |
Expr::Repeat { |
| 2012 |
child: Box::new(make_literal("{")), |
| 2013 |
lo: 2, |
| 2014 |
hi: 2, |
| 2015 |
greedy: true |
| 2016 |
} |
| 2017 |
); |
| 2018 |
} |
| 2019 |
|
| 2020 |
#[test] |
| 2021 |
fn literal_escape() { |
| 2022 |
assert_eq!(p("\\'"), make_literal("'")); |
| 2023 |
assert_eq!(p("\\\""), make_literal("\"")); |
| 2024 |
assert_eq!(p("\\ "), make_literal(" ")); |
| 2025 |
assert_eq!(p("\\xA0"), make_literal("\u{A0}")); |
| 2026 |
assert_eq!(p("\\x{1F4A9}"), make_literal("\u{1F4A9}")); |
| 2027 |
assert_eq!(p("\\x{000000B7}"), make_literal("\u{B7}")); |
| 2028 |
assert_eq!(p("\\u21D2"), make_literal("\u{21D2}")); |
| 2029 |
assert_eq!(p("\\u{21D2}"), make_literal("\u{21D2}")); |
| 2030 |
assert_eq!(p("\\u21D2x"), p("\u{21D2}x")); |
| 2031 |
assert_eq!(p("\\U0001F60A"), make_literal("\u{1F60A}")); |
| 2032 |
assert_eq!(p("\\U{0001F60A}"), make_literal("\u{1F60A}")); |
| 2033 |
} |
| 2034 |
|
| 2035 |
#[test] |
| 2036 |
fn hex_escape() { |
| 2037 |
assert_eq!( |
| 2038 |
p("\\h"), |
| 2039 |
Expr::Delegate { |
| 2040 |
inner: String::from("[0-9A-Fa-f]"), |
| 2041 |
casei: false, |
| 2042 |
} |
| 2043 |
); |
| 2044 |
assert_eq!( |
| 2045 |
p("\\H"), |
| 2046 |
Expr::Delegate { |
| 2047 |
inner: String::from("[^0-9A-Fa-f]"), |
| 2048 |
casei: false, |
| 2049 |
} |
| 2050 |
); |
| 2051 |
} |
| 2052 |
|
| 2053 |
#[test] |
| 2054 |
fn invalid_escape() { |
| 2055 |
assert_error( |
| 2056 |
"\\", |
| 2057 |
"Parsing error at position 0: Backslash without following character", |
| 2058 |
); |
| 2059 |
assert_error("\\q", "Parsing error at position 0: Invalid escape: \\q"); |
| 2060 |
assert_error("\\u", "Parsing error at position 2: Invalid hex escape"); |
| 2061 |
assert_error("\\U", "Parsing error at position 2: Invalid hex escape"); |
| 2062 |
assert_error("\\x", "Parsing error at position 2: Invalid hex escape"); |
| 2063 |
assert_error("\\xAG", "Parsing error at position 2: Invalid hex escape"); |
| 2064 |
assert_error("\\xA", "Parsing error at position 2: Invalid hex escape"); |
| 2065 |
assert_error("\\x{}", "Parsing error at position 2: Invalid hex escape"); |
| 2066 |
assert_error("\\x{AG}", "Parsing error at position 2: Invalid hex escape"); |
| 2067 |
assert_error("\\x{42", "Parsing error at position 2: Invalid hex escape"); |
| 2068 |
assert_error( |
| 2069 |
"\\x{D800}", |
| 2070 |
"Parsing error at position 2: Invalid codepoint for hex or unicode escape", |
| 2071 |
); |
| 2072 |
assert_error( |
| 2073 |
"\\x{110000}", |
| 2074 |
"Parsing error at position 2: Invalid codepoint for hex or unicode escape", |
| 2075 |
); |
| 2076 |
assert_error("\\u123", "Parsing error at position 2: Invalid hex escape"); |
| 2077 |
assert_error("\\u123x", "Parsing error at position 2: Invalid hex escape"); |
| 2078 |
assert_error("\\u{}", "Parsing error at position 2: Invalid hex escape"); |
| 2079 |
assert_error( |
| 2080 |
"\\U1234567", |
| 2081 |
"Parsing error at position 2: Invalid hex escape", |
| 2082 |
); |
| 2083 |
assert_error("\\U{}", "Parsing error at position 2: Invalid hex escape"); |
| 2084 |
} |
| 2085 |
|
| 2086 |
#[test] |
| 2087 |
fn concat() { |
| 2088 |
assert_eq!( |
| 2089 |
p("ab"), |
| 2090 |
Expr::Concat(vec![make_literal("a"), make_literal("b"),]) |
| 2091 |
); |
| 2092 |
} |
| 2093 |
|
| 2094 |
#[test] |
| 2095 |
fn alt() { |
| 2096 |
assert_eq!( |
| 2097 |
p("a|b"), |
| 2098 |
Expr::Alt(vec![make_literal("a"), make_literal("b"),]) |
| 2099 |
); |
| 2100 |
} |
| 2101 |
|
| 2102 |
#[test] |
| 2103 |
fn group() { |
| 2104 |
assert_eq!(p("(a)"), make_group(make_literal("a"),)); |
| 2105 |
} |
| 2106 |
|
| 2107 |
#[test] |
| 2108 |
fn named_group() { |
| 2109 |
assert_eq!(p("(?'name'a)"), make_group(make_literal("a"),)); |
| 2110 |
assert_eq!(p("(?<name>a)"), make_group(make_literal("a"),)); |
| 2111 |
} |
| 2112 |
|
| 2113 |
#[test] |
| 2114 |
fn unrestricted_named_group() { |
| 2115 |
// Hyphens in group names |
| 2116 |
assert_eq!(p("(?<foo-bar>a)"), make_group(make_literal("a"))); |
| 2117 |
assert_eq!(p("(?'foo-bar'a)"), make_group(make_literal("a"))); |
| 2118 |
assert_eq!(p("(?P<foo-bar>a)"), make_group(make_literal("a"))); |
| 2119 |
|
| 2120 |
// Multiple hyphens / CSS-like names |
| 2121 |
assert_eq!(p("(?<data-value-1>a)"), make_group(make_literal("a"))); |
| 2122 |
|
| 2123 |
// Leading/trailing hyphens |
| 2124 |
assert_eq!(p("(?<-foo>a)"), make_group(make_literal("a"))); |
| 2125 |
assert_eq!(p("(?<foo->a)"), make_group(make_literal("a"))); |
| 2126 |
|
| 2127 |
// Special characters in group names |
| 2128 |
assert_eq!(p("(?<#>a)"), make_group(make_literal("a"))); |
| 2129 |
assert_eq!(p("(?<hello, world!>a)"), make_group(make_literal("a"))); |
| 2130 |
assert_eq!(p("(?<a b c>a)"), make_group(make_literal("a"))); |
| 2131 |
|
| 2132 |
// Emoji in group names |
| 2133 |
assert_eq!(p("(?<\u{1F3AF}>a)"), make_group(make_literal("a"))); |
| 2134 |
|
| 2135 |
// Delimiter chars that don't conflict (single-quote inside angle brackets, etc.) |
| 2136 |
assert_eq!(p("(?<a'b>a)"), make_group(make_literal("a"))); |
| 2137 |
assert_eq!(p("(?'a>b'a)"), make_group(make_literal("a"))); |
| 2138 |
|
| 2139 |
// Name that looks numeric with hyphens (treated as named, not numeric) |
| 2140 |
let tree = Expr::parse_tree("(?<1-2>a)").unwrap(); |
| 2141 |
assert_eq!(tree.named_groups.get("1-2"), Some(&1)); |
| 2142 |
|
| 2143 |
// Verify named_groups map is populated correctly for hyphenated names |
| 2144 |
let tree = Expr::parse_tree("(?<foo-bar>a)").unwrap(); |
| 2145 |
assert_eq!(tree.named_groups.get("foo-bar"), Some(&1)); |
| 2146 |
|
| 2147 |
let tree = Expr::parse_tree("(?P<data-value>a)").unwrap(); |
| 2148 |
assert_eq!(tree.named_groups.get("data-value"), Some(&1)); |
| 2149 |
} |
| 2150 |
|
| 2151 |
#[test] |
| 2152 |
fn unrestricted_named_group_empty_still_rejected() { |
| 2153 |
// Empty names are still rejected |
| 2154 |
fail("(?<>a)"); |
| 2155 |
fail("(?P<>a)"); |
| 2156 |
fail("(?''a)"); |
| 2157 |
} |
| 2158 |
|
| 2159 |
#[test] |
| 2160 |
fn unrestricted_named_group_missing_close_still_rejected() { |
| 2161 |
// Missing close delimiter |
| 2162 |
fail("(?<foo-bar"); |
| 2163 |
fail("(?'foo-bar"); |
| 2164 |
fail("(?P<foo-bar"); |
| 2165 |
} |
| 2166 |
|
| 2167 |
#[test] |
| 2168 |
fn group_repeat() { |
| 2169 |
assert_eq!( |
| 2170 |
p("(a){2}"), |
| 2171 |
Expr::Repeat { |
| 2172 |
child: Box::new(make_group(make_literal("a"))), |
| 2173 |
lo: 2, |
| 2174 |
hi: 2, |
| 2175 |
greedy: true |
| 2176 |
} |
| 2177 |
); |
| 2178 |
} |
| 2179 |
|
| 2180 |
#[test] |
| 2181 |
fn repeat() { |
| 2182 |
assert_eq!( |
| 2183 |
p("a{2,42}"), |
| 2184 |
Expr::Repeat { |
| 2185 |
child: Box::new(make_literal("a")), |
| 2186 |
lo: 2, |
| 2187 |
hi: 42, |
| 2188 |
greedy: true |
| 2189 |
} |
| 2190 |
); |
| 2191 |
assert_eq!( |
| 2192 |
p("a{2,}"), |
| 2193 |
Expr::Repeat { |
| 2194 |
child: Box::new(make_literal("a")), |
| 2195 |
lo: 2, |
| 2196 |
hi: usize::MAX, |
| 2197 |
greedy: true |
| 2198 |
} |
| 2199 |
); |
| 2200 |
assert_eq!( |
| 2201 |
p("a{2}"), |
| 2202 |
Expr::Repeat { |
| 2203 |
child: Box::new(make_literal("a")), |
| 2204 |
lo: 2, |
| 2205 |
hi: 2, |
| 2206 |
greedy: true |
| 2207 |
} |
| 2208 |
); |
| 2209 |
assert_eq!( |
| 2210 |
p("a{,2}"), |
| 2211 |
Expr::Repeat { |
| 2212 |
child: Box::new(make_literal("a")), |
| 2213 |
lo: 0, |
| 2214 |
hi: 2, |
| 2215 |
greedy: true |
| 2216 |
} |
| 2217 |
); |
| 2218 |
|
| 2219 |
assert_eq!( |
| 2220 |
p("a{2,42}?"), |
| 2221 |
Expr::Repeat { |
| 2222 |
child: Box::new(make_literal("a")), |
| 2223 |
lo: 2, |
| 2224 |
hi: 42, |
| 2225 |
greedy: false |
| 2226 |
} |
| 2227 |
); |
| 2228 |
assert_eq!( |
| 2229 |
p("a{2,}?"), |
| 2230 |
Expr::Repeat { |
| 2231 |
child: Box::new(make_literal("a")), |
| 2232 |
lo: 2, |
| 2233 |
hi: usize::MAX, |
| 2234 |
greedy: false |
| 2235 |
} |
| 2236 |
); |
| 2237 |
assert_eq!( |
| 2238 |
p("a{2}?"), |
| 2239 |
Expr::Repeat { |
| 2240 |
child: Box::new(make_literal("a")), |
| 2241 |
lo: 2, |
| 2242 |
hi: 2, |
| 2243 |
greedy: false |
| 2244 |
} |
| 2245 |
); |
| 2246 |
assert_eq!( |
| 2247 |
p("a{,2}?"), |
| 2248 |
Expr::Repeat { |
| 2249 |
child: Box::new(make_literal("a")), |
| 2250 |
lo: 0, |
| 2251 |
hi: 2, |
| 2252 |
greedy: false |
| 2253 |
} |
| 2254 |
); |
| 2255 |
} |
| 2256 |
|
| 2257 |
#[test] |
| 2258 |
fn invalid_repeat() { |
| 2259 |
// Invalid repeat syntax results in literal |
| 2260 |
assert_eq!( |
| 2261 |
p("a{"), |
| 2262 |
Expr::Concat(vec![make_literal("a"), make_literal("{"),]) |
| 2263 |
); |
| 2264 |
assert_eq!( |
| 2265 |
p("a{6"), |
| 2266 |
Expr::Concat(vec![ |
| 2267 |
make_literal("a"), |
| 2268 |
make_literal("{"), |
| 2269 |
make_literal("6"), |
| 2270 |
]) |
| 2271 |
); |
| 2272 |
assert_eq!( |
| 2273 |
p("a{6,"), |
| 2274 |
Expr::Concat(vec![ |
| 2275 |
make_literal("a"), |
| 2276 |
make_literal("{"), |
| 2277 |
make_literal("6"), |
| 2278 |
make_literal(","), |
| 2279 |
]) |
| 2280 |
); |
| 2281 |
assert_eq!( |
| 2282 |
p("a{1,A}"), |
| 2283 |
Expr::Concat(vec![ |
| 2284 |
make_literal("a"), |
| 2285 |
make_literal("{"), |
| 2286 |
make_literal("1"), |
| 2287 |
make_literal(","), |
| 2288 |
make_literal("A"), |
| 2289 |
make_literal("}"), |
| 2290 |
]) |
| 2291 |
); |
| 2292 |
assert_eq!( |
| 2293 |
p("a{1,2A}"), |
| 2294 |
Expr::Concat(vec![ |
| 2295 |
make_literal("a"), |
| 2296 |
make_literal("{"), |
| 2297 |
make_literal("1"), |
| 2298 |
make_literal(","), |
| 2299 |
make_literal("2"), |
| 2300 |
make_literal("A"), |
| 2301 |
make_literal("}"), |
| 2302 |
]) |
| 2303 |
); |
| 2304 |
} |
| 2305 |
|
| 2306 |
#[test] |
| 2307 |
fn quantifiers_on_assertions_in_regex_mode() { |
| 2308 |
assert_eq!( |
| 2309 |
p(r"\b{1}"), |
| 2310 |
Expr::Repeat { |
| 2311 |
child: Box::new(Expr::Assertion(Assertion::WordBoundary)), |
| 2312 |
lo: 1, |
| 2313 |
hi: 1, |
| 2314 |
greedy: true |
| 2315 |
} |
| 2316 |
); |
| 2317 |
assert_eq!( |
| 2318 |
p(r"\B{2}"), |
| 2319 |
Expr::Repeat { |
| 2320 |
child: Box::new(Expr::Assertion(Assertion::NotWordBoundary)), |
| 2321 |
lo: 2, |
| 2322 |
hi: 2, |
| 2323 |
greedy: true |
| 2324 |
} |
| 2325 |
); |
| 2326 |
assert_eq!( |
| 2327 |
p(r"^{3}"), |
| 2328 |
Expr::Repeat { |
| 2329 |
child: Box::new(Expr::Assertion(Assertion::StartText)), |
| 2330 |
lo: 3, |
| 2331 |
hi: 3, |
| 2332 |
greedy: true |
| 2333 |
} |
| 2334 |
); |
| 2335 |
assert_eq!( |
| 2336 |
p(r"${1,5}"), |
| 2337 |
Expr::Repeat { |
| 2338 |
child: Box::new(Expr::Assertion(Assertion::EndText)), |
| 2339 |
lo: 1, |
| 2340 |
hi: 5, |
| 2341 |
greedy: true |
| 2342 |
} |
| 2343 |
); |
| 2344 |
assert_eq!( |
| 2345 |
p(r"\A*"), |
| 2346 |
Expr::Repeat { |
| 2347 |
child: Box::new(Expr::Assertion(Assertion::StartText)), |
| 2348 |
lo: 0, |
| 2349 |
hi: usize::MAX, |
| 2350 |
greedy: true |
| 2351 |
} |
| 2352 |
); |
| 2353 |
assert_eq!( |
| 2354 |
p(r"\z+"), |
| 2355 |
Expr::Repeat { |
| 2356 |
child: Box::new(Expr::Assertion(Assertion::EndText)), |
| 2357 |
lo: 1, |
| 2358 |
hi: usize::MAX, |
| 2359 |
greedy: true |
| 2360 |
} |
| 2361 |
); |
| 2362 |
assert_eq!( |
| 2363 |
p(r"^?"), |
| 2364 |
Expr::Repeat { |
| 2365 |
child: Box::new(Expr::Assertion(Assertion::StartText)), |
| 2366 |
lo: 0, |
| 2367 |
hi: 1, |
| 2368 |
greedy: true |
| 2369 |
} |
| 2370 |
); |
| 2371 |
assert_eq!( |
| 2372 |
p(r"${2}"), |
| 2373 |
Expr::Repeat { |
| 2374 |
child: Box::new(Expr::Assertion(Assertion::EndText)), |
| 2375 |
lo: 2, |
| 2376 |
hi: 2, |
| 2377 |
greedy: true |
| 2378 |
} |
| 2379 |
); |
| 2380 |
assert_eq!( |
| 2381 |
p(r"(?m)^?"), |
| 2382 |
Expr::Repeat { |
| 2383 |
child: Box::new(Expr::Assertion(Assertion::StartLine { crlf: false })), |
| 2384 |
lo: 0, |
| 2385 |
hi: 1, |
| 2386 |
greedy: true |
| 2387 |
} |
| 2388 |
); |
| 2389 |
assert_eq!( |
| 2390 |
p(r"(?m)${2}"), |
| 2391 |
Expr::Repeat { |
| 2392 |
child: Box::new(Expr::Assertion(Assertion::EndLine { crlf: false })), |
| 2393 |
lo: 2, |
| 2394 |
hi: 2, |
| 2395 |
greedy: true |
| 2396 |
} |
| 2397 |
); |
| 2398 |
assert_eq!( |
| 2399 |
p(r"\b+"), |
| 2400 |
Expr::Repeat { |
| 2401 |
child: Box::new(Expr::Assertion(Assertion::WordBoundary)), |
| 2402 |
lo: 1, |
| 2403 |
hi: usize::MAX, |
| 2404 |
greedy: true |
| 2405 |
} |
| 2406 |
); |
| 2407 |
} |
| 2408 |
|
| 2409 |
#[test] |
| 2410 |
fn delegate_zero() { |
| 2411 |
assert_eq!(p("\\b"), Expr::Assertion(Assertion::WordBoundary),); |
| 2412 |
assert_eq!(p("\\B"), Expr::Assertion(Assertion::NotWordBoundary),); |
| 2413 |
} |
| 2414 |
|
| 2415 |
#[test] |
| 2416 |
fn delegate_named_group() { |
| 2417 |
assert_eq!( |
| 2418 |
p("\\p{Greek}"), |
| 2419 |
Expr::Delegate { |
| 2420 |
inner: String::from("\\p{greek}"), |
| 2421 |
casei: false, |
| 2422 |
} |
| 2423 |
); |
| 2424 |
assert_eq!( |
| 2425 |
p("\\pL"), |
| 2426 |
Expr::Delegate { |
| 2427 |
inner: String::from("\\pL"), |
| 2428 |
casei: false, |
| 2429 |
} |
| 2430 |
); |
| 2431 |
assert_eq!( |
| 2432 |
p("\\P{Greek}"), |
| 2433 |
Expr::Delegate { |
| 2434 |
inner: String::from("\\P{greek}"), |
| 2435 |
casei: false, |
| 2436 |
} |
| 2437 |
); |
| 2438 |
assert_eq!( |
| 2439 |
p("\\PL"), |
| 2440 |
Expr::Delegate { |
| 2441 |
inner: String::from("\\PL"), |
| 2442 |
casei: false, |
| 2443 |
} |
| 2444 |
); |
| 2445 |
assert_eq!( |
| 2446 |
p("(?i)\\p{Ll}"), |
| 2447 |
Expr::Delegate { |
| 2448 |
inner: String::from("\\p{ll}"), |
| 2449 |
casei: true, |
| 2450 |
} |
| 2451 |
); |
| 2452 |
} |
| 2453 |
|
| 2454 |
#[test] |
| 2455 |
fn backref() { |
| 2456 |
let tree = Expr::parse_tree(r"(.)\1").unwrap(); |
| 2457 |
assert_eq!( |
| 2458 |
tree.expr, |
| 2459 |
Expr::Concat(vec![ |
| 2460 |
make_group(Expr::Any { |
| 2461 |
newline: false, |
| 2462 |
crlf: false |
| 2463 |
}), |
| 2464 |
Expr::Backref { |
| 2465 |
group: 1, |
| 2466 |
casei: false, |
| 2467 |
}, |
| 2468 |
]) |
| 2469 |
); |
| 2470 |
assert!(tree.numeric_capture_group_references); |
| 2471 |
} |
| 2472 |
|
| 2473 |
#[test] |
| 2474 |
fn named_backref() { |
| 2475 |
let tree = Expr::parse_tree(r"(?<i>.)\k<i>").unwrap(); |
| 2476 |
assert_eq!( |
| 2477 |
tree.expr, |
| 2478 |
Expr::Concat(vec![ |
| 2479 |
make_group(Expr::Any { |
| 2480 |
newline: false, |
| 2481 |
crlf: false |
| 2482 |
}), |
| 2483 |
Expr::Backref { |
| 2484 |
group: 1, |
| 2485 |
casei: false, |
| 2486 |
}, |
| 2487 |
]) |
| 2488 |
); |
| 2489 |
assert!(!tree.numeric_capture_group_references); |
| 2490 |
} |
| 2491 |
|
| 2492 |
#[test] |
| 2493 |
fn relative_backref() { |
| 2494 |
let tree = Expr::parse_tree(r"(a)(.)\k<-1>").unwrap(); |
| 2495 |
assert_eq!( |
| 2496 |
tree.expr, |
| 2497 |
Expr::Concat(vec![ |
| 2498 |
make_group(make_literal("a")), |
| 2499 |
make_group(Expr::Any { |
| 2500 |
newline: false, |
| 2501 |
crlf: false |
| 2502 |
}), |
| 2503 |
Expr::Backref { |
| 2504 |
group: 2, |
| 2505 |
casei: false, |
| 2506 |
}, |
| 2507 |
]) |
| 2508 |
); |
| 2509 |
// this doesn't count as a numeric reference |
| 2510 |
assert!(!tree.numeric_capture_group_references); |
| 2511 |
|
| 2512 |
let tree = Expr::parse_tree(r"(a)\k<+1>(.)").unwrap(); |
| 2513 |
assert_eq!( |
| 2514 |
tree.expr, |
| 2515 |
Expr::Concat(vec![ |
| 2516 |
make_group(make_literal("a")), |
| 2517 |
Expr::Backref { |
| 2518 |
group: 2, |
| 2519 |
casei: false, |
| 2520 |
}, |
| 2521 |
make_group(Expr::Any { |
| 2522 |
newline: false, |
| 2523 |
crlf: false |
| 2524 |
}), |
| 2525 |
]) |
| 2526 |
); |
| 2527 |
// this doesn't count as a numeric reference |
| 2528 |
assert!(!tree.numeric_capture_group_references); |
| 2529 |
|
| 2530 |
// "-" is now a valid unrestricted group name |
| 2531 |
p("(?P<->.)"); |
| 2532 |
fail("(.)(?P=-)"); |
| 2533 |
fail(r"(a)\k<-0>(.)"); |
| 2534 |
fail(r"(a)\k<+0>(.)"); |
| 2535 |
fail(r"(a)\k<+>(.)"); |
| 2536 |
fail(r"(a)\k<->(.)"); |
| 2537 |
fail(r"(a)\k<>(.)"); |
| 2538 |
} |
| 2539 |
|
| 2540 |
#[test] |
| 2541 |
fn relative_backref_with_recursion_level() { |
| 2542 |
assert_eq!( |
| 2543 |
p(r"()\k<1+3>"), |
| 2544 |
Expr::Concat(vec![ |
| 2545 |
make_group(Expr::Empty), |
| 2546 |
Expr::BackrefWithRelativeRecursionLevel { |
| 2547 |
group: 1, |
| 2548 |
relative_level: 3, |
| 2549 |
casei: false, |
| 2550 |
}, |
| 2551 |
]), |
| 2552 |
); |
| 2553 |
|
| 2554 |
assert_eq!( |
| 2555 |
p(r"()\k<1-0>"), |
| 2556 |
Expr::Concat(vec![ |
| 2557 |
make_group(Expr::Empty), |
| 2558 |
Expr::BackrefWithRelativeRecursionLevel { |
| 2559 |
group: 1, |
| 2560 |
relative_level: 0, |
| 2561 |
casei: false, |
| 2562 |
}, |
| 2563 |
]), |
| 2564 |
); |
| 2565 |
|
| 2566 |
assert_eq!( |
| 2567 |
p(r"(?<n>)\k<n+3>"), |
| 2568 |
Expr::Concat(vec![ |
| 2569 |
make_group(Expr::Empty), |
| 2570 |
Expr::BackrefWithRelativeRecursionLevel { |
| 2571 |
group: 1, |
| 2572 |
relative_level: 3, |
| 2573 |
casei: false, |
| 2574 |
}, |
| 2575 |
]), |
| 2576 |
); |
| 2577 |
|
| 2578 |
assert_eq!( |
| 2579 |
p(r"(?<n>)\k<n-3>"), |
| 2580 |
Expr::Concat(vec![ |
| 2581 |
make_group(Expr::Empty), |
| 2582 |
Expr::BackrefWithRelativeRecursionLevel { |
| 2583 |
group: 1, |
| 2584 |
relative_level: -3, |
| 2585 |
casei: false, |
| 2586 |
} |
| 2587 |
]), |
| 2588 |
); |
| 2589 |
|
| 2590 |
assert_eq!( |
| 2591 |
p(r"\A(?<a>|.|(?:(?<b>.)\g<a>\k<b+0>))\z"), |
| 2592 |
Expr::Concat(vec![ |
| 2593 |
Expr::Assertion(Assertion::StartText), |
| 2594 |
make_group(Expr::Alt(vec![ |
| 2595 |
Expr::Empty, |
| 2596 |
Expr::Any { |
| 2597 |
newline: false, |
| 2598 |
crlf: false |
| 2599 |
}, |
| 2600 |
Expr::Concat(vec![ |
| 2601 |
make_group(Expr::Any { |
| 2602 |
newline: false, |
| 2603 |
crlf: false |
| 2604 |
}), |
| 2605 |
Expr::SubroutineCall(1), |
| 2606 |
Expr::BackrefWithRelativeRecursionLevel { |
| 2607 |
group: 2, |
| 2608 |
relative_level: 0, |
| 2609 |
casei: false, |
| 2610 |
}, |
| 2611 |
]) |
| 2612 |
])), |
| 2613 |
Expr::Assertion(Assertion::EndText) |
| 2614 |
]), |
| 2615 |
); |
| 2616 |
} |
| 2617 |
|
| 2618 |
#[test] |
| 2619 |
fn relative_subroutine_call() { |
| 2620 |
assert_eq!( |
| 2621 |
p(r"(a)(.)\g<-1>"), |
| 2622 |
Expr::Concat(vec![ |
| 2623 |
make_group(make_literal("a")), |
| 2624 |
make_group(Expr::Any { |
| 2625 |
newline: false, |
| 2626 |
crlf: false |
| 2627 |
}), |
| 2628 |
Expr::SubroutineCall(2), |
| 2629 |
]) |
| 2630 |
); |
| 2631 |
|
| 2632 |
assert_eq!( |
| 2633 |
p(r"(a)\g<+1>(.)"), |
| 2634 |
Expr::Concat(vec![ |
| 2635 |
make_group(make_literal("a")), |
| 2636 |
Expr::SubroutineCall(2), |
| 2637 |
make_group(Expr::Any { |
| 2638 |
newline: false, |
| 2639 |
crlf: false |
| 2640 |
}), |
| 2641 |
]) |
| 2642 |
); |
| 2643 |
|
| 2644 |
fail(r"(a)\g<-0>(.)"); |
| 2645 |
fail(r"(a)\g<+0>(.)"); |
| 2646 |
fail(r"(a)\g<+>(.)"); |
| 2647 |
fail(r"(a)\g<->(.)"); |
| 2648 |
fail(r"(a)\g<>(.)"); |
| 2649 |
} |
| 2650 |
|
| 2651 |
#[test] |
| 2652 |
fn lookaround() { |
| 2653 |
assert_eq!( |
| 2654 |
p("(?=a)"), |
| 2655 |
Expr::LookAround(Box::new(make_literal("a")), LookAhead) |
| 2656 |
); |
| 2657 |
assert_eq!( |
| 2658 |
p("(?!a)"), |
| 2659 |
Expr::LookAround(Box::new(make_literal("a")), LookAheadNeg) |
| 2660 |
); |
| 2661 |
assert_eq!( |
| 2662 |
p("(?<=a)"), |
| 2663 |
Expr::LookAround(Box::new(make_literal("a")), LookBehind) |
| 2664 |
); |
| 2665 |
assert_eq!( |
| 2666 |
p("(?<!a)"), |
| 2667 |
Expr::LookAround(Box::new(make_literal("a")), LookBehindNeg) |
| 2668 |
); |
| 2669 |
} |
| 2670 |
|
| 2671 |
#[test] |
| 2672 |
fn shy_group() { |
| 2673 |
assert_eq!( |
| 2674 |
p("(?:ab)c"), |
| 2675 |
Expr::Concat(vec![ |
| 2676 |
Expr::Concat(vec![make_literal("a"), make_literal("b"),]), |
| 2677 |
make_literal("c"), |
| 2678 |
]) |
| 2679 |
); |
| 2680 |
} |
| 2681 |
|
| 2682 |
#[test] |
| 2683 |
fn flag_state() { |
| 2684 |
assert_eq!( |
| 2685 |
p("(?s)."), |
| 2686 |
Expr::Any { |
| 2687 |
newline: true, |
| 2688 |
crlf: false |
| 2689 |
} |
| 2690 |
); |
| 2691 |
assert_eq!( |
| 2692 |
p("(?s:(?-s:.))"), |
| 2693 |
Expr::Any { |
| 2694 |
newline: false, |
| 2695 |
crlf: false |
| 2696 |
} |
| 2697 |
); |
| 2698 |
assert_eq!( |
| 2699 |
p("(?s:.)."), |
| 2700 |
Expr::Concat(vec![ |
| 2701 |
Expr::Any { |
| 2702 |
newline: true, |
| 2703 |
crlf: false |
| 2704 |
}, |
| 2705 |
Expr::Any { |
| 2706 |
newline: false, |
| 2707 |
crlf: false |
| 2708 |
}, |
| 2709 |
]) |
| 2710 |
); |
| 2711 |
assert_eq!( |
| 2712 |
p("(?:(?s).)."), |
| 2713 |
Expr::Concat(vec![ |
| 2714 |
Expr::Any { |
| 2715 |
newline: true, |
| 2716 |
crlf: false |
| 2717 |
}, |
| 2718 |
Expr::Any { |
| 2719 |
newline: false, |
| 2720 |
crlf: false |
| 2721 |
}, |
| 2722 |
]) |
| 2723 |
); |
| 2724 |
} |
| 2725 |
|
| 2726 |
#[test] |
| 2727 |
fn flag_multiline() { |
| 2728 |
assert_eq!(p("^"), Expr::Assertion(Assertion::StartText)); |
| 2729 |
assert_eq!( |
| 2730 |
p("(?m:^)"), |
| 2731 |
Expr::Assertion(Assertion::StartLine { crlf: false }) |
| 2732 |
); |
| 2733 |
assert_eq!(p("$"), Expr::Assertion(Assertion::EndText)); |
| 2734 |
assert_eq!( |
| 2735 |
p("(?m:$)"), |
| 2736 |
Expr::Assertion(Assertion::EndLine { crlf: false }) |
| 2737 |
); |
| 2738 |
} |
| 2739 |
|
| 2740 |
#[test] |
| 2741 |
fn flag_crlf() { |
| 2742 |
assert_eq!( |
| 2743 |
p("(?mR:^)"), |
| 2744 |
Expr::Assertion(Assertion::StartLine { crlf: true }) |
| 2745 |
); |
| 2746 |
assert_eq!( |
| 2747 |
p("(?Rm:^)"), |
| 2748 |
Expr::Assertion(Assertion::StartLine { crlf: true }) |
| 2749 |
); |
| 2750 |
assert_eq!( |
| 2751 |
p("(?mR:$)"), |
| 2752 |
Expr::Assertion(Assertion::EndLine { crlf: true }) |
| 2753 |
); |
| 2754 |
// Negating R reverts to LF-only |
| 2755 |
assert_eq!( |
| 2756 |
p("(?mR)(?-R:^)"), |
| 2757 |
Expr::Assertion(Assertion::StartLine { crlf: false }) |
| 2758 |
); |
| 2759 |
} |
| 2760 |
|
| 2761 |
#[test] |
| 2762 |
fn flag_swap_greed() { |
| 2763 |
assert_eq!(p("a*"), p("(?U:a*?)")); |
| 2764 |
assert_eq!(p("a*?"), p("(?U:a*)")); |
| 2765 |
} |
| 2766 |
|
| 2767 |
#[test] |
| 2768 |
fn invalid_flags() { |
| 2769 |
assert!(Expr::parse_tree("(?").is_err()); |
| 2770 |
assert!(Expr::parse_tree("(?)").is_err()); |
| 2771 |
assert!(Expr::parse_tree("(?-)").is_err()); |
| 2772 |
assert!(Expr::parse_tree("(?-:a)").is_err()); |
| 2773 |
assert!(Expr::parse_tree("(?q:a)").is_err()); |
| 2774 |
} |
| 2775 |
|
| 2776 |
#[test] |
| 2777 |
fn lifetime() { |
| 2778 |
assert_eq!( |
| 2779 |
p("\\'[a-zA-Z_][a-zA-Z0-9_]*(?!\\')\\b"), |
| 2780 |
Expr::Concat(vec![ |
| 2781 |
make_literal("'"), |
| 2782 |
Expr::Delegate { |
| 2783 |
inner: String::from("[a-zA-Z_]"), |
| 2784 |
casei: false, |
| 2785 |
}, |
| 2786 |
Expr::Repeat { |
| 2787 |
child: Box::new(Expr::Delegate { |
| 2788 |
inner: String::from("[a-zA-Z0-9_]"), |
| 2789 |
casei: false, |
| 2790 |
}), |
| 2791 |
lo: 0, |
| 2792 |
hi: usize::MAX, |
| 2793 |
greedy: true |
| 2794 |
}, |
| 2795 |
Expr::LookAround(Box::new(make_literal("'")), LookAheadNeg), |
| 2796 |
Expr::Assertion(Assertion::WordBoundary), |
| 2797 |
]) |
| 2798 |
); |
| 2799 |
} |
| 2800 |
|
| 2801 |
#[test] |
| 2802 |
fn ignore_whitespace() { |
| 2803 |
assert_eq!(p("(?x: )"), p("")); |
| 2804 |
assert_eq!(p("(?x) | "), p("|")); |
| 2805 |
assert_eq!(p("(?x: a )"), p("a")); |
| 2806 |
assert_eq!(p("(?x: a # ) bobby tables\n b )"), p("ab")); |
| 2807 |
assert_eq!(p("(?x: a | b )"), p("a|b")); |
| 2808 |
assert_eq!(p("(?x: ( a b ) )"), p("(ab)")); |
| 2809 |
assert_eq!(p("(?x: a + )"), p("a+")); |
| 2810 |
assert_eq!(p("(?x: a {2} )"), p("a{2}")); |
| 2811 |
assert_eq!(p("(?x: a { 2 } )"), p("a{2}")); |
| 2812 |
assert_eq!(p("(?x: a { 2 , } )"), p("a{2,}")); |
| 2813 |
assert_eq!(p("(?x: a { , 2 } )"), p("a{,2}")); |
| 2814 |
assert_eq!(p("(?x: a { 2 , 3 } )"), p("a{2,3}")); |
| 2815 |
assert_eq!(p("(?x: a { 2 , 3 } ? )"), p("a{2,3}?")); |
| 2816 |
assert_eq!(p("(?x: ( ? i : . ) )"), p("(?i:.)")); |
| 2817 |
assert_eq!(p("(?x: ( ?= a ) )"), p("(?=a)")); |
| 2818 |
assert_eq!(p("(?x: [ ] )"), p("[ ]")); |
| 2819 |
assert_eq!(p("(?x: [ ^] )"), p("[ ^]")); |
| 2820 |
assert_eq!(p("(?x: [a - z] )"), p("[a - z]")); |
| 2821 |
assert_eq!(p("(?x: [ \\] \\\\] )"), p("[ \\] \\\\]")); |
| 2822 |
assert_eq!(p("(?x: a\\ b )"), p("a b")); |
| 2823 |
assert_eq!(p("(?x: a (?-x:#) b )"), p("a#b")); |
| 2824 |
assert_eq!(p("(?x: a (?# b))c"), p("ac")); |
| 2825 |
assert_eq!(p("(?x: \\b { s t a r t} a )"), p("\\b{start}a")); |
| 2826 |
assert_eq!(p("(?x: \\b {end} )"), p("\\b{end}")); |
| 2827 |
assert_eq!(p("(?x: \\b { start-half } )"), p("\\b{start-half}")); |
| 2828 |
assert_eq!(p("(?x: \\b { e n d - h a l f } )"), p("\\b{end-half}")); |
| 2829 |
assert_eq!(p("(?x: \\b{s\nt\ra\trt} a)"), p("\\b{start}a")); |
| 2830 |
assert_eq!(p("(?x: \\u { 0 0 3 2} a)"), p("\\u{0032}a")); |
| 2831 |
assert_eq!(p("(?x: \\U { 0001 F600 } a)"), p("\\U{0001F600}a")); |
| 2832 |
assert_eq!(p("(?x: \\x { 3 2} a)"), p("\\x{32}a")); |
| 2833 |
assert_eq!(p("(?x: \\b { s t a # x\nr t} a )"), p("\\b{start}a")); |
| 2834 |
assert_eq!(p("(?x: \\b { s t a (?# x)r t} a )"), p("\\b{start}a")); |
| 2835 |
assert_eq!(p("(?x: \\u { 0 0 # x\n3 2} a)"), p("\\u{0032}a")); |
| 2836 |
assert_eq!(p("(?x: \\u { 0 0 (?# x)3 2} a)"), p("\\u{0032}a")); |
| 2837 |
} |
| 2838 |
|
| 2839 |
#[test] |
| 2840 |
fn comments() { |
| 2841 |
assert_eq!(p(r"ab(?# comment)"), p("ab")); |
| 2842 |
assert_eq!(p(r"ab(?#)"), p("ab")); |
| 2843 |
assert_eq!(p(r"(?# comment 1)(?# comment 2)ab"), p("ab")); |
| 2844 |
assert_eq!(p(r"ab(?# comment \))c"), p("abc")); |
| 2845 |
assert_eq!(p(r"ab(?# comment \\)c"), p("abc")); |
| 2846 |
assert_eq!(p(r"ab(?# comment ()c"), p("abc")); |
| 2847 |
assert_eq!(p(r"ab(?# comment)*"), p("ab*")); |
| 2848 |
fail(r"ab(?# comment"); |
| 2849 |
fail(r"ab(?# comment\"); |
| 2850 |
} |
| 2851 |
|
| 2852 |
#[test] |
| 2853 |
fn atomic_group() { |
| 2854 |
assert_eq!(p("(?>a)"), Expr::AtomicGroup(Box::new(make_literal("a")))); |
| 2855 |
} |
| 2856 |
|
| 2857 |
#[test] |
| 2858 |
fn possessive() { |
| 2859 |
assert_eq!( |
| 2860 |
p("a++"), |
| 2861 |
Expr::AtomicGroup(Box::new(Expr::Repeat { |
| 2862 |
child: Box::new(make_literal("a")), |
| 2863 |
lo: 1, |
| 2864 |
hi: usize::MAX, |
| 2865 |
greedy: true |
| 2866 |
})) |
| 2867 |
); |
| 2868 |
assert_eq!( |
| 2869 |
p("a*+"), |
| 2870 |
Expr::AtomicGroup(Box::new(Expr::Repeat { |
| 2871 |
child: Box::new(make_literal("a")), |
| 2872 |
lo: 0, |
| 2873 |
hi: usize::MAX, |
| 2874 |
greedy: true |
| 2875 |
})) |
| 2876 |
); |
| 2877 |
assert_eq!( |
| 2878 |
p("a?+"), |
| 2879 |
Expr::AtomicGroup(Box::new(Expr::Repeat { |
| 2880 |
child: Box::new(make_literal("a")), |
| 2881 |
lo: 0, |
| 2882 |
hi: 1, |
| 2883 |
greedy: true |
| 2884 |
})) |
| 2885 |
); |
| 2886 |
} |
| 2887 |
|
| 2888 |
#[test] |
| 2889 |
fn invalid_backref() { |
| 2890 |
// Only syntactic tests (non-decimal or number overflow); see tests in the analyze module |
| 2891 |
// for out-of-range group number validation. |
| 2892 |
assert_error( |
| 2893 |
r".\18446744073709551616", |
| 2894 |
"Parsing error at position 2: Invalid back reference", |
| 2895 |
); // overflows usize - not a valid integer |
| 2896 |
assert_error(r".\c", "Parsing error at position 1: Invalid escape: \\c"); |
| 2897 |
// not decimal |
| 2898 |
} |
| 2899 |
|
| 2900 |
#[test] |
| 2901 |
fn invalid_group_name_backref() { |
| 2902 |
assert_error( |
| 2903 |
"\\k<id>(?<id>.)", |
| 2904 |
"Parsing error at position 2: Invalid group name in back reference: id", |
| 2905 |
); |
| 2906 |
} |
| 2907 |
|
| 2908 |
#[test] |
| 2909 |
fn invalid_group_name() { |
| 2910 |
assert_error( |
| 2911 |
"(?<id)", |
| 2912 |
"Parsing error at position 1: Could not parse group name", |
| 2913 |
); |
| 2914 |
assert_error( |
| 2915 |
"(?<>)", |
| 2916 |
"Parsing error at position 1: Could not parse group name", |
| 2917 |
); |
| 2918 |
assert_error( |
| 2919 |
"\\kxxx<id>", |
| 2920 |
"Parsing error at position 2: Could not parse group name", |
| 2921 |
); |
| 2922 |
// "-" can only be used after a name for relative recursion level, so must be followed by a number |
| 2923 |
assert_error( |
| 2924 |
"\\k<id-withdash>", |
| 2925 |
"Parsing error at position 2: Could not parse group name", |
| 2926 |
); |
| 2927 |
assert_error( |
| 2928 |
"\\k<-id>", |
| 2929 |
"Parsing error at position 2: Could not parse group name", |
| 2930 |
); |
| 2931 |
} |
| 2932 |
|
| 2933 |
#[test] |
| 2934 |
fn unknown_flag() { |
| 2935 |
assert_error( |
| 2936 |
"(?-:a)", |
| 2937 |
"Parsing error at position 2: Unknown group flag: (?-:", |
| 2938 |
); |
| 2939 |
assert_error( |
| 2940 |
"(?)", |
| 2941 |
"Parsing error at position 2: Unknown group flag: (?)", |
| 2942 |
); |
| 2943 |
assert_error( |
| 2944 |
"(?--)", |
| 2945 |
"Parsing error at position 2: Unknown group flag: (?--", |
| 2946 |
); |
| 2947 |
// Check that we don't split on char boundary |
| 2948 |
assert_error( |
| 2949 |
"(?\u{1F60A})", |
| 2950 |
"Parsing error at position 2: Unknown group flag: (?\u{1F60A}", |
| 2951 |
); |
| 2952 |
} |
| 2953 |
|
| 2954 |
#[test] |
| 2955 |
fn no_quantifiers_on_lookarounds() { |
| 2956 |
assert_error( |
| 2957 |
"(?=hello)+", |
| 2958 |
"Parsing error at position 9: Target of repeat operator is invalid", |
| 2959 |
); |
| 2960 |
assert_error( |
| 2961 |
"(?<!hello)*", |
| 2962 |
"Parsing error at position 10: Target of repeat operator is invalid", |
| 2963 |
); |
| 2964 |
assert_error( |
| 2965 |
"(?<=hello){2,3}", |
| 2966 |
"Parsing error at position 14: Target of repeat operator is invalid", |
| 2967 |
); |
| 2968 |
assert_error( |
| 2969 |
"(?!hello)?", |
| 2970 |
"Parsing error at position 9: Target of repeat operator is invalid", |
| 2971 |
); |
| 2972 |
assert_error( |
| 2973 |
"(a|b|?)", |
| 2974 |
"Parsing error at position 5: Target of repeat operator is invalid", |
| 2975 |
); |
| 2976 |
} |
| 2977 |
|
| 2978 |
#[test] |
| 2979 |
fn no_quantifiers_on_assertions_in_oniguruma_mode() { |
| 2980 |
assert_error_oniguruma( |
| 2981 |
r"\b{1}", |
| 2982 |
"Parsing error at position 4: Target of repeat operator is invalid", |
| 2983 |
); |
| 2984 |
assert_error_oniguruma( |
| 2985 |
r"\B{2}", |
| 2986 |
"Parsing error at position 4: Target of repeat operator is invalid", |
| 2987 |
); |
| 2988 |
assert_error_oniguruma( |
| 2989 |
r"^{3}", |
| 2990 |
"Parsing error at position 3: Target of repeat operator is invalid", |
| 2991 |
); |
| 2992 |
assert_error_oniguruma( |
| 2993 |
r"${1,5}", |
| 2994 |
"Parsing error at position 5: Target of repeat operator is invalid", |
| 2995 |
); |
| 2996 |
assert_error_oniguruma( |
| 2997 |
r"\A*", |
| 2998 |
"Parsing error at position 2: Target of repeat operator is invalid", |
| 2999 |
); |
| 3000 |
assert_error_oniguruma( |
| 3001 |
r"\z+", |
| 3002 |
"Parsing error at position 2: Target of repeat operator is invalid", |
| 3003 |
); |
| 3004 |
assert_error_oniguruma( |
| 3005 |
r"^?", |
| 3006 |
"Parsing error at position 1: Target of repeat operator is invalid", |
| 3007 |
); |
| 3008 |
assert_error_oniguruma( |
| 3009 |
r"${2}", |
| 3010 |
"Parsing error at position 3: Target of repeat operator is invalid", |
| 3011 |
); |
| 3012 |
assert_error_oniguruma( |
| 3013 |
r"(?m)^?", |
| 3014 |
"Parsing error at position 5: Target of repeat operator is invalid", |
| 3015 |
); |
| 3016 |
assert_error_oniguruma( |
| 3017 |
r"(?m)${2}", |
| 3018 |
"Parsing error at position 7: Target of repeat operator is invalid", |
| 3019 |
); |
| 3020 |
assert_error_oniguruma( |
| 3021 |
r"\b+", |
| 3022 |
"Parsing error at position 2: Target of repeat operator is invalid", |
| 3023 |
); |
| 3024 |
} |
| 3025 |
|
| 3026 |
#[test] |
| 3027 |
fn keepout() { |
| 3028 |
assert_eq!( |
| 3029 |
p("a\\Kb"), |
| 3030 |
Expr::Concat(vec![make_literal("a"), Expr::KeepOut, make_literal("b"),]) |
| 3031 |
); |
| 3032 |
} |
| 3033 |
|
| 3034 |
#[test] |
| 3035 |
fn no_quantifiers_on_other_non_repeatable_expressions() { |
| 3036 |
assert_error( |
| 3037 |
r"\K?", |
| 3038 |
"Parsing error at position 2: Target of repeat operator is invalid", |
| 3039 |
); |
| 3040 |
assert_error( |
| 3041 |
r"\G*", |
| 3042 |
"Parsing error at position 2: Target of repeat operator is invalid", |
| 3043 |
); |
| 3044 |
} |
| 3045 |
|
| 3046 |
#[test] |
| 3047 |
fn empty_noncapturing_group_with_quantifier_default_mode() { |
| 3048 |
// In default mode, quantifiers on empty non-capturing groups are errors. |
| 3049 |
assert_error( |
| 3050 |
"(?:)*", |
| 3051 |
"Parsing error at position 4: Target of repeat operator is invalid", |
| 3052 |
); |
| 3053 |
assert_error( |
| 3054 |
"(?:)+", |
| 3055 |
"Parsing error at position 4: Target of repeat operator is invalid", |
| 3056 |
); |
| 3057 |
assert_error( |
| 3058 |
"(?:)?", |
| 3059 |
"Parsing error at position 4: Target of repeat operator is invalid", |
| 3060 |
); |
| 3061 |
assert_error( |
| 3062 |
"(?:){3}", |
| 3063 |
"Parsing error at position 6: Target of repeat operator is invalid", |
| 3064 |
); |
| 3065 |
} |
| 3066 |
|
| 3067 |
#[test] |
| 3068 |
fn empty_noncapturing_group_with_quantifier_oniguruma_mode() { |
| 3069 |
// Oniguruma silently accepts quantifiers on empty non-capturing groups |
| 3070 |
// as zero-width no-ops, collapsing them to Expr::Empty. |
| 3071 |
assert_eq!(parse_oniguruma("(?:)*").unwrap(), Expr::Empty); |
| 3072 |
assert_eq!(parse_oniguruma("(?:)+").unwrap(), Expr::Empty); |
| 3073 |
assert_eq!(parse_oniguruma("(?:)?").unwrap(), Expr::Empty); |
| 3074 |
assert_eq!(parse_oniguruma("(?:){3}").unwrap(), Expr::Empty); |
| 3075 |
assert_eq!(parse_oniguruma("(?:){2,5}").unwrap(), Expr::Empty); |
| 3076 |
// Non-greedy modifier |
| 3077 |
assert_eq!(parse_oniguruma("(?:)*?").unwrap(), Expr::Empty); |
| 3078 |
assert_eq!(parse_oniguruma("(?:)+?").unwrap(), Expr::Empty); |
| 3079 |
assert_eq!(parse_oniguruma("(?:)??").unwrap(), Expr::Empty); |
| 3080 |
// Possessive modifier |
| 3081 |
assert_eq!(parse_oniguruma("(?:)*+").unwrap(), Expr::Empty); |
| 3082 |
assert_eq!(parse_oniguruma("(?:)++").unwrap(), Expr::Empty); |
| 3083 |
// Both non-greedy and possessive |
| 3084 |
assert_eq!(parse_oniguruma("(?:)*?+").unwrap(), Expr::Empty); |
| 3085 |
} |
| 3086 |
|
| 3087 |
#[test] |
| 3088 |
fn start_line_in_oniguruma_mode() { |
| 3089 |
assert_eq!( |
| 3090 |
parse_oniguruma("(?R:^)").unwrap(), |
| 3091 |
Expr::Assertion(Assertion::StartLineOniguruma { crlf: true }) |
| 3092 |
); |
| 3093 |
assert_eq!( |
| 3094 |
parse_oniguruma("^").unwrap(), |
| 3095 |
Expr::Assertion(Assertion::StartLineOniguruma { crlf: false }) |
| 3096 |
); |
| 3097 |
} |
| 3098 |
|
| 3099 |
#[test] |
| 3100 |
fn empty_noncapturing_group_with_quantifier_extended_mode() { |
| 3101 |
// In (?x) mode, whitespace between the group and quantifier (and |
| 3102 |
// between the quantifier and its modifiers) should be handled |
| 3103 |
// correctly. |
| 3104 |
assert_eq!(parse_oniguruma("(?x: (?:) * )").unwrap(), Expr::Empty); |
| 3105 |
assert_eq!(parse_oniguruma("(?x: (?:) + )").unwrap(), Expr::Empty); |
| 3106 |
assert_eq!(parse_oniguruma("(?x: (?:) ? )").unwrap(), Expr::Empty); |
| 3107 |
assert_eq!(parse_oniguruma("(?x: (?:) {3} )").unwrap(), Expr::Empty); |
| 3108 |
assert_eq!(parse_oniguruma("(?x: (?:) {2,5} )").unwrap(), Expr::Empty); |
| 3109 |
// Non-greedy modifier with whitespace |
| 3110 |
assert_eq!(parse_oniguruma("(?x: (?:) * ? )").unwrap(), Expr::Empty); |
| 3111 |
assert_eq!(parse_oniguruma("(?x: (?:) + ? )").unwrap(), Expr::Empty); |
| 3112 |
// Possessive modifier with whitespace |
| 3113 |
assert_eq!(parse_oniguruma("(?x: (?:) * + )").unwrap(), Expr::Empty); |
| 3114 |
} |
| 3115 |
|
| 3116 |
#[test] |
| 3117 |
fn empty_noncapturing_group_with_quantifier_in_concat() { |
| 3118 |
// Empty group + quantifier in the middle of a larger pattern should |
| 3119 |
// parse correctly, with the empty group collapsing away. |
| 3120 |
assert_eq!( |
| 3121 |
parse_oniguruma("a(?:)*b").unwrap(), |
| 3122 |
Expr::Concat(vec![make_literal("a"), make_literal("b")]) |
| 3123 |
); |
| 3124 |
assert_eq!( |
| 3125 |
parse_oniguruma("(?x: a (?:) * b )").unwrap(), |
| 3126 |
Expr::Concat(vec![make_literal("a"), make_literal("b")]) |
| 3127 |
); |
| 3128 |
} |
| 3129 |
|
| 3130 |
#[test] |
| 3131 |
fn empty_noncapturing_group_with_flags_and_quantifier_oniguruma_mode() { |
| 3132 |
// Non-capturing groups with flags like (?i:) that are empty should |
| 3133 |
// also be handled. |
| 3134 |
assert_eq!(parse_oniguruma("(?i:)*").unwrap(), Expr::Empty); |
| 3135 |
assert_eq!(parse_oniguruma("(?s:)+").unwrap(), Expr::Empty); |
| 3136 |
assert_eq!(parse_oniguruma("(?x: (?i:) * )").unwrap(), Expr::Empty); |
| 3137 |
} |
| 3138 |
|
| 3139 |
#[test] |
| 3140 |
fn swapped_order_quantifier_oniguruma_mode() { |
| 3141 |
assert_eq!( |
| 3142 |
parse_oniguruma("x{3,0}").unwrap(), |
| 3143 |
Expr::AtomicGroup(Box::new(Expr::Repeat { |
| 3144 |
child: Box::new(make_literal("x")), |
| 3145 |
lo: 0, |
| 3146 |
hi: 3, |
| 3147 |
greedy: true, |
| 3148 |
})) |
| 3149 |
); |
| 3150 |
} |
| 3151 |
|
| 3152 |
#[test] |
| 3153 |
fn plus_after_user_specified_quantifier_oniguruma_mode() { |
| 3154 |
assert_eq!( |
| 3155 |
parse_oniguruma("x{2}+").unwrap(), |
| 3156 |
Expr::Repeat { |
| 3157 |
child: Box::new(Expr::Repeat { |
| 3158 |
child: Box::new(make_literal("x")), |
| 3159 |
lo: 2, |
| 3160 |
hi: 2, |
| 3161 |
greedy: true, |
| 3162 |
}), |
| 3163 |
lo: 1, |
| 3164 |
hi: usize::MAX, |
| 3165 |
greedy: true, |
| 3166 |
} |
| 3167 |
); |
| 3168 |
} |
| 3169 |
|
| 3170 |
#[test] |
| 3171 |
fn backref_exists_condition() { |
| 3172 |
assert_eq!( |
| 3173 |
p("(h)?(?(1))"), |
| 3174 |
Expr::Concat(vec![ |
| 3175 |
Expr::Repeat { |
| 3176 |
child: Box::new(make_group(make_literal("h"))), |
| 3177 |
lo: 0, |
| 3178 |
hi: 1, |
| 3179 |
greedy: true |
| 3180 |
}, |
| 3181 |
Expr::BackrefExistsCondition { |
| 3182 |
group: 1, |
| 3183 |
relative_recursion_level: None |
| 3184 |
} |
| 3185 |
]) |
| 3186 |
); |
| 3187 |
assert_eq!( |
| 3188 |
p("(?<h>h)?(?('h'))"), |
| 3189 |
Expr::Concat(vec![ |
| 3190 |
Expr::Repeat { |
| 3191 |
child: Box::new(make_group(make_literal("h"))), |
| 3192 |
lo: 0, |
| 3193 |
hi: 1, |
| 3194 |
greedy: true |
| 3195 |
}, |
| 3196 |
Expr::BackrefExistsCondition { |
| 3197 |
group: 1, |
| 3198 |
relative_recursion_level: None |
| 3199 |
} |
| 3200 |
]) |
| 3201 |
); |
| 3202 |
} |
| 3203 |
|
| 3204 |
#[test] |
| 3205 |
fn backref_exists_condition_with_recursion_level_suffix() { |
| 3206 |
// `(?(1+0)b|c)` is a conditional that tests whether group 1 matched at relative |
| 3207 |
// recursion level 0. The parser accepts it; compile rejects it as not yet supported. |
| 3208 |
// Named forms require delimiters: `(?(<n+0>)...)` or `(?('n+0')...)`. |
| 3209 |
for pattern in &[ |
| 3210 |
r"(a)(?(1+0)b|c)d", |
| 3211 |
r"(?<n>a)(?(<n+0>)b|c)d", |
| 3212 |
r"(?<n>a)(?('n+0')b|c)d", |
| 3213 |
] { |
| 3214 |
assert_eq!( |
| 3215 |
p(pattern), |
| 3216 |
Expr::Concat(vec![ |
| 3217 |
make_group(make_literal("a")), |
| 3218 |
Expr::Conditional { |
| 3219 |
condition: Box::new(Expr::BackrefExistsCondition { |
| 3220 |
group: 1, |
| 3221 |
relative_recursion_level: Some(0), |
| 3222 |
}), |
| 3223 |
true_branch: Box::new(make_literal("b")), |
| 3224 |
false_branch: Box::new(make_literal("c")), |
| 3225 |
}, |
| 3226 |
make_literal("d"), |
| 3227 |
]), |
| 3228 |
"pattern: {pattern:?}", |
| 3229 |
); |
| 3230 |
} |
| 3231 |
} |
| 3232 |
|
| 3233 |
#[test] |
| 3234 |
fn conditional_non_backref_validity_check_without_branches() { |
| 3235 |
assert_error( |
| 3236 |
"(?(foo))", |
| 3237 |
"Parsing error at position 7: General parsing error: expected conditional to be a backreference or at least an expression for when the condition is true", |
| 3238 |
); |
| 3239 |
} |
| 3240 |
|
| 3241 |
#[test] |
| 3242 |
fn conditional_invalid_target_of_repeat_operator() { |
| 3243 |
assert_error( |
| 3244 |
r"(?(?=\d)\w|!)", |
| 3245 |
"Parsing error at position 3: Target of repeat operator is invalid", |
| 3246 |
); |
| 3247 |
} |
| 3248 |
|
| 3249 |
#[test] |
| 3250 |
fn conditional_unclosed_at_end_of_pattern() { |
| 3251 |
assert_error( |
| 3252 |
r"(?(", |
| 3253 |
"Parsing error at position 3: Opening parenthesis without closing parenthesis", |
| 3254 |
); |
| 3255 |
} |
| 3256 |
|
| 3257 |
#[test] |
| 3258 |
fn subroutine_call_unclosed_at_end_of_pattern() { |
| 3259 |
assert_error( |
| 3260 |
r"\g<", |
| 3261 |
"Parsing error at position 2: Could not parse group name", |
| 3262 |
); |
| 3263 |
|
| 3264 |
assert_error( |
| 3265 |
r"\g<name", |
| 3266 |
"Parsing error at position 2: Could not parse group name", |
| 3267 |
); |
| 3268 |
|
| 3269 |
assert_error( |
| 3270 |
r"\g'", |
| 3271 |
"Parsing error at position 2: Could not parse group name", |
| 3272 |
); |
| 3273 |
|
| 3274 |
assert_error( |
| 3275 |
r"\g''", |
| 3276 |
"Parsing error at position 2: Could not parse group name", |
| 3277 |
); |
| 3278 |
|
| 3279 |
assert_error( |
| 3280 |
r"\g<>", |
| 3281 |
"Parsing error at position 2: Could not parse group name", |
| 3282 |
); |
| 3283 |
|
| 3284 |
assert_error(r"\g", "Parsing error at position 0: Invalid escape: \\g"); |
| 3285 |
|
| 3286 |
assert_error( |
| 3287 |
r"\g test", |
| 3288 |
"Parsing error at position 2: Could not parse group name", |
| 3289 |
); |
| 3290 |
} |
| 3291 |
|
| 3292 |
#[test] |
| 3293 |
fn subroutine_call_missing_subroutine_reference() { |
| 3294 |
assert_error( |
| 3295 |
r"\g test", |
| 3296 |
"Parsing error at position 2: Could not parse group name", |
| 3297 |
); |
| 3298 |
} |
| 3299 |
|
| 3300 |
#[test] |
| 3301 |
fn subroutine_call_name_includes_dash() { |
| 3302 |
// With unrestricted names in subroutine calls, these are now valid names |
| 3303 |
// (though they won't resolve to actual groups, that's caught during analysis) |
| 3304 |
let tree = Expr::parse_tree(r"\g<1-0>(?<1-0>a)").unwrap(); |
| 3305 |
assert!(tree.contains_subroutines); |
| 3306 |
|
| 3307 |
let tree = Expr::parse_tree(r"\g<name+1>(?<name+1>a)").unwrap(); |
| 3308 |
assert!(tree.contains_subroutines); |
| 3309 |
} |
| 3310 |
|
| 3311 |
#[test] |
| 3312 |
fn backref_condition_with_one_two_or_three_branches() { |
| 3313 |
assert_eq!( |
| 3314 |
p("(h)?(?(1)i|x)"), |
| 3315 |
Expr::Concat(vec![ |
| 3316 |
Expr::Repeat { |
| 3317 |
child: Box::new(make_group(make_literal("h"))), |
| 3318 |
lo: 0, |
| 3319 |
hi: 1, |
| 3320 |
greedy: true |
| 3321 |
}, |
| 3322 |
Expr::Conditional { |
| 3323 |
condition: Box::new(Expr::BackrefExistsCondition { |
| 3324 |
group: 1, |
| 3325 |
relative_recursion_level: None |
| 3326 |
}), |
| 3327 |
true_branch: Box::new(make_literal("i")), |
| 3328 |
false_branch: Box::new(make_literal("x")), |
| 3329 |
}, |
| 3330 |
]) |
| 3331 |
); |
| 3332 |
|
| 3333 |
assert_eq!( |
| 3334 |
p("(h)?(?(1)i)"), |
| 3335 |
Expr::Concat(vec![ |
| 3336 |
Expr::Repeat { |
| 3337 |
child: Box::new(make_group(make_literal("h"))), |
| 3338 |
lo: 0, |
| 3339 |
hi: 1, |
| 3340 |
greedy: true |
| 3341 |
}, |
| 3342 |
Expr::Conditional { |
| 3343 |
condition: Box::new(Expr::BackrefExistsCondition { |
| 3344 |
group: 1, |
| 3345 |
relative_recursion_level: None |
| 3346 |
}), |
| 3347 |
true_branch: Box::new(make_literal("i")), |
| 3348 |
false_branch: Box::new(Expr::Empty), |
| 3349 |
}, |
| 3350 |
]) |
| 3351 |
); |
| 3352 |
|
| 3353 |
assert_eq!( |
| 3354 |
p("(h)?(?(1)ii|xy|z)"), |
| 3355 |
Expr::Concat(vec![ |
| 3356 |
Expr::Repeat { |
| 3357 |
child: Box::new(make_group(make_literal("h"))), |
| 3358 |
lo: 0, |
| 3359 |
hi: 1, |
| 3360 |
greedy: true |
| 3361 |
}, |
| 3362 |
Expr::Conditional { |
| 3363 |
condition: Box::new(Expr::BackrefExistsCondition { |
| 3364 |
group: 1, |
| 3365 |
relative_recursion_level: None |
| 3366 |
}), |
| 3367 |
true_branch: Box::new(Expr::Concat( |
| 3368 |
vec![make_literal("i"), make_literal("i"),] |
| 3369 |
)), |
| 3370 |
false_branch: Box::new(Expr::Alt(vec![ |
| 3371 |
Expr::Concat(vec![make_literal("x"), make_literal("y"),]), |
| 3372 |
make_literal("z"), |
| 3373 |
])), |
| 3374 |
}, |
| 3375 |
]) |
| 3376 |
); |
| 3377 |
|
| 3378 |
assert_eq!( |
| 3379 |
p("(?<cap>h)?(?(<cap>)ii|xy|z)"), |
| 3380 |
Expr::Concat(vec![ |
| 3381 |
Expr::Repeat { |
| 3382 |
child: Box::new(make_group(make_literal("h"))), |
| 3383 |
lo: 0, |
| 3384 |
hi: 1, |
| 3385 |
greedy: true |
| 3386 |
}, |
| 3387 |
Expr::Conditional { |
| 3388 |
condition: Box::new(Expr::BackrefExistsCondition { |
| 3389 |
group: 1, |
| 3390 |
relative_recursion_level: None |
| 3391 |
}), |
| 3392 |
true_branch: Box::new(Expr::Concat( |
| 3393 |
vec![make_literal("i"), make_literal("i"),] |
| 3394 |
)), |
| 3395 |
false_branch: Box::new(Expr::Alt(vec![ |
| 3396 |
Expr::Concat(vec![make_literal("x"), make_literal("y"),]), |
| 3397 |
make_literal("z"), |
| 3398 |
])), |
| 3399 |
}, |
| 3400 |
]) |
| 3401 |
); |
| 3402 |
} |
| 3403 |
|
| 3404 |
#[test] |
| 3405 |
fn conditional() { |
| 3406 |
assert_eq!( |
| 3407 |
p("((?(a)b|c))(\\1)"), |
| 3408 |
Expr::Concat(vec![ |
| 3409 |
make_group(Expr::Conditional { |
| 3410 |
condition: Box::new(make_literal("a")), |
| 3411 |
true_branch: Box::new(make_literal("b")), |
| 3412 |
false_branch: Box::new(make_literal("c")) |
| 3413 |
}), |
| 3414 |
make_group(Expr::Backref { |
| 3415 |
group: 1, |
| 3416 |
casei: false, |
| 3417 |
},) |
| 3418 |
]) |
| 3419 |
); |
| 3420 |
|
| 3421 |
assert_eq!( |
| 3422 |
p(r"^(?(\d)abc|\d!)$"), |
| 3423 |
Expr::Concat(vec![ |
| 3424 |
Expr::Assertion(Assertion::StartText), |
| 3425 |
Expr::Conditional { |
| 3426 |
condition: Box::new(Expr::Delegate { |
| 3427 |
inner: "\\d".to_string(), |
| 3428 |
casei: false, |
| 3429 |
}), |
| 3430 |
true_branch: Box::new(Expr::Concat(vec![ |
| 3431 |
make_literal("a"), |
| 3432 |
make_literal("b"), |
| 3433 |
make_literal("c"), |
| 3434 |
])), |
| 3435 |
false_branch: Box::new(Expr::Concat(vec![ |
| 3436 |
Expr::Delegate { |
| 3437 |
inner: "\\d".to_string(), |
| 3438 |
casei: false, |
| 3439 |
}, |
| 3440 |
make_literal("!"), |
| 3441 |
])), |
| 3442 |
}, |
| 3443 |
Expr::Assertion(Assertion::EndText), |
| 3444 |
]) |
| 3445 |
); |
| 3446 |
|
| 3447 |
assert_eq!( |
| 3448 |
p(r"(?((?=\d))\w|!)"), |
| 3449 |
Expr::Conditional { |
| 3450 |
condition: Box::new(Expr::LookAround( |
| 3451 |
Box::new(Expr::Delegate { |
| 3452 |
inner: "\\d".to_string(), |
| 3453 |
casei: false, |
| 3454 |
}), |
| 3455 |
LookAhead |
| 3456 |
)), |
| 3457 |
true_branch: Box::new(Expr::Delegate { |
| 3458 |
inner: "\\w".to_string(), |
| 3459 |
casei: false, |
| 3460 |
}), |
| 3461 |
false_branch: Box::new(make_literal("!")), |
| 3462 |
}, |
| 3463 |
); |
| 3464 |
|
| 3465 |
assert_eq!( |
| 3466 |
p(r"(?((ab))c|d)"), |
| 3467 |
Expr::Conditional { |
| 3468 |
condition: Box::new(make_group(Expr::Concat(vec![ |
| 3469 |
make_literal("a"), |
| 3470 |
make_literal("b"), |
| 3471 |
]),)), |
| 3472 |
true_branch: Box::new(make_literal("c")), |
| 3473 |
false_branch: Box::new(make_literal("d")), |
| 3474 |
}, |
| 3475 |
); |
| 3476 |
} |
| 3477 |
|
| 3478 |
#[test] |
| 3479 |
fn subroutines() { |
| 3480 |
assert_eq!( |
| 3481 |
p(r"(a)\g1"), |
| 3482 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3483 |
); |
| 3484 |
|
| 3485 |
assert_eq!( |
| 3486 |
p(r"(a)\g<1>"), |
| 3487 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3488 |
); |
| 3489 |
|
| 3490 |
assert_eq!( |
| 3491 |
p(r"(?<group_name>a)\g<group_name>"), |
| 3492 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3493 |
); |
| 3494 |
|
| 3495 |
assert_eq!( |
| 3496 |
p(r"(?<group_name>a)\g'group_name'"), |
| 3497 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3498 |
); |
| 3499 |
|
| 3500 |
assert_eq!( |
| 3501 |
p(r"(?<group_name>a)(?P>group_name)"), |
| 3502 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3503 |
); |
| 3504 |
} |
| 3505 |
|
| 3506 |
#[test] |
| 3507 |
fn subroutines_with_unrestricted_names() { |
| 3508 |
// Hyphenated names via \g<name> |
| 3509 |
assert_eq!( |
| 3510 |
p(r"(?<foo-bar>a)\g<foo-bar>"), |
| 3511 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3512 |
); |
| 3513 |
|
| 3514 |
// Hyphenated names via \g'name' |
| 3515 |
assert_eq!( |
| 3516 |
p(r"(?<foo-bar>a)\g'foo-bar'"), |
| 3517 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3518 |
); |
| 3519 |
|
| 3520 |
// Hyphenated names via (?P>name) |
| 3521 |
assert_eq!( |
| 3522 |
p(r"(?<foo-bar>a)(?P>foo-bar)"), |
| 3523 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3524 |
); |
| 3525 |
|
| 3526 |
// Forward reference with hyphenated name |
| 3527 |
assert_eq!( |
| 3528 |
p(r"\g<foo-bar>(?<foo-bar>a)"), |
| 3529 |
Expr::Concat(vec![Expr::SubroutineCall(1), make_group(make_literal("a"))]) |
| 3530 |
); |
| 3531 |
|
| 3532 |
// Emoji name via \g |
| 3533 |
assert_eq!( |
| 3534 |
p("(?<\u{1F3AF}>a)\\g<\u{1F3AF}>"), |
| 3535 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3536 |
); |
| 3537 |
|
| 3538 |
// Emoji name via (?P>) |
| 3539 |
assert_eq!( |
| 3540 |
p("(?<\u{1F3AF}>a)(?P>\u{1F3AF})"), |
| 3541 |
Expr::Concat(vec![make_group(make_literal("a")), Expr::SubroutineCall(1)]) |
| 3542 |
); |
| 3543 |
|
| 3544 |
// Space in name via \g |
| 3545 |
assert_eq!( |
| 3546 |
p(r"(?<a b>x)\g<a b>"), |
| 3547 |
Expr::Concat(vec![make_group(make_literal("x")), Expr::SubroutineCall(1)]) |
| 3548 |
); |
| 3549 |
} |
| 3550 |
|
| 3551 |
#[test] |
| 3552 |
fn subroutine_defined_later() { |
| 3553 |
assert_eq!( |
| 3554 |
p(r"\g<name>(?<name>a)"), |
| 3555 |
Expr::Concat(vec![Expr::SubroutineCall(1), make_group(make_literal("a")),]) |
| 3556 |
); |
| 3557 |
|
| 3558 |
assert_eq!( |
| 3559 |
p(r"\g<c>(?:a|b|(?<c>c)?)"), |
| 3560 |
Expr::Concat(vec![ |
| 3561 |
Expr::SubroutineCall(1), |
| 3562 |
Expr::Alt(vec![ |
| 3563 |
make_literal("a"), |
| 3564 |
make_literal("b"), |
| 3565 |
Expr::Repeat { |
| 3566 |
child: Box::new(make_group(make_literal("c"))), |
| 3567 |
lo: 0, |
| 3568 |
hi: 1, |
| 3569 |
greedy: true |
| 3570 |
} |
| 3571 |
]) |
| 3572 |
]) |
| 3573 |
); |
| 3574 |
|
| 3575 |
assert_eq!( |
| 3576 |
p(r"(?<a>a)?\g<b>(?(<a>)(?<b>b)|c)"), |
| 3577 |
Expr::Concat(vec![ |
| 3578 |
Expr::Repeat { |
| 3579 |
child: Box::new(make_group(make_literal("a"))), |
| 3580 |
lo: 0, |
| 3581 |
hi: 1, |
| 3582 |
greedy: true |
| 3583 |
}, |
| 3584 |
Expr::SubroutineCall(2), |
| 3585 |
Expr::Conditional { |
| 3586 |
condition: Box::new(Expr::BackrefExistsCondition { |
| 3587 |
group: 1, |
| 3588 |
relative_recursion_level: None |
| 3589 |
}), |
| 3590 |
true_branch: Box::new(make_group(make_literal("b"))), |
| 3591 |
false_branch: Box::new(make_literal("c")), |
| 3592 |
} |
| 3593 |
]) |
| 3594 |
); |
| 3595 |
|
| 3596 |
assert_eq!( |
| 3597 |
p(r"\g<1>(a)"), |
| 3598 |
Expr::Concat(vec![Expr::SubroutineCall(1), make_group(make_literal("a")),]) |
| 3599 |
); |
| 3600 |
} |
| 3601 |
|
| 3602 |
#[test] |
| 3603 |
fn recursive_subroutine_call() { |
| 3604 |
assert_eq!( |
| 3605 |
p(r"\A(?<a>|.|(?:(?<b>.)\g<a>\k<b>))\z"), |
| 3606 |
Expr::Concat(vec![ |
| 3607 |
Expr::Assertion(Assertion::StartText,), |
| 3608 |
make_group(Expr::Alt(vec![ |
| 3609 |
Expr::Empty, |
| 3610 |
Expr::Any { |
| 3611 |
newline: false, |
| 3612 |
crlf: false |
| 3613 |
}, |
| 3614 |
Expr::Concat(vec![ |
| 3615 |
make_group(Expr::Any { |
| 3616 |
newline: false, |
| 3617 |
crlf: false |
| 3618 |
},), |
| 3619 |
Expr::SubroutineCall(1,), |
| 3620 |
Expr::Backref { |
| 3621 |
group: 2, |
| 3622 |
casei: false, |
| 3623 |
}, |
| 3624 |
],), |
| 3625 |
],),), |
| 3626 |
Expr::Assertion(Assertion::EndText,), |
| 3627 |
],) |
| 3628 |
); |
| 3629 |
} |
| 3630 |
|
| 3631 |
#[test] |
| 3632 |
fn self_recursive_subroutine_call() { |
| 3633 |
let tree = Expr::parse_tree(r"hello\g<0>?world").unwrap(); |
| 3634 |
assert!(tree.self_recursive); |
| 3635 |
assert!(tree.numeric_capture_group_references); |
| 3636 |
|
| 3637 |
let tree = Expr::parse_tree(r"hello\g0?world").unwrap(); |
| 3638 |
assert!(tree.self_recursive); |
| 3639 |
assert!(tree.numeric_capture_group_references); |
| 3640 |
|
| 3641 |
let tree = Expr::parse_tree(r"hello world").unwrap(); |
| 3642 |
assert!(!tree.self_recursive); |
| 3643 |
assert!(!tree.numeric_capture_group_references); |
| 3644 |
|
| 3645 |
let tree = Expr::parse_tree(r"hello\g1world").unwrap(); |
| 3646 |
assert!(!tree.self_recursive); |
| 3647 |
assert!(tree.numeric_capture_group_references); |
| 3648 |
|
| 3649 |
let tree = Expr::parse_tree(r"hello\g<1>world").unwrap(); |
| 3650 |
assert!(!tree.self_recursive); |
| 3651 |
assert!(tree.numeric_capture_group_references); |
| 3652 |
|
| 3653 |
let tree = Expr::parse_tree(r"(hello\g1?world)").unwrap(); |
| 3654 |
assert!(!tree.self_recursive); |
| 3655 |
assert!(tree.numeric_capture_group_references); |
| 3656 |
|
| 3657 |
let tree = Expr::parse_tree(r"(?<a>hello\g<a>world)").unwrap(); |
| 3658 |
assert!(!tree.self_recursive); |
| 3659 |
assert!(!tree.numeric_capture_group_references); |
| 3660 |
} |
| 3661 |
|
| 3662 |
// found by cargo fuzz, then minimized |
| 3663 |
#[test] |
| 3664 |
fn fuzz_1() { |
| 3665 |
p(r"\ä"); |
| 3666 |
} |
| 3667 |
|
| 3668 |
#[test] |
| 3669 |
fn fuzz_2() { |
| 3670 |
p(r"\pä"); |
| 3671 |
} |
| 3672 |
|
| 3673 |
#[test] |
| 3674 |
fn fuzz_3() { |
| 3675 |
fail(r"(?()^"); |
| 3676 |
fail(r#"!w(?()\"Kuz>"#); |
| 3677 |
} |
| 3678 |
|
| 3679 |
#[test] |
| 3680 |
fn fuzz_4() { |
| 3681 |
fail(r"\u{2}(?(2)"); |
| 3682 |
} |
| 3683 |
|
| 3684 |
#[test] |
| 3685 |
fn word_boundary_brace_syntax() { |
| 3686 |
// Valid patterns produce correct assertions |
| 3687 |
assert_eq!( |
| 3688 |
p(r"\b{start}"), |
| 3689 |
Expr::Assertion(Assertion::LeftWordBoundary) |
| 3690 |
); |
| 3691 |
assert_eq!(p(r"\b{end}"), Expr::Assertion(Assertion::RightWordBoundary)); |
| 3692 |
assert_eq!( |
| 3693 |
p(r"\b{start-half}"), |
| 3694 |
Expr::Assertion(Assertion::LeftWordHalfBoundary) |
| 3695 |
); |
| 3696 |
assert_eq!( |
| 3697 |
p(r"\b{end-half}"), |
| 3698 |
Expr::Assertion(Assertion::RightWordHalfBoundary) |
| 3699 |
); |
| 3700 |
} |
| 3701 |
|
| 3702 |
#[test] |
| 3703 |
fn word_boundary_brace_parsing_errors() { |
| 3704 |
// Invalid patterns produce expected errors |
| 3705 |
let test_cases = [ |
| 3706 |
(r"\b{invalid}", "Invalid escape: \\b{invalid}"), |
| 3707 |
(r"\b{start ", "Invalid escape: \\b{...}"), |
| 3708 |
(r"\b{end ", "Invalid escape: \\b{...}"), |
| 3709 |
(r"\b{}", "Invalid escape: \\b{}"), |
| 3710 |
(r"\b{", "Invalid escape: \\b{...}"), |
| 3711 |
(r"\b{ }", "Invalid escape: \\b{ }"), |
| 3712 |
(r"\b{START}", "Invalid escape: \\b{START}"), |
| 3713 |
(r"\b{END}", "Invalid escape: \\b{END}"), |
| 3714 |
(r"\b{ s t a r t }", "Invalid escape: \\b{ s t a r t }"), |
| 3715 |
// \B{...} patterns should fail |
| 3716 |
(r"\B{start}", "Invalid escape: \\B{start}"), |
| 3717 |
(r"\B{end}", "Invalid escape: \\B{end}"), |
| 3718 |
(r"\B{start-half}", "Invalid escape: \\B{start-half}"), |
| 3719 |
(r"\B{end-half}", "Invalid escape: \\B{end-half}"), |
| 3720 |
(r"\c{start}", "Invalid escape: \\c"), |
| 3721 |
]; |
| 3722 |
|
| 3723 |
for (pattern, expected_error) in test_cases { |
| 3724 |
assert_error( |
| 3725 |
pattern, |
| 3726 |
&format!("Parsing error at position 0: {}", expected_error), |
| 3727 |
); |
| 3728 |
} |
| 3729 |
} |
| 3730 |
|
| 3731 |
fn get_options(func: impl Fn(SyntaxConfig) -> SyntaxConfig) -> RegexOptions { |
| 3732 |
let mut options = RegexOptions::default(); |
| 3733 |
options.syntaxc = func(options.syntaxc); |
| 3734 |
options |
| 3735 |
} |
| 3736 |
|
| 3737 |
#[test] |
| 3738 |
fn parse_with_case_insensitive_in_pattern() { |
| 3739 |
let tree = Expr::parse_tree("(?i)hello"); |
| 3740 |
let expr = tree.unwrap().expr; |
| 3741 |
|
| 3742 |
assert_eq!( |
| 3743 |
expr, |
| 3744 |
Expr::Concat(vec![ |
| 3745 |
make_literal_case_insensitive("h", true), |
| 3746 |
make_literal_case_insensitive("e", true), |
| 3747 |
make_literal_case_insensitive("l", true), |
| 3748 |
make_literal_case_insensitive("l", true), |
| 3749 |
make_literal_case_insensitive("o", true) |
| 3750 |
]) |
| 3751 |
); |
| 3752 |
} |
| 3753 |
|
| 3754 |
#[test] |
| 3755 |
fn parse_with_case_insensitive_option() { |
| 3756 |
let options = get_options(|x| x.case_insensitive(true)); |
| 3757 |
|
| 3758 |
let tree = Expr::parse_tree_with_flags("hello", options.compute_flags()); |
| 3759 |
let expr = tree.unwrap().expr; |
| 3760 |
|
| 3761 |
assert_eq!( |
| 3762 |
expr, |
| 3763 |
Expr::Concat(vec![ |
| 3764 |
make_literal_case_insensitive("h", true), |
| 3765 |
make_literal_case_insensitive("e", true), |
| 3766 |
make_literal_case_insensitive("l", true), |
| 3767 |
make_literal_case_insensitive("l", true), |
| 3768 |
make_literal_case_insensitive("o", true) |
| 3769 |
]) |
| 3770 |
); |
| 3771 |
} |
| 3772 |
|
| 3773 |
#[test] |
| 3774 |
fn parse_with_multiline_in_pattern() { |
| 3775 |
let options = get_options(|x| x); |
| 3776 |
|
| 3777 |
let tree = Expr::parse_tree_with_flags("(?m)^hello$", options.compute_flags()); |
| 3778 |
let expr = tree.unwrap().expr; |
| 3779 |
|
| 3780 |
assert_eq!( |
| 3781 |
expr, |
| 3782 |
Expr::Concat(vec![ |
| 3783 |
Expr::Assertion(Assertion::StartLine { crlf: false }), |
| 3784 |
make_literal("h"), |
| 3785 |
make_literal("e"), |
| 3786 |
make_literal("l"), |
| 3787 |
make_literal("l"), |
| 3788 |
make_literal("o"), |
| 3789 |
Expr::Assertion(Assertion::EndLine { crlf: false }) |
| 3790 |
]) |
| 3791 |
); |
| 3792 |
} |
| 3793 |
|
| 3794 |
#[test] |
| 3795 |
fn parse_with_multiline_option() { |
| 3796 |
let options = get_options(|x| x.multi_line(true)); |
| 3797 |
|
| 3798 |
let tree = Expr::parse_tree_with_flags("^hello$", options.compute_flags()); |
| 3799 |
let expr = tree.unwrap().expr; |
| 3800 |
|
| 3801 |
assert_eq!( |
| 3802 |
expr, |
| 3803 |
Expr::Concat(vec![ |
| 3804 |
Expr::Assertion(Assertion::StartLine { crlf: false }), |
| 3805 |
make_literal("h"), |
| 3806 |
make_literal("e"), |
| 3807 |
make_literal("l"), |
| 3808 |
make_literal("l"), |
| 3809 |
make_literal("o"), |
| 3810 |
Expr::Assertion(Assertion::EndLine { crlf: false }) |
| 3811 |
]) |
| 3812 |
); |
| 3813 |
} |
| 3814 |
|
| 3815 |
#[test] |
| 3816 |
fn parse_with_dot_matches_new_line_in_pattern() { |
| 3817 |
let options = get_options(|x| x); |
| 3818 |
|
| 3819 |
let tree = Expr::parse_tree_with_flags("(?s)(.*)", options.compute_flags()); |
| 3820 |
let expr = tree.unwrap().expr; |
| 3821 |
|
| 3822 |
assert_eq!( |
| 3823 |
expr, |
| 3824 |
make_group(Expr::Repeat { |
| 3825 |
child: Box::new(Expr::Any { |
| 3826 |
newline: true, |
| 3827 |
crlf: false |
| 3828 |
}), |
| 3829 |
lo: 0, |
| 3830 |
hi: usize::MAX, |
| 3831 |
greedy: true |
| 3832 |
}) |
| 3833 |
); |
| 3834 |
} |
| 3835 |
|
| 3836 |
#[test] |
| 3837 |
fn parse_with_dot_matches_new_line_option() { |
| 3838 |
let options = get_options(|x| x.dot_matches_new_line(true)); |
| 3839 |
|
| 3840 |
let tree = Expr::parse_tree_with_flags("(.*)", options.compute_flags()); |
| 3841 |
let expr = tree.unwrap().expr; |
| 3842 |
|
| 3843 |
assert_eq!( |
| 3844 |
expr, |
| 3845 |
make_group(Expr::Repeat { |
| 3846 |
child: Box::new(Expr::Any { |
| 3847 |
newline: true, |
| 3848 |
crlf: false |
| 3849 |
}), |
| 3850 |
lo: 0, |
| 3851 |
hi: usize::MAX, |
| 3852 |
greedy: true |
| 3853 |
}) |
| 3854 |
); |
| 3855 |
} |
| 3856 |
|
| 3857 |
#[test] |
| 3858 |
fn parse_fancy_with_dot_matches_new_line_in_pattern() { |
| 3859 |
let options = get_options(|x| x.dot_matches_new_line(true)); |
| 3860 |
|
| 3861 |
let tree = Expr::parse_tree_with_flags("(.*)(?<=hugo)", options.compute_flags()); |
| 3862 |
let expr = tree.unwrap().expr; |
| 3863 |
|
| 3864 |
assert_eq!( |
| 3865 |
expr, |
| 3866 |
Expr::Concat(vec![ |
| 3867 |
make_group(Expr::Repeat { |
| 3868 |
child: Box::new(Expr::Any { |
| 3869 |
newline: true, |
| 3870 |
crlf: false |
| 3871 |
}), |
| 3872 |
lo: 0, |
| 3873 |
hi: usize::MAX, |
| 3874 |
greedy: true |
| 3875 |
}), |
| 3876 |
Expr::LookAround( |
| 3877 |
Box::new(Expr::Concat(vec![ |
| 3878 |
make_literal("h"), |
| 3879 |
make_literal("u"), |
| 3880 |
make_literal("g"), |
| 3881 |
make_literal("o") |
| 3882 |
])), |
| 3883 |
LookBehind |
| 3884 |
) |
| 3885 |
]) |
| 3886 |
); |
| 3887 |
} |
| 3888 |
|
| 3889 |
#[test] |
| 3890 |
fn parse_with_case_insensitive_from_pattern_and_multi_line_option() { |
| 3891 |
let options = get_options(|x| x.multi_line(true)); |
| 3892 |
|
| 3893 |
let tree = Expr::parse_tree_with_flags("(?i)^hello$", options.compute_flags()); |
| 3894 |
let expr = tree.unwrap().expr; |
| 3895 |
|
| 3896 |
assert_eq!( |
| 3897 |
expr, |
| 3898 |
Expr::Concat(vec![ |
| 3899 |
Expr::Assertion(Assertion::StartLine { crlf: false }), |
| 3900 |
make_literal_case_insensitive("h", true), |
| 3901 |
make_literal_case_insensitive("e", true), |
| 3902 |
make_literal_case_insensitive("l", true), |
| 3903 |
make_literal_case_insensitive("l", true), |
| 3904 |
make_literal_case_insensitive("o", true), |
| 3905 |
Expr::Assertion(Assertion::EndLine { crlf: false }) |
| 3906 |
]) |
| 3907 |
); |
| 3908 |
} |
| 3909 |
|
| 3910 |
#[test] |
| 3911 |
fn parse_with_multi_line_and_case_insensitive_options() { |
| 3912 |
let mut options = get_options(|x| x.multi_line(true)); |
| 3913 |
options.syntaxc = options.syntaxc.case_insensitive(true); |
| 3914 |
|
| 3915 |
let tree = Expr::parse_tree_with_flags("^hello$", options.compute_flags()); |
| 3916 |
let expr = tree.unwrap().expr; |
| 3917 |
|
| 3918 |
assert_eq!( |
| 3919 |
expr, |
| 3920 |
Expr::Concat(vec![ |
| 3921 |
Expr::Assertion(Assertion::StartLine { crlf: false }), |
| 3922 |
make_literal_case_insensitive("h", true), |
| 3923 |
make_literal_case_insensitive("e", true), |
| 3924 |
make_literal_case_insensitive("l", true), |
| 3925 |
make_literal_case_insensitive("l", true), |
| 3926 |
make_literal_case_insensitive("o", true), |
| 3927 |
Expr::Assertion(Assertion::EndLine { crlf: false }) |
| 3928 |
]) |
| 3929 |
); |
| 3930 |
} |
| 3931 |
|
| 3932 |
#[test] |
| 3933 |
fn parse_backtracking_control_verbs() { |
| 3934 |
assert_eq!( |
| 3935 |
p(r"(*FAIL)"), |
| 3936 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Fail) |
| 3937 |
); |
| 3938 |
assert_eq!( |
| 3939 |
p(r"(*F)"), |
| 3940 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Fail) |
| 3941 |
); |
| 3942 |
assert_eq!( |
| 3943 |
p(r"a(*FAIL)"), |
| 3944 |
Expr::Concat(vec![ |
| 3945 |
make_literal("a"), |
| 3946 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Fail) |
| 3947 |
]) |
| 3948 |
); |
| 3949 |
assert_eq!( |
| 3950 |
p(r"(?(*FAIL)a|b)"), |
| 3951 |
Expr::Conditional { |
| 3952 |
condition: Box::new(Expr::BacktrackingControlVerb(BacktrackingControlVerb::Fail)), |
| 3953 |
true_branch: Box::new(make_literal("a")), |
| 3954 |
false_branch: Box::new(make_literal("b")) |
| 3955 |
} |
| 3956 |
); |
| 3957 |
|
| 3958 |
assert_eq!( |
| 3959 |
p(r"(*ACCEPT)"), |
| 3960 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Accept) |
| 3961 |
); |
| 3962 |
assert_eq!( |
| 3963 |
p(r"(*COMMIT)"), |
| 3964 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Commit) |
| 3965 |
); |
| 3966 |
assert_eq!( |
| 3967 |
p(r"(*SKIP)"), |
| 3968 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Skip) |
| 3969 |
); |
| 3970 |
assert_eq!( |
| 3971 |
p(r"(*PRUNE)"), |
| 3972 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Prune) |
| 3973 |
); |
| 3974 |
|
| 3975 |
assert_error( |
| 3976 |
"(*RANDOM)", |
| 3977 |
"Parsing error at position 1: Target of repeat operator is invalid", |
| 3978 |
); |
| 3979 |
} |
| 3980 |
|
| 3981 |
#[test] |
| 3982 |
fn remap_unicode_property_if_necessary_outside_class_tests() { |
| 3983 |
// Test \p with unicode flag |
| 3984 |
assert_eq!( |
| 3985 |
remap_unicode_property_if_necessary(r"\p{alnum}", true, false), |
| 3986 |
r"[\p{alpha}\p{digit}]" |
| 3987 |
); |
| 3988 |
assert_eq!( |
| 3989 |
remap_unicode_property_if_necessary(r"\p{blank}", true, false), |
| 3990 |
r"[\p{Zs}\x09]" |
| 3991 |
); |
| 3992 |
assert_eq!( |
| 3993 |
remap_unicode_property_if_necessary(r"\p{word}", true, false), |
| 3994 |
r"\w" |
| 3995 |
); |
| 3996 |
assert_eq!( |
| 3997 |
remap_unicode_property_if_necessary(r"\p{Greek}", true, false), |
| 3998 |
r"\p{greek}" |
| 3999 |
); |
| 4000 |
|
| 4001 |
// Test \p without unicode flag |
| 4002 |
assert_eq!( |
| 4003 |
remap_unicode_property_if_necessary(r"\p{alnum}", false, false), |
| 4004 |
r"[[:alnum:]]" |
| 4005 |
); |
| 4006 |
assert_eq!( |
| 4007 |
remap_unicode_property_if_necessary(r"\p{blank}", false, false), |
| 4008 |
r"[\t ]" |
| 4009 |
); |
| 4010 |
assert_eq!( |
| 4011 |
remap_unicode_property_if_necessary(r"\p{word}", false, false), |
| 4012 |
r"[_[:alnum:]]" |
| 4013 |
); |
| 4014 |
assert_eq!( |
| 4015 |
remap_unicode_property_if_necessary(r"\p{Greek}", false, false), |
| 4016 |
r"\p{greek}" |
| 4017 |
); |
| 4018 |
|
| 4019 |
// Test \P with unicode flag |
| 4020 |
assert_eq!( |
| 4021 |
remap_unicode_property_if_necessary(r"\P{alnum}", true, false), |
| 4022 |
r"[^\p{alpha}\p{digit}]" |
| 4023 |
); |
| 4024 |
assert_eq!( |
| 4025 |
remap_unicode_property_if_necessary(r"\P{blank}", true, false), |
| 4026 |
r"[^\p{Zs}\x09]" |
| 4027 |
); |
| 4028 |
assert_eq!( |
| 4029 |
remap_unicode_property_if_necessary(r"\P{word}", true, false), |
| 4030 |
r"\W" |
| 4031 |
); |
| 4032 |
assert_eq!( |
| 4033 |
remap_unicode_property_if_necessary(r"\P{Greek}", true, false), |
| 4034 |
r"\P{greek}" |
| 4035 |
); |
| 4036 |
|
| 4037 |
// Test \P without unicode flag |
| 4038 |
assert_eq!( |
| 4039 |
remap_unicode_property_if_necessary(r"\P{alnum}", false, false), |
| 4040 |
r"[^[:alnum:]]" |
| 4041 |
); |
| 4042 |
assert_eq!( |
| 4043 |
remap_unicode_property_if_necessary(r"\P{blank}", false, false), |
| 4044 |
r"[^\t ]" |
| 4045 |
); |
| 4046 |
assert_eq!( |
| 4047 |
remap_unicode_property_if_necessary(r"\P{word}", false, false), |
| 4048 |
r"[^_[:alnum:]]" |
| 4049 |
); |
| 4050 |
assert_eq!( |
| 4051 |
remap_unicode_property_if_necessary(r"\P{Greek}", false, false), |
| 4052 |
r"\P{greek}" |
| 4053 |
); |
| 4054 |
|
| 4055 |
// Test \p{cntrl} with unicode flag |
| 4056 |
assert_eq!( |
| 4057 |
remap_unicode_property_if_necessary(r"\p{cntrl}", true, false), |
| 4058 |
r"[\x00-\x1F\x7F-\x9F]" |
| 4059 |
); |
| 4060 |
// Test \P{cntrl} with unicode flag |
| 4061 |
assert_eq!( |
| 4062 |
remap_unicode_property_if_necessary(r"\P{cntrl}", true, false), |
| 4063 |
r"[^\x00-\x1F\x7F-\x9F]" |
| 4064 |
); |
| 4065 |
// Test \p{cntrl} without unicode flag |
| 4066 |
assert_eq!( |
| 4067 |
remap_unicode_property_if_necessary(r"\p{cntrl}", false, false), |
| 4068 |
r"[[:cntrl:]]" |
| 4069 |
); |
| 4070 |
// Test \P{cntrl} without unicode flag |
| 4071 |
assert_eq!( |
| 4072 |
remap_unicode_property_if_necessary(r"\P{cntrl}", false, false), |
| 4073 |
r"[^[:cntrl:]]" |
| 4074 |
); |
| 4075 |
|
| 4076 |
// Test \p{graph} with unicode flag |
| 4077 |
assert_eq!( |
| 4078 |
remap_unicode_property_if_necessary(r"\p{graph}", true, false), |
| 4079 |
r"[^\p{White_Space}\p{C}]" |
| 4080 |
); |
| 4081 |
// Test \P{graph} with unicode flag |
| 4082 |
assert_eq!( |
| 4083 |
remap_unicode_property_if_necessary(r"\P{graph}", true, false), |
| 4084 |
r"[\p{White_Space}\p{C}]" |
| 4085 |
); |
| 4086 |
// Test \p{graph} without unicode flag |
| 4087 |
assert_eq!( |
| 4088 |
remap_unicode_property_if_necessary(r"\p{graph}", false, false), |
| 4089 |
r"[[:graph:]]" |
| 4090 |
); |
| 4091 |
// Test \P{graph} without unicode flag |
| 4092 |
assert_eq!( |
| 4093 |
remap_unicode_property_if_necessary(r"\P{graph}", false, false), |
| 4094 |
r"[^[:graph:]]" |
| 4095 |
); |
| 4096 |
|
| 4097 |
// Test \p{print} with unicode flag |
| 4098 |
assert_eq!( |
| 4099 |
remap_unicode_property_if_necessary(r"\p{print}", true, false), |
| 4100 |
r"[^\p{C}\t\n\v\f\r]" |
| 4101 |
); |
| 4102 |
// Test \P{print} with unicode flag |
| 4103 |
assert_eq!( |
| 4104 |
remap_unicode_property_if_necessary(r"\P{print}", true, false), |
| 4105 |
r"[\p{C}\t\n\v\f\r]" |
| 4106 |
); |
| 4107 |
// Test \p{print} without unicode flag |
| 4108 |
assert_eq!( |
| 4109 |
remap_unicode_property_if_necessary(r"\p{print}", false, false), |
| 4110 |
r"[[:print:]]" |
| 4111 |
); |
| 4112 |
// Test \P{print} without unicode flag |
| 4113 |
assert_eq!( |
| 4114 |
remap_unicode_property_if_necessary(r"\P{print}", false, false), |
| 4115 |
r"[^[:print:]]" |
| 4116 |
); |
| 4117 |
// Test \p{cs} and \P{cs} (surrogates, never matches in UTF-8) |
| 4118 |
assert_eq!( |
| 4119 |
remap_unicode_property_if_necessary(r"\p{Cs}", true, false), |
| 4120 |
r"\P{any}" |
| 4121 |
); |
| 4122 |
assert_eq!( |
| 4123 |
remap_unicode_property_if_necessary(r"\P{Cs}", true, false), |
| 4124 |
r"\p{any}" |
| 4125 |
); |
| 4126 |
} |
| 4127 |
|
| 4128 |
#[test] |
| 4129 |
fn remap_unicode_property_if_necessary_inside_class_tests() { |
| 4130 |
// Test \p with unicode flag |
| 4131 |
assert_eq!( |
| 4132 |
remap_unicode_property_if_necessary(r"\p{alnum}", true, true), |
| 4133 |
r"\p{alpha}\p{digit}" |
| 4134 |
); |
| 4135 |
assert_eq!( |
| 4136 |
remap_unicode_property_if_necessary(r"\p{blank}", true, true), |
| 4137 |
r"\p{Zs}\x09" |
| 4138 |
); |
| 4139 |
assert_eq!( |
| 4140 |
remap_unicode_property_if_necessary(r"\p{word}", true, true), |
| 4141 |
r"\w" |
| 4142 |
); |
| 4143 |
assert_eq!( |
| 4144 |
remap_unicode_property_if_necessary(r"\p{Greek}", true, true), |
| 4145 |
r"\p{greek}" |
| 4146 |
); |
| 4147 |
|
| 4148 |
// Test \p without unicode flag |
| 4149 |
assert_eq!( |
| 4150 |
remap_unicode_property_if_necessary(r"\p{alnum}", false, true), |
| 4151 |
r"[:alnum:]" |
| 4152 |
); |
| 4153 |
assert_eq!( |
| 4154 |
remap_unicode_property_if_necessary(r"\p{blank}", false, true), |
| 4155 |
r"\t " |
| 4156 |
); |
| 4157 |
assert_eq!( |
| 4158 |
remap_unicode_property_if_necessary(r"\p{word}", false, true), |
| 4159 |
r"_[:alnum:]" |
| 4160 |
); |
| 4161 |
assert_eq!( |
| 4162 |
remap_unicode_property_if_necessary(r"\p{Greek}", false, true), |
| 4163 |
r"\p{greek}" |
| 4164 |
); |
| 4165 |
|
| 4166 |
// Test \P with unicode flag |
| 4167 |
assert_eq!( |
| 4168 |
remap_unicode_property_if_necessary(r"\P{alnum}", true, true), |
| 4169 |
r"[^\p{alpha}\p{digit}]" |
| 4170 |
); |
| 4171 |
assert_eq!( |
| 4172 |
remap_unicode_property_if_necessary(r"\P{blank}", true, true), |
| 4173 |
r"[^\p{Zs}\x09]" |
| 4174 |
); |
| 4175 |
assert_eq!( |
| 4176 |
remap_unicode_property_if_necessary(r"\P{word}", true, true), |
| 4177 |
r"\W" |
| 4178 |
); |
| 4179 |
assert_eq!( |
| 4180 |
remap_unicode_property_if_necessary(r"\P{Greek}", true, true), |
| 4181 |
r"\P{greek}" |
| 4182 |
); |
| 4183 |
|
| 4184 |
// Test \p{cntrl} inside class with unicode flag |
| 4185 |
assert_eq!( |
| 4186 |
remap_unicode_property_if_necessary(r"\p{cntrl}", true, true), |
| 4187 |
r"\x00-\x1F\x7F-\x9F" |
| 4188 |
); |
| 4189 |
// Test \P{cntrl} inside class with unicode flag |
| 4190 |
assert_eq!( |
| 4191 |
remap_unicode_property_if_necessary(r"\P{cntrl}", true, true), |
| 4192 |
r"[^\x00-\x1F\x7F-\x9F]" |
| 4193 |
); |
| 4194 |
// Test \p{cntrl} inside class without unicode flag |
| 4195 |
assert_eq!( |
| 4196 |
remap_unicode_property_if_necessary(r"\p{cntrl}", false, true), |
| 4197 |
r"[:cntrl:]" |
| 4198 |
); |
| 4199 |
// Test \P{cntrl} inside class without unicode flag |
| 4200 |
assert_eq!( |
| 4201 |
remap_unicode_property_if_necessary(r"\P{cntrl}", false, true), |
| 4202 |
r"[^[:cntrl:]]" |
| 4203 |
); |
| 4204 |
|
| 4205 |
// Test \p{graph} inside class with unicode flag |
| 4206 |
assert_eq!( |
| 4207 |
remap_unicode_property_if_necessary(r"\p{graph}", true, true), |
| 4208 |
r"[^\p{White_Space}\p{C}]" |
| 4209 |
); |
| 4210 |
// Test \P{graph} inside class with unicode flag |
| 4211 |
assert_eq!( |
| 4212 |
remap_unicode_property_if_necessary(r"\P{graph}", true, true), |
| 4213 |
r"[\p{White_Space}\p{C}]" |
| 4214 |
); |
| 4215 |
// Test \p{graph} inside class without unicode flag |
| 4216 |
assert_eq!( |
| 4217 |
remap_unicode_property_if_necessary(r"\p{graph}", false, true), |
| 4218 |
r"[:graph:]" |
| 4219 |
); |
| 4220 |
// Test \P{graph} inside class without unicode flag |
| 4221 |
assert_eq!( |
| 4222 |
remap_unicode_property_if_necessary(r"\P{graph}", false, true), |
| 4223 |
r"[^[:graph:]]" |
| 4224 |
); |
| 4225 |
|
| 4226 |
// Test \p{print} inside class with unicode flag |
| 4227 |
assert_eq!( |
| 4228 |
remap_unicode_property_if_necessary(r"\p{print}", true, true), |
| 4229 |
r"[^\p{C}\t\n\v\f\r]" |
| 4230 |
); |
| 4231 |
// Test \P{print} inside class with unicode flag |
| 4232 |
assert_eq!( |
| 4233 |
remap_unicode_property_if_necessary(r"\P{print}", true, true), |
| 4234 |
r"[\p{C}\t\n\v\f\r]" |
| 4235 |
); |
| 4236 |
// Test \p{print} inside class without unicode flag |
| 4237 |
assert_eq!( |
| 4238 |
remap_unicode_property_if_necessary(r"\p{print}", false, true), |
| 4239 |
r"[:print:]" |
| 4240 |
); |
| 4241 |
// Test \P{print} inside class without unicode flag |
| 4242 |
assert_eq!( |
| 4243 |
remap_unicode_property_if_necessary(r"\P{print}", false, true), |
| 4244 |
r"[^[:print:]]" |
| 4245 |
); |
| 4246 |
|
| 4247 |
// Test \P without unicode flag |
| 4248 |
assert_eq!( |
| 4249 |
remap_unicode_property_if_necessary(r"\P{alnum}", false, true), |
| 4250 |
r"[^[:alnum:]]" |
| 4251 |
); |
| 4252 |
assert_eq!( |
| 4253 |
remap_unicode_property_if_necessary(r"\P{blank}", false, true), |
| 4254 |
r"[^\t ]" |
| 4255 |
); |
| 4256 |
assert_eq!( |
| 4257 |
remap_unicode_property_if_necessary(r"\P{word}", false, true), |
| 4258 |
r"[^_[:alnum:]]" |
| 4259 |
); |
| 4260 |
assert_eq!( |
| 4261 |
remap_unicode_property_if_necessary(r"\P{Greek}", false, true), |
| 4262 |
r"\P{greek}" |
| 4263 |
); |
| 4264 |
} |
| 4265 |
|
| 4266 |
#[test] |
| 4267 |
fn remap_unicode_property_case_insensitive() { |
| 4268 |
// Test case-insensitive conversion for Emoji and other properties |
| 4269 |
assert_eq!( |
| 4270 |
remap_unicode_property_if_necessary(r"\p{Emoji}", true, false), |
| 4271 |
r"\p{emoji}" |
| 4272 |
); |
| 4273 |
assert_eq!( |
| 4274 |
remap_unicode_property_if_necessary(r"\p{EMOJI}", true, false), |
| 4275 |
r"\p{emoji}" |
| 4276 |
); |
| 4277 |
assert_eq!( |
| 4278 |
remap_unicode_property_if_necessary(r"\P{Emoji}", true, false), |
| 4279 |
r"\P{emoji}" |
| 4280 |
); |
| 4281 |
assert_eq!( |
| 4282 |
remap_unicode_property_if_necessary(r"\P{EMOJI}", true, false), |
| 4283 |
r"\P{emoji}" |
| 4284 |
); |
| 4285 |
|
| 4286 |
// Test Word property (both uppercase and lowercase) |
| 4287 |
assert_eq!( |
| 4288 |
remap_unicode_property_if_necessary(r"\p{Word}", true, false), |
| 4289 |
r"\w" |
| 4290 |
); |
| 4291 |
assert_eq!( |
| 4292 |
remap_unicode_property_if_necessary(r"\p{WORD}", true, false), |
| 4293 |
r"\w" |
| 4294 |
); |
| 4295 |
} |
| 4296 |
|
| 4297 |
#[test] |
| 4298 |
fn remap_unicode_property_caret_negation() { |
| 4299 |
// Test \p{^...} syntax (Oniguruma negation inside braces) |
| 4300 |
// \p{^Emoji} should become \P{emoji} |
| 4301 |
assert_eq!( |
| 4302 |
remap_unicode_property_if_necessary(r"\p{^Emoji}", true, false), |
| 4303 |
r"\P{emoji}" |
| 4304 |
); |
| 4305 |
assert_eq!( |
| 4306 |
remap_unicode_property_if_necessary(r"\p{^EMOJI}", true, false), |
| 4307 |
r"\P{emoji}" |
| 4308 |
); |
| 4309 |
|
| 4310 |
// \P{^Word} should become \p{word} which becomes \w |
| 4311 |
assert_eq!( |
| 4312 |
remap_unicode_property_if_necessary(r"\P{^Word}", true, false), |
| 4313 |
r"\w" |
| 4314 |
); |
| 4315 |
assert_eq!( |
| 4316 |
remap_unicode_property_if_necessary(r"\P{^WORD}", true, false), |
| 4317 |
r"\w" |
| 4318 |
); |
| 4319 |
|
| 4320 |
// \p{^Greek} should become \P{greek} |
| 4321 |
assert_eq!( |
| 4322 |
remap_unicode_property_if_necessary(r"\p{^Greek}", true, false), |
| 4323 |
r"\P{greek}" |
| 4324 |
); |
| 4325 |
|
| 4326 |
// \P{^Greek} should become \p{greek} |
| 4327 |
assert_eq!( |
| 4328 |
remap_unicode_property_if_necessary(r"\P{^Greek}", true, false), |
| 4329 |
r"\p{greek}" |
| 4330 |
); |
| 4331 |
} |
| 4332 |
|
| 4333 |
#[test] |
| 4334 |
fn parse_absent_repeater() { |
| 4335 |
assert_eq!( |
| 4336 |
p(r"(?~abc)"), |
| 4337 |
Expr::Absent(Absent::Repeater(Box::new(Expr::Concat(vec![ |
| 4338 |
make_literal("a"), |
| 4339 |
make_literal("b"), |
| 4340 |
make_literal("c"), |
| 4341 |
])))) |
| 4342 |
); |
| 4343 |
} |
| 4344 |
|
| 4345 |
#[test] |
| 4346 |
fn parse_absent_expression() { |
| 4347 |
assert_eq!( |
| 4348 |
p(r"(?~|abc|\d+)"), |
| 4349 |
Expr::Absent(Absent::Expression { |
| 4350 |
absent: Box::new(Expr::Concat(vec![ |
| 4351 |
make_literal("a"), |
| 4352 |
make_literal("b"), |
| 4353 |
make_literal("c"), |
| 4354 |
])), |
| 4355 |
exp: Box::new(Expr::Repeat { |
| 4356 |
child: Box::new(Expr::Delegate { |
| 4357 |
inner: "\\d".to_string(), |
| 4358 |
casei: false, |
| 4359 |
}), |
| 4360 |
lo: 1, |
| 4361 |
hi: usize::MAX, |
| 4362 |
greedy: true |
| 4363 |
}), |
| 4364 |
}) |
| 4365 |
); |
| 4366 |
} |
| 4367 |
|
| 4368 |
#[test] |
| 4369 |
fn parse_absent_stopper() { |
| 4370 |
assert_eq!( |
| 4371 |
p(r"(?~|abc)"), |
| 4372 |
Expr::Absent(Absent::Stopper(Box::new(Expr::Concat(vec![ |
| 4373 |
make_literal("a"), |
| 4374 |
make_literal("b"), |
| 4375 |
make_literal("c"), |
| 4376 |
])))) |
| 4377 |
); |
| 4378 |
} |
| 4379 |
|
| 4380 |
#[test] |
| 4381 |
fn parse_absent_range_clear() { |
| 4382 |
assert_eq!(p(r"(?~|)"), Expr::Absent(Absent::Clear)); |
| 4383 |
} |
| 4384 |
|
| 4385 |
#[test] |
| 4386 |
fn define_group() { |
| 4387 |
assert_eq!( |
| 4388 |
p(r"(?(DEFINE)(?<word>\w+))"), |
| 4389 |
Expr::DefineGroup { |
| 4390 |
definitions: Box::new(make_group(Expr::Repeat { |
| 4391 |
child: Box::new(Expr::Delegate { |
| 4392 |
inner: "\\w".to_string(), |
| 4393 |
casei: false, |
| 4394 |
}), |
| 4395 |
lo: 1, |
| 4396 |
hi: usize::MAX, |
| 4397 |
greedy: true, |
| 4398 |
})), |
| 4399 |
} |
| 4400 |
); |
| 4401 |
} |
| 4402 |
|
| 4403 |
#[test] |
| 4404 |
fn define_group_with_subroutine_call() { |
| 4405 |
assert_eq!( |
| 4406 |
p(r"(?(DEFINE)(?<word>\w+))\g<word>"), |
| 4407 |
Expr::Concat(vec![ |
| 4408 |
Expr::DefineGroup { |
| 4409 |
definitions: Box::new(make_group(Expr::Repeat { |
| 4410 |
child: Box::new(Expr::Delegate { |
| 4411 |
inner: "\\w".to_string(), |
| 4412 |
casei: false, |
| 4413 |
}), |
| 4414 |
lo: 1, |
| 4415 |
hi: usize::MAX, |
| 4416 |
greedy: true, |
| 4417 |
})), |
| 4418 |
}, |
| 4419 |
Expr::SubroutineCall(1), |
| 4420 |
]) |
| 4421 |
); |
| 4422 |
} |
| 4423 |
} |