| 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 |
//! Compilation of regexes to VM. |
| 22 |
|
| 23 |
use alloc::boxed::Box; |
| 24 |
use alloc::format; |
| 25 |
use alloc::string::{String, ToString}; |
| 26 |
#[cfg(feature = "variable-lookbehinds")] |
| 27 |
use alloc::sync::Arc; |
| 28 |
#[cfg(feature = "variable-lookbehinds")] |
| 29 |
use alloc::vec; |
| 30 |
use alloc::vec::Vec; |
| 31 |
use regex_automata::meta::Regex as RaRegex; |
| 32 |
use regex_automata::meta::{Builder as RaBuilder, Config as RaConfig}; |
| 33 |
use regex_automata::nfa::thompson::WhichCaptures; |
| 34 |
#[cfg(feature = "variable-lookbehinds")] |
| 35 |
use regex_automata::util::pool::Pool; |
| 36 |
|
| 37 |
#[cfg(not(feature = "std"))] |
| 38 |
use alloc::collections::BTreeMap as Map; |
| 39 |
#[cfg(feature = "std")] |
| 40 |
use std::collections::HashMap as Map; |
| 41 |
|
| 42 |
use crate::analyze::Info; |
| 43 |
use crate::seek::build_seek_pattern; |
| 44 |
use crate::to_hir::{expr_to_hir, HirCtx}; |
| 45 |
#[cfg(feature = "variable-lookbehinds")] |
| 46 |
use crate::vm::{CachePoolFn, ReverseBackwardsDelegate}; |
| 47 |
use crate::vm::{CaptureGroupRange, CaseiLiteral, CharClassMatcher, Delegate, Insn, Prog, Seek}; |
| 48 |
use crate::LookAround::*; |
| 49 |
use crate::{ |
| 50 |
Absent, BacktrackingControlVerb, BytesMode, CompileError, Error, Expr, LookAround, Result, |
| 51 |
}; |
| 52 |
use regex_syntax::hir::Hir; |
| 53 |
|
| 54 |
/// Maximum recursion depth for subroutine calls (matches Oniguruma's limit) |
| 55 |
pub(crate) const MAX_SUBROUTINE_RECURSION_DEPTH: usize = 19; |
| 56 |
|
| 57 |
// I'm thinking it probably doesn't make a lot of sense having this split |
| 58 |
// out from Compiler. |
| 59 |
struct VMBuilder { |
| 60 |
prog: Vec<Insn>, |
| 61 |
n_saves: usize, |
| 62 |
} |
| 63 |
|
| 64 |
impl VMBuilder { |
| 65 |
fn new(max_group: usize) -> VMBuilder { |
| 66 |
VMBuilder { |
| 67 |
prog: Vec::new(), |
| 68 |
n_saves: max_group * 2, |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
fn build(self, bytes_mode: BytesMode, seek_pattern: String, max_size: usize) -> Prog { |
| 73 |
Prog::new(self.prog, self.n_saves, bytes_mode, seek_pattern, max_size) |
| 74 |
} |
| 75 |
|
| 76 |
fn newsave(&mut self) -> usize { |
| 77 |
let result = self.n_saves; |
| 78 |
self.n_saves += 1; |
| 79 |
result |
| 80 |
} |
| 81 |
|
| 82 |
fn pc(&self) -> usize { |
| 83 |
self.prog.len() |
| 84 |
} |
| 85 |
|
| 86 |
// would "emit" be a better name? |
| 87 |
fn add(&mut self, insn: Insn) { |
| 88 |
self.prog.push(insn); |
| 89 |
} |
| 90 |
|
| 91 |
fn set_jmp_target(&mut self, jmp_pc: usize, target: usize) { |
| 92 |
match self.prog[jmp_pc] { |
| 93 |
Insn::Jmp(ref mut next) => *next = target, |
| 94 |
_ => panic!("mutating instruction other than Jmp"), |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
fn set_split_target(&mut self, split_pc: usize, target: usize, second: bool) { |
| 99 |
match self.prog[split_pc] { |
| 100 |
Insn::Split(_, ref mut y) if second => *y = target, |
| 101 |
Insn::Split(ref mut x, _) => *x = target, |
| 102 |
_ => panic!("mutating instruction other than Split"), |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
fn set_repeat_target(&mut self, repeat_pc: usize, target: usize) { |
| 107 |
match self.prog[repeat_pc] { |
| 108 |
Insn::RepeatGr { ref mut next, .. } |
| 109 |
| Insn::RepeatNg { ref mut next, .. } |
| 110 |
| Insn::RepeatEpsilonGr { ref mut next, .. } |
| 111 |
| Insn::RepeatEpsilonNg { ref mut next, .. } => *next = target, |
| 112 |
_ => panic!("mutating instruction other than Repeat"), |
| 113 |
} |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
struct Compiler<'a> { |
| 118 |
b: VMBuilder, |
| 119 |
options: CompileOptions, |
| 120 |
inside_alternation: bool, |
| 121 |
/// Map from group number to its Info node for subroutine expansion |
| 122 |
group_info_map: Map<usize, &'a Info<'a>>, |
| 123 |
/// Stack tracking currently expanding subroutine calls to detect recursion depth |
| 124 |
subroutine_recursion_stack: Vec<usize>, |
| 125 |
/// Root Info node for handling group 0 subroutine calls |
| 126 |
root_info: &'a Info<'a>, |
| 127 |
/// Delegated engines already built during this compile, keyed by the |
| 128 |
/// delegate pattern string and whether capture slots were compiled in. |
| 129 |
/// Alternations (lookbehind branches especially) often repeat the same |
| 130 |
/// fragment, and building a `meta::Regex` dominates compile time, so |
| 131 |
/// identical fragments share one engine (cloning it is a cheap Arc copy). |
| 132 |
delegate_memo: Map<(String, bool), RaRegex>, |
| 133 |
} |
| 134 |
|
| 135 |
impl<'a> Compiler<'a> { |
| 136 |
fn visit(&mut self, info: &Info<'_>, hard: bool) -> Result<()> { |
| 137 |
if !hard && !info.hard { |
| 138 |
// easy case, delegate entire subexpr |
| 139 |
return self.compile_delegate(info); |
| 140 |
} |
| 141 |
match *info.expr { |
| 142 |
Expr::Empty => (), |
| 143 |
Expr::Literal { ref val, casei } => { |
| 144 |
if !casei { |
| 145 |
self.b.add(Insn::Lit(val.clone())); |
| 146 |
} else { |
| 147 |
self.compile_delegate(info)?; |
| 148 |
} |
| 149 |
} |
| 150 |
Expr::Any { newline: true, .. } => { |
| 151 |
self.b.add(Insn::Any); |
| 152 |
} |
| 153 |
Expr::Any { |
| 154 |
newline: false, |
| 155 |
crlf: true, |
| 156 |
} => { |
| 157 |
self.b.add(Insn::AnyNoCRLF); |
| 158 |
} |
| 159 |
Expr::Any { |
| 160 |
newline: false, |
| 161 |
crlf: false, |
| 162 |
} => { |
| 163 |
self.b.add(Insn::AnyNoNL); |
| 164 |
} |
| 165 |
Expr::GeneralNewline { unicode } => { |
| 166 |
self.compile_general_newline(unicode)?; |
| 167 |
} |
| 168 |
Expr::Concat(_) => { |
| 169 |
self.compile_concat(info, hard)?; |
| 170 |
} |
| 171 |
Expr::Alt(_) => { |
| 172 |
let count = info.children.len(); |
| 173 |
self.compile_alt(count, |compiler, i| compiler.visit(&info.children[i], hard))?; |
| 174 |
} |
| 175 |
Expr::Group(_) => { |
| 176 |
let group = info.start_group(); |
| 177 |
self.b.add(Insn::SaveCaptureGroupStart(group)); |
| 178 |
self.visit(&info.children[0], hard)?; |
| 179 |
self.b.add(Insn::Save(group * 2 + 1)); |
| 180 |
} |
| 181 |
Expr::Repeat { lo, hi, greedy, .. } => { |
| 182 |
self.compile_repeat(info, lo, hi, greedy, hard)?; |
| 183 |
} |
| 184 |
Expr::LookAround(_, la) => { |
| 185 |
self.compile_lookaround(info, la)?; |
| 186 |
} |
| 187 |
Expr::Backref { group, casei } => { |
| 188 |
self.b.add(Insn::Backref { |
| 189 |
slot: group * 2, |
| 190 |
casei, |
| 191 |
// use the pre-computed effective unicode flag (unicode && !Ascii bytes mode) |
| 192 |
unicode: self.options.unicode, |
| 193 |
}); |
| 194 |
} |
| 195 |
Expr::BackrefExistsCondition { |
| 196 |
group, |
| 197 |
relative_recursion_level: None, |
| 198 |
} => { |
| 199 |
self.b.add(Insn::BackrefExistsCondition(group)); |
| 200 |
} |
| 201 |
Expr::BackrefExistsCondition { |
| 202 |
relative_recursion_level: Some(_), |
| 203 |
.. |
| 204 |
} => { |
| 205 |
return Err(Error::CompileError(Box::new( |
| 206 |
CompileError::FeatureNotYetSupported( |
| 207 |
"Backref exists condition with relative recursion level".to_string(), |
| 208 |
), |
| 209 |
))); |
| 210 |
} |
| 211 |
Expr::BacktrackingControlVerb(BacktrackingControlVerb::Fail) => { |
| 212 |
self.b.add(Insn::Fail); |
| 213 |
} |
| 214 |
Expr::BacktrackingControlVerb(_) => { |
| 215 |
return Err(Error::CompileError(Box::new( |
| 216 |
CompileError::FeatureNotYetSupported( |
| 217 |
"Backtracking control verbs other than 'fail'".to_string(), |
| 218 |
), |
| 219 |
))); |
| 220 |
} |
| 221 |
Expr::AtomicGroup(_) => { |
| 222 |
// TODO optimization: atomic insns are not needed if the |
| 223 |
// child doesn't do any backtracking. |
| 224 |
self.b.add(Insn::BeginAtomic); |
| 225 |
self.visit(&info.children[0], false)?; |
| 226 |
self.b.add(Insn::EndAtomic); |
| 227 |
} |
| 228 |
Expr::Delegate { .. } => { |
| 229 |
// TODO: might want to have more specialized impls |
| 230 |
self.compile_delegate(info)?; |
| 231 |
} |
| 232 |
Expr::Assertion(assertion) => { |
| 233 |
self.b.add(Insn::Assertion(assertion)); |
| 234 |
} |
| 235 |
Expr::KeepOut => { |
| 236 |
self.b.add(Insn::Save(0)); |
| 237 |
} |
| 238 |
Expr::ContinueFromPreviousMatchEnd => { |
| 239 |
self.b.add(Insn::ContinueFromPreviousMatchEnd { |
| 240 |
at_start: info.start_group() <= 1 |
| 241 |
&& info.min_pos_in_group == 0 |
| 242 |
&& !self.inside_alternation, |
| 243 |
}); |
| 244 |
} |
| 245 |
Expr::Conditional { .. } => { |
| 246 |
self.compile_conditional( |
| 247 |
|compiler| compiler.visit(&info.children[0], hard), |
| 248 |
|compiler| compiler.visit(&info.children[1], hard), |
| 249 |
|compiler| compiler.visit(&info.children[2], hard), |
| 250 |
)?; |
| 251 |
} |
| 252 |
Expr::SubroutineCall(target_group) => { |
| 253 |
// Check if we're already expanding this specific group (direct/indirect recursion) |
| 254 |
let recursion_count = self |
| 255 |
.subroutine_recursion_stack |
| 256 |
.iter() |
| 257 |
.filter(|&&g| g == target_group) |
| 258 |
.count(); |
| 259 |
if recursion_count >= MAX_SUBROUTINE_RECURSION_DEPTH { |
| 260 |
// Hit recursion limit - don't expand further, effectively making this match fail |
| 261 |
// This matches Oniguruma's behavior of limiting recursion depth |
| 262 |
self.b.add(Insn::Fail); |
| 263 |
return Ok(()); |
| 264 |
} |
| 265 |
|
| 266 |
// Handle group 0 (whole pattern) specially |
| 267 |
let target_info = if target_group == 0 { |
| 268 |
Some(self.root_info) |
| 269 |
} else { |
| 270 |
self.group_info_map.get(&target_group).map(|v| &**v) |
| 271 |
}; |
| 272 |
|
| 273 |
if let Some(target_info) = target_info { |
| 274 |
// Track that we're expanding this subroutine |
| 275 |
self.subroutine_recursion_stack.push(target_group); |
| 276 |
|
| 277 |
// For group 0, visit the entire root info |
| 278 |
// For other groups, visit the child of the Group expression |
| 279 |
if target_group == 0 { |
| 280 |
self.visit(target_info, hard)?; |
| 281 |
} else { |
| 282 |
// Groups should always have at least one child (the group content) |
| 283 |
// If empty, this is an error in the analysis phase |
| 284 |
if target_info.children.is_empty() { |
| 285 |
return Err(Error::CompileError(Box::new( |
| 286 |
CompileError::UnexpectedGeneralError(format!( |
| 287 |
"Subroutine call to empty group {}", |
| 288 |
target_group |
| 289 |
)), |
| 290 |
))); |
| 291 |
} |
| 292 |
self.b.add(Insn::SaveCaptureGroupStart(target_group)); |
| 293 |
self.visit(&target_info.children[0], hard)?; |
| 294 |
self.b.add(Insn::Save(target_group * 2 + 1)); |
| 295 |
} |
| 296 |
|
| 297 |
// Pop the recursion stack |
| 298 |
self.subroutine_recursion_stack.pop(); |
| 299 |
} else { |
| 300 |
// The target group doesn't exist (invalid group reference) |
| 301 |
// This should have been caught by analysis, but be defensive |
| 302 |
return Err(Error::CompileError(Box::new( |
| 303 |
CompileError::SubroutineCallTargetNotFound( |
| 304 |
format!( |
| 305 |
"Invalid subroutine call to non-existent group {}", |
| 306 |
target_group |
| 307 |
), |
| 308 |
0, |
| 309 |
), |
| 310 |
))); |
| 311 |
} |
| 312 |
} |
| 313 |
Expr::Absent(Absent::Repeater(_)) => { |
| 314 |
let child_info = &info.children[0]; |
| 315 |
if child_info.hard { |
| 316 |
// Nested absent operators are not yet supported |
| 317 |
let is_absent = |e: &Expr| matches!(e, Expr::Absent(_)); |
| 318 |
if is_absent(child_info.expr) || child_info.expr.has_descendant(is_absent) { |
| 319 |
return Err(Error::CompileError(Box::new( |
| 320 |
CompileError::FeatureNotYetSupported( |
| 321 |
"Nested absent operators".to_string(), |
| 322 |
), |
| 323 |
))); |
| 324 |
} |
| 325 |
// Expand (?~hard) to (?((?!hard))\O|)* using the VM's conditional machinery |
| 326 |
self.compile_hard_absent_repeater(child_info)?; |
| 327 |
} else { |
| 328 |
// Compile the child expression as a delegate |
| 329 |
let delegate = DelegateBuilder::new(&self.options) |
| 330 |
.push(child_info) |
| 331 |
.build_delegate(&self.options, &mut self.delegate_memo)?; |
| 332 |
|
| 333 |
// Add the Absent instruction |
| 334 |
self.b.add(Insn::AbsentRepeater(delegate)); |
| 335 |
} |
| 336 |
} |
| 337 |
Expr::BackrefWithRelativeRecursionLevel { .. } => unreachable!(), |
| 338 |
Expr::Absent(ref absent) => { |
| 339 |
use crate::Absent::*; |
| 340 |
let error_msg = match absent { |
| 341 |
Repeater(_) => "Absent repeater", |
| 342 |
Expression { .. } => "Absent expression", |
| 343 |
Stopper(_) => "Absent stopper", |
| 344 |
Clear => "Range clear", |
| 345 |
}; |
| 346 |
return Err(Error::CompileError(Box::new( |
| 347 |
CompileError::FeatureNotYetSupported(error_msg.to_string()), |
| 348 |
))); |
| 349 |
} |
| 350 |
Expr::DefineGroup { .. } => { |
| 351 |
// DEFINE groups don't generate any VM instructions themselves. |
| 352 |
// The groups defined inside are available for subroutine calls, |
| 353 |
// but the DEFINE block itself doesn't match anything. |
| 354 |
// Group numbers were already assigned during analysis, and the |
| 355 |
// subroutine calls will inline the appropriate code when invoked. |
| 356 |
} |
| 357 |
Expr::AstNode { .. } => unreachable!("Should have been rejected during analysis"), |
| 358 |
} |
| 359 |
Ok(()) |
| 360 |
} |
| 361 |
|
| 362 |
fn compile_alt<F>(&mut self, count: usize, mut handle_alternative: F) -> Result<()> |
| 363 |
where |
| 364 |
F: FnMut(&mut Compiler, usize) -> Result<()>, |
| 365 |
{ |
| 366 |
let was_inside_alternation = self.inside_alternation; |
| 367 |
self.inside_alternation = true; |
| 368 |
let mut jmps = Vec::new(); |
| 369 |
let mut last_pc = usize::MAX; |
| 370 |
for i in 0..count { |
| 371 |
let has_next = i != count - 1; |
| 372 |
let pc = self.b.pc(); |
| 373 |
if has_next { |
| 374 |
self.b.add(Insn::Split(pc + 1, usize::MAX)); |
| 375 |
} |
| 376 |
if last_pc != usize::MAX { |
| 377 |
self.b.set_split_target(last_pc, pc, true); |
| 378 |
} |
| 379 |
last_pc = pc; |
| 380 |
|
| 381 |
handle_alternative(self, i)?; |
| 382 |
|
| 383 |
if has_next { |
| 384 |
// All except the last branch need to jump over instructions of |
| 385 |
// other branches. The last branch can just continue to the next |
| 386 |
// instruction. |
| 387 |
let pc = self.b.pc(); |
| 388 |
jmps.push(pc); |
| 389 |
self.b.add(Insn::Jmp(0)); |
| 390 |
} |
| 391 |
} |
| 392 |
let next_pc = self.b.pc(); |
| 393 |
for jmp_pc in jmps { |
| 394 |
self.b.set_jmp_target(jmp_pc, next_pc); |
| 395 |
} |
| 396 |
self.inside_alternation = was_inside_alternation; |
| 397 |
Ok(()) |
| 398 |
} |
| 399 |
|
| 400 |
fn compile_conditional<C, T, F>( |
| 401 |
&mut self, |
| 402 |
mut condition: C, |
| 403 |
mut truth: T, |
| 404 |
mut false_branch: F, |
| 405 |
) -> Result<()> |
| 406 |
where |
| 407 |
C: FnMut(&mut Compiler) -> Result<()>, |
| 408 |
T: FnMut(&mut Compiler) -> Result<()>, |
| 409 |
F: FnMut(&mut Compiler) -> Result<()>, |
| 410 |
{ |
| 411 |
// here we use atomic group functionality to be able to remove the program counter |
| 412 |
// relating to the split instruction's second position if the conditional succeeds |
| 413 |
// This is to ensure that if the condition succeeds, but the "true" branch from the |
| 414 |
// conditional fails, that it wouldn't jump to the "false" branch. |
| 415 |
self.b.add(Insn::BeginAtomic); |
| 416 |
|
| 417 |
let was_inside_alternation = self.inside_alternation; |
| 418 |
self.inside_alternation = true; |
| 419 |
|
| 420 |
let split_pc = self.b.pc(); |
| 421 |
// add the split instruction - we will update it's second pc later |
| 422 |
self.b.add(Insn::Split(split_pc + 1, usize::MAX)); |
| 423 |
|
| 424 |
// add the conditional expression |
| 425 |
condition(self)?; |
| 426 |
|
| 427 |
// mark it as successful to remove the state we added as a split earlier |
| 428 |
self.b.add(Insn::EndAtomic); |
| 429 |
|
| 430 |
// add the truth branch |
| 431 |
truth(self)?; |
| 432 |
// add an instruction to jump over the false branch - we will update the jump target later |
| 433 |
let jump_over_false_pc = self.b.pc(); |
| 434 |
self.b.add(Insn::Jmp(0)); |
| 435 |
|
| 436 |
// add the false branch, update the split target |
| 437 |
self.b.set_split_target(split_pc, self.b.pc(), true); |
| 438 |
false_branch(self)?; |
| 439 |
|
| 440 |
// update the jump target for jumping over the false branch |
| 441 |
self.b.set_jmp_target(jump_over_false_pc, self.b.pc()); |
| 442 |
|
| 443 |
self.inside_alternation = was_inside_alternation; |
| 444 |
|
| 445 |
Ok(()) |
| 446 |
} |
| 447 |
|
| 448 |
/// Compile a hard absent repeater `(?~inner)` by expanding it to its equivalent |
| 449 |
/// conditional form: `(?((?!inner))\O|)*` |
| 450 |
/// |
| 451 |
/// This is a greedy loop that: |
| 452 |
/// - When `inner` does not match at the current position: consumes one character (`\O`, |
| 453 |
/// which matches any character including newlines) |
| 454 |
/// - When `inner` matches: consumes nothing and exits the loop |
| 455 |
fn compile_hard_absent_repeater(&mut self, inner: &Info<'_>) -> Result<()> { |
| 456 |
let repeat = self.b.newsave(); |
| 457 |
let check = self.b.newsave(); |
| 458 |
self.b.add(Insn::Save0(repeat)); |
| 459 |
let loop_pc = self.b.pc(); |
| 460 |
self.b.add(Insn::RepeatEpsilonGr { |
| 461 |
lo: 0, |
| 462 |
next: usize::MAX, |
| 463 |
repeat, |
| 464 |
check, |
| 465 |
}); |
| 466 |
|
| 467 |
// Compile the body as: (?((?!inner))\O|) |
| 468 |
// Condition: negative lookahead - succeeds when inner does NOT match |
| 469 |
// Truth branch: consume one character (including newlines) |
| 470 |
// False branch: empty - when inner matches, consume nothing (triggers epsilon exit) |
| 471 |
self.compile_conditional( |
| 472 |
|compiler| compiler.compile_negative_lookaround(inner, LookAheadNeg), |
| 473 |
|compiler| { |
| 474 |
compiler.b.add(Insn::Any); |
| 475 |
Ok(()) |
| 476 |
}, |
| 477 |
|_| Ok(()), |
| 478 |
)?; |
| 479 |
|
| 480 |
self.b.add(Insn::Jmp(loop_pc)); |
| 481 |
let next_pc = self.b.pc(); |
| 482 |
self.b.set_repeat_target(loop_pc, next_pc); |
| 483 |
Ok(()) |
| 484 |
} |
| 485 |
|
| 486 |
fn compile_concat(&mut self, info: &Info<'_>, hard: bool) -> Result<()> { |
| 487 |
// First: determine a prefix which is constant size and not hard. |
| 488 |
let prefix_end = info |
| 489 |
.children |
| 490 |
.iter() |
| 491 |
.take_while(|c| c.const_size && !c.hard) |
| 492 |
.count(); |
| 493 |
|
| 494 |
// If incoming difficulty is not hard, the suffix after the last |
| 495 |
// hard child can be done with NFA. |
| 496 |
let suffix_len = if !hard { |
| 497 |
info.children[prefix_end..] |
| 498 |
.iter() |
| 499 |
.rev() |
| 500 |
.take_while(|c| !c.hard) |
| 501 |
.count() |
| 502 |
} else { |
| 503 |
// Even for hard, we can delegate a const-sized suffix |
| 504 |
info.children[prefix_end..] |
| 505 |
.iter() |
| 506 |
.rev() |
| 507 |
.take_while(|c| c.const_size && !c.hard) |
| 508 |
.count() |
| 509 |
}; |
| 510 |
let suffix_begin = info.children.len() - suffix_len; |
| 511 |
|
| 512 |
self.compile_delegates(&info.children[..prefix_end])?; |
| 513 |
|
| 514 |
for child in info.children[prefix_end..suffix_begin].iter() { |
| 515 |
self.visit(child, true)?; |
| 516 |
} |
| 517 |
|
| 518 |
self.compile_delegates(&info.children[suffix_begin..]) |
| 519 |
} |
| 520 |
|
| 521 |
fn compile_repeat( |
| 522 |
&mut self, |
| 523 |
info: &Info<'_>, |
| 524 |
lo: usize, |
| 525 |
hi: usize, |
| 526 |
greedy: bool, |
| 527 |
hard: bool, |
| 528 |
) -> Result<()> { |
| 529 |
let child = &info.children[0]; |
| 530 |
if lo == 0 && hi == 0 { |
| 531 |
// zero repetition, matches empty string without executing child |
| 532 |
// This can happen with patterns like (abc){0}, which should match but never |
| 533 |
// execute the child expression or its capture groups |
| 534 |
return Ok(()); |
| 535 |
} |
| 536 |
if lo == 0 && hi == 1 { |
| 537 |
// e? |
| 538 |
let pc = self.b.pc(); |
| 539 |
self.b.add(Insn::Split(pc + 1, pc + 1)); |
| 540 |
// TODO: do we want to do an epsilon check here? If we do |
| 541 |
// it here and in Alt, we might be able to make a good |
| 542 |
// bound on stack depth |
| 543 |
self.visit(child, hard)?; |
| 544 |
let next_pc = self.b.pc(); |
| 545 |
self.b.set_split_target(pc, next_pc, greedy); |
| 546 |
return Ok(()); |
| 547 |
} |
| 548 |
let hard = hard | info.hard; |
| 549 |
if hi == usize::MAX && child.min_size == 0 { |
| 550 |
// Use RepeatEpsilon instructions to prevent empty repeat |
| 551 |
let repeat = self.b.newsave(); |
| 552 |
let check = self.b.newsave(); |
| 553 |
self.b.add(Insn::Save0(repeat)); |
| 554 |
let pc = self.b.pc(); |
| 555 |
if greedy { |
| 556 |
self.b.add(Insn::RepeatEpsilonGr { |
| 557 |
lo, |
| 558 |
next: usize::MAX, |
| 559 |
repeat, |
| 560 |
check, |
| 561 |
}); |
| 562 |
} else { |
| 563 |
self.b.add(Insn::RepeatEpsilonNg { |
| 564 |
lo, |
| 565 |
next: usize::MAX, |
| 566 |
repeat, |
| 567 |
check, |
| 568 |
}); |
| 569 |
} |
| 570 |
self.visit(child, hard)?; |
| 571 |
self.b.add(Insn::Jmp(pc)); |
| 572 |
let next_pc = self.b.pc(); |
| 573 |
self.b.set_repeat_target(pc, next_pc); |
| 574 |
} else if lo == 0 && hi == usize::MAX { |
| 575 |
// e* |
| 576 |
let pc = self.b.pc(); |
| 577 |
self.b.add(Insn::Split(pc + 1, pc + 1)); |
| 578 |
self.visit(child, hard)?; |
| 579 |
self.b.add(Insn::Jmp(pc)); |
| 580 |
let next_pc = self.b.pc(); |
| 581 |
self.b.set_split_target(pc, next_pc, greedy); |
| 582 |
} else if lo == 1 && hi == usize::MAX { |
| 583 |
// e+ |
| 584 |
let pc = self.b.pc(); |
| 585 |
self.visit(child, hard)?; |
| 586 |
let next = self.b.pc() + 1; |
| 587 |
let (x, y) = if greedy { (pc, next) } else { (next, pc) }; |
| 588 |
self.b.add(Insn::Split(x, y)); |
| 589 |
} else { |
| 590 |
let repeat = self.b.newsave(); |
| 591 |
self.b.add(Insn::Save0(repeat)); |
| 592 |
let pc = self.b.pc(); |
| 593 |
if greedy { |
| 594 |
self.b.add(Insn::RepeatGr { |
| 595 |
lo, |
| 596 |
hi, |
| 597 |
next: usize::MAX, |
| 598 |
repeat, |
| 599 |
}); |
| 600 |
} else { |
| 601 |
self.b.add(Insn::RepeatNg { |
| 602 |
lo, |
| 603 |
hi, |
| 604 |
next: usize::MAX, |
| 605 |
repeat, |
| 606 |
}); |
| 607 |
} |
| 608 |
self.visit(child, hard)?; |
| 609 |
self.b.add(Insn::Jmp(pc)); |
| 610 |
let next_pc = self.b.pc(); |
| 611 |
self.b.set_repeat_target(pc, next_pc); |
| 612 |
} |
| 613 |
Ok(()) |
| 614 |
} |
| 615 |
|
| 616 |
fn compile_lookaround(&mut self, info: &Info<'_>, la: LookAround) -> Result<()> { |
| 617 |
let inner = &info.children[0]; |
| 618 |
match la { |
| 619 |
LookBehind => { |
| 620 |
if let &Info { |
| 621 |
const_size: false, |
| 622 |
expr: &Expr::Alt(_), |
| 623 |
.. |
| 624 |
} = inner |
| 625 |
{ |
| 626 |
// Make const size by transforming `(?<=a|bb)` to `(?<=a)|(?<=bb)` |
| 627 |
let alternatives = &inner.children; |
| 628 |
self.compile_alt(alternatives.len(), |compiler, i| { |
| 629 |
let alternative = &alternatives[i]; |
| 630 |
compiler.compile_positive_lookaround(alternative, la) |
| 631 |
}) |
| 632 |
} else { |
| 633 |
self.compile_positive_lookaround(inner, la) |
| 634 |
} |
| 635 |
} |
| 636 |
LookBehindNeg => { |
| 637 |
if let &Info { |
| 638 |
const_size: false, |
| 639 |
expr: &Expr::Alt(_), |
| 640 |
.. |
| 641 |
} = inner |
| 642 |
{ |
| 643 |
// Make const size by transforming `(?<!a|bb)` to `(?<!a)(?<!bb)` |
| 644 |
let alternatives = &inner.children; |
| 645 |
for alternative in alternatives { |
| 646 |
self.compile_negative_lookaround(alternative, la)?; |
| 647 |
} |
| 648 |
Ok(()) |
| 649 |
} else { |
| 650 |
self.compile_negative_lookaround(inner, la) |
| 651 |
} |
| 652 |
} |
| 653 |
LookAhead => self.compile_positive_lookaround(inner, la), |
| 654 |
LookAheadNeg => self.compile_negative_lookaround(inner, la), |
| 655 |
} |
| 656 |
} |
| 657 |
|
| 658 |
fn compile_positive_lookaround(&mut self, inner: &Info<'_>, la: LookAround) -> Result<()> { |
| 659 |
let save = self.b.newsave(); |
| 660 |
self.b.add(Insn::Save(save)); |
| 661 |
self.compile_lookaround_inner(inner, la)?; |
| 662 |
self.b.add(Insn::Restore(save)); |
| 663 |
Ok(()) |
| 664 |
} |
| 665 |
|
| 666 |
fn compile_negative_lookaround(&mut self, inner: &Info<'_>, la: LookAround) -> Result<()> { |
| 667 |
let pc = self.b.pc(); |
| 668 |
self.b.add(Insn::Split(pc + 1, usize::MAX)); |
| 669 |
self.compile_lookaround_inner(inner, la)?; |
| 670 |
self.b.add(Insn::FailNegativeLookAround); |
| 671 |
let next_pc = self.b.pc(); |
| 672 |
self.b.set_split_target(pc, next_pc, true); |
| 673 |
Ok(()) |
| 674 |
} |
| 675 |
|
| 676 |
fn compile_lookaround_inner(&mut self, inner: &Info<'_>, la: LookAround) -> Result<()> { |
| 677 |
if la == LookBehind || la == LookBehindNeg { |
| 678 |
if inner.const_size { |
| 679 |
self.b.add(Insn::GoBack(inner.min_size)); |
| 680 |
self.visit(inner, false) |
| 681 |
} else if !inner.hard { |
| 682 |
#[cfg(feature = "variable-lookbehinds")] |
| 683 |
{ |
| 684 |
let mut delegate_builder = DelegateBuilder::new(&self.options); |
| 685 |
delegate_builder.push(inner); |
| 686 |
self.compile_variable_lookbehind(delegate_builder) |
| 687 |
} |
| 688 |
#[cfg(not(feature = "variable-lookbehinds"))] |
| 689 |
{ |
| 690 |
Err(Error::CompileError(Box::new( |
| 691 |
CompileError::VariableLookBehindRequiresFeature, |
| 692 |
))) |
| 693 |
} |
| 694 |
} else { |
| 695 |
// If the variable lookbehind is a Concat expression where all children |
| 696 |
// are either easy or are guaranteed to consume 0 characters, then we can |
| 697 |
// compile it as variable lookbehind without additional goback instructions. |
| 698 |
if let Expr::Concat(_) = inner.expr { |
| 699 |
let can_compile = inner |
| 700 |
.children |
| 701 |
.iter() |
| 702 |
.all(|child| !child.hard || child.const_size); |
| 703 |
|
| 704 |
if can_compile { |
| 705 |
#[cfg(feature = "variable-lookbehinds")] |
| 706 |
{ |
| 707 |
let mut delegate_nodes = vec![]; |
| 708 |
let mut go_back: usize = 0; |
| 709 |
for child in inner.children.iter().rev() { |
| 710 |
if child.hard { |
| 711 |
self.compile_variable_lookbehind_from_concat_nodes( |
| 712 |
&delegate_nodes, |
| 713 |
)?; |
| 714 |
delegate_nodes.clear(); |
| 715 |
|
| 716 |
go_back += child.min_size; |
| 717 |
if go_back > 0 { |
| 718 |
self.b.add(Insn::GoBack(go_back)); |
| 719 |
} |
| 720 |
self.visit(child, false)?; |
| 721 |
go_back = child.min_size; |
| 722 |
} else { |
| 723 |
if go_back > 0 { |
| 724 |
self.b.add(Insn::GoBack(go_back)); |
| 725 |
go_back = 0; |
| 726 |
} |
| 727 |
delegate_nodes.push(child); |
| 728 |
} |
| 729 |
} |
| 730 |
self.compile_variable_lookbehind_from_concat_nodes(&delegate_nodes)?; |
| 731 |
Ok(()) |
| 732 |
} |
| 733 |
#[cfg(not(feature = "variable-lookbehinds"))] |
| 734 |
{ |
| 735 |
Err(Error::CompileError(Box::new( |
| 736 |
CompileError::VariableLookBehindRequiresFeature, |
| 737 |
))) |
| 738 |
} |
| 739 |
} else { |
| 740 |
Err(Error::CompileError(Box::new( |
| 741 |
CompileError::FeatureNotYetSupported( |
| 742 |
"Variable length lookbehinds with fancy features".to_string(), |
| 743 |
), |
| 744 |
))) |
| 745 |
} |
| 746 |
} else { |
| 747 |
// variable sized lookbehinds with fancy features are currently unsupported |
| 748 |
Err(Error::CompileError(Box::new( |
| 749 |
CompileError::FeatureNotYetSupported( |
| 750 |
"Variable length lookbehinds with fancy features".to_string(), |
| 751 |
), |
| 752 |
))) |
| 753 |
} |
| 754 |
} |
| 755 |
} else { |
| 756 |
self.visit(inner, false) |
| 757 |
} |
| 758 |
} |
| 759 |
|
| 760 |
#[cfg(feature = "variable-lookbehinds")] |
| 761 |
fn compile_variable_lookbehind_from_concat_nodes( |
| 762 |
&mut self, |
| 763 |
infos: &Vec<&Info<'_>>, |
| 764 |
) -> Result<()> { |
| 765 |
if infos.is_empty() { |
| 766 |
Ok(()) |
| 767 |
} else { |
| 768 |
let mut delegate_builder = DelegateBuilder::new(&self.options); |
| 769 |
for info in infos.iter().rev() { |
| 770 |
delegate_builder.push(info); |
| 771 |
} |
| 772 |
self.compile_variable_lookbehind(delegate_builder) |
| 773 |
} |
| 774 |
} |
| 775 |
|
| 776 |
#[cfg(feature = "variable-lookbehinds")] |
| 777 |
fn compile_variable_lookbehind(&mut self, delegate_builder: DelegateBuilder) -> Result<()> { |
| 778 |
let pattern = &delegate_builder.re; |
| 779 |
let capture_groups = delegate_builder |
| 780 |
.capture_groups |
| 781 |
.expect("Expected at least one expression"); |
| 782 |
|
| 783 |
// Use reverse matching for variable-sized lookbehinds without fancy features |
| 784 |
use regex_automata::hybrid::dfa; |
| 785 |
use regex_automata::nfa::thompson; |
| 786 |
// Build a reverse DFA for the pattern |
| 787 |
let dfa = match dfa::DFA::builder() |
| 788 |
.configure(dfa::Config::new().unicode_word_boundary(true)) |
| 789 |
.thompson(thompson::Config::new().reverse(true)) |
| 790 |
.build(pattern) |
| 791 |
{ |
| 792 |
Ok(dfa) => Arc::new(dfa), |
| 793 |
Err(e) => { |
| 794 |
return Err(Error::CompileError(Box::new(CompileError::DfaBuildError( |
| 795 |
pattern.to_string(), |
| 796 |
e.to_string(), |
| 797 |
)))) |
| 798 |
} |
| 799 |
}; |
| 800 |
|
| 801 |
let create: CachePoolFn = alloc::boxed::Box::new({ |
| 802 |
let dfa = Arc::clone(&dfa); |
| 803 |
move || dfa.create_cache() |
| 804 |
}); |
| 805 |
let cache_pool = Pool::new(create); |
| 806 |
|
| 807 |
// Build the forward regex for capture group extraction. It is only run |
| 808 |
// anchored (see vm.rs BackwardsDelegate) and exists precisely to report |
| 809 |
// captures, so disable the prefilter but keep all capture groups. |
| 810 |
let forward_regex = if capture_groups.start() != capture_groups.end() { |
| 811 |
Some(compile_inner( |
| 812 |
pattern, |
| 813 |
&self.options, |
| 814 |
DelegateUsage::anchored(true), |
| 815 |
)?) |
| 816 |
} else { |
| 817 |
None |
| 818 |
}; |
| 819 |
|
| 820 |
self.b |
| 821 |
.add(Insn::BackwardsDelegate(ReverseBackwardsDelegate { |
| 822 |
dfa, |
| 823 |
cache_pool, |
| 824 |
pattern: pattern.to_string(), |
| 825 |
capture_group_extraction_inner: forward_regex, |
| 826 |
capture_groups: capture_groups.to_option_if_non_empty(), |
| 827 |
})); |
| 828 |
Ok(()) |
| 829 |
} |
| 830 |
|
| 831 |
fn compile_delegates(&mut self, infos: &[Info<'_>]) -> Result<()> { |
| 832 |
if infos.is_empty() { |
| 833 |
return Ok(()); |
| 834 |
} |
| 835 |
// A batch that is entirely literal compiles to a native literal |
| 836 |
// instruction instead of a delegated engine. Case-sensitive literals |
| 837 |
// become a plain byte-compare `Lit`; batches containing |
| 838 |
// case-insensitive characters become a `LitCasei` (Unicode mode only — |
| 839 |
// see `try_casei_literal`). This keeps each literal branch of an |
| 840 |
// alternation off a per-branch delegated engine, so build cost does not |
| 841 |
// scale with the number of branches. |
| 842 |
if let Some(any_casei) = infos |
| 843 |
.iter() |
| 844 |
.try_fold(false, |any, e| e.is_literal_get_casei().map(|c| any || c)) |
| 845 |
{ |
| 846 |
if !any_casei { |
| 847 |
let mut val = String::new(); |
| 848 |
for info in infos { |
| 849 |
info.push_literal(&mut val); |
| 850 |
} |
| 851 |
self.b.add(Insn::Lit(val)); |
| 852 |
return Ok(()); |
| 853 |
} |
| 854 |
let mut chars = Vec::new(); |
| 855 |
for info in infos { |
| 856 |
info.push_literal_chars(&mut chars); |
| 857 |
} |
| 858 |
if let Some(lit) = self.try_casei_literal(&chars) { |
| 859 |
self.b.add(Insn::LitCasei(lit)); |
| 860 |
return Ok(()); |
| 861 |
} |
| 862 |
} |
| 863 |
|
| 864 |
let mut delegate_builder = DelegateBuilder::new(&self.options); |
| 865 |
for info in infos { |
| 866 |
delegate_builder.push(info); |
| 867 |
} |
| 868 |
// Skip emitting a delegate for an empty regex (e.g. a batch of |
| 869 |
// only DefineGroups), as it would just match the empty string. |
| 870 |
if !delegate_builder.is_empty() { |
| 871 |
self.b |
| 872 |
.add(delegate_builder.build(&self.options, &mut self.delegate_memo)?); |
| 873 |
} |
| 874 |
Ok(()) |
| 875 |
} |
| 876 |
|
| 877 |
fn compile_delegate(&mut self, info: &Info) -> Result<()> { |
| 878 |
self.compile_delegates(core::slice::from_ref(info)) |
| 879 |
} |
| 880 |
|
| 881 |
/// Builds a [`CaseiLiteral`] from `(char, casei)` pairs: each |
| 882 |
/// case-insensitive character contributes its Unicode simple case-fold |
| 883 |
/// class (what a delegated `(?i)` literal matches), each case-sensitive |
| 884 |
/// one a singleton. `None` when the fold semantics wouldn't match a |
| 885 |
/// delegated engine's — non-Unicode syntax folds ASCII-only, and non-UTF-8 |
| 886 |
/// haystacks can't be decoded per codepoint — so the caller falls back to |
| 887 |
/// a delegate. |
| 888 |
fn try_casei_literal(&self, chars: &[(char, bool)]) -> Option<CaseiLiteral> { |
| 889 |
use regex_syntax::hir::{ClassUnicode, ClassUnicodeRange}; |
| 890 |
|
| 891 |
if !self.options.unicode || !matches!(self.options.bytes_mode, BytesMode::Unicode) { |
| 892 |
return None; |
| 893 |
} |
| 894 |
let mut out = Vec::with_capacity(chars.len()); |
| 895 |
for &(c, casei) in chars { |
| 896 |
let ranges: Box<[(char, char)]> = if casei { |
| 897 |
let mut class = ClassUnicode::new([ClassUnicodeRange::new(c, c)]); |
| 898 |
// Errs when regex-syntax was built without its case-folding |
| 899 |
// tables; the delegate fallback handles it the old way. |
| 900 |
class.try_case_fold_simple().ok()?; |
| 901 |
class |
| 902 |
.ranges() |
| 903 |
.iter() |
| 904 |
.map(|r| (r.start(), r.end())) |
| 905 |
.collect() |
| 906 |
} else { |
| 907 |
Box::new([(c, c)]) |
| 908 |
}; |
| 909 |
out.push(ranges); |
| 910 |
} |
| 911 |
Some(CaseiLiteral::new(out.into())) |
| 912 |
} |
| 913 |
|
| 914 |
fn compile_general_newline(&mut self, unicode: bool) -> Result<()> { |
| 915 |
// Compile \R as: try \r\n first, then try single newline chars |
| 916 |
// The entire \R is atomic - once it matches, we don't backtrack |
| 917 |
// This prevents \r\n from backtracking to \r |
| 918 |
|
| 919 |
self.b.add(Insn::BeginAtomic); |
| 920 |
|
| 921 |
// Split: try \r\n first, then single chars |
| 922 |
let split_pc = self.b.pc(); |
| 923 |
self.b.add(Insn::Split(split_pc + 1, usize::MAX)); // Will fix second target later |
| 924 |
|
| 925 |
// First alternative: \r\n |
| 926 |
self.b.add(Insn::Lit("\r\n".to_string())); |
| 927 |
|
| 928 |
// Jump over other alternatives |
| 929 |
let jmp_pc = self.b.pc(); |
| 930 |
self.b.add(Insn::Jmp(usize::MAX)); // Will fix target later |
| 931 |
|
| 932 |
// Second alternative: single newline characters |
| 933 |
let single_newline_char_pc = self.b.pc(); |
| 934 |
self.b |
| 935 |
.set_split_target(split_pc, single_newline_char_pc, true); |
| 936 |
|
| 937 |
// Compile a delegate for matching single newline characters. |
| 938 |
// In Ascii bytes mode, Unicode chars are not allowed in the delegate, |
| 939 |
// so we always use the non-Unicode pattern regardless of the `unicode` flag. |
| 940 |
let use_unicode = unicode && !matches!(self.options.bytes_mode, BytesMode::Ascii); |
| 941 |
let pattern = if use_unicode { |
| 942 |
// Unicode mode: \n, \v, \f, \r, U+0085, U+2028, U+2029 |
| 943 |
"[\n\x0B\x0C\r\u{0085}\u{2028}\u{2029}]" |
| 944 |
} else { |
| 945 |
// Non-Unicode mode: \n, \v, \f, \r |
| 946 |
"[\n\x0B\x0C\r]" |
| 947 |
}; |
| 948 |
|
| 949 |
// This delegate (a single newline character class) is run anchored and |
| 950 |
// has no capture groups fancy-regex reads. Match it natively when possible |
| 951 |
// (skipping engine construction), falling back to a delegate otherwise. |
| 952 |
if let Some(matcher) = try_char_class_matcher(pattern, &self.options) { |
| 953 |
self.b.add(Insn::CharClass(matcher)); |
| 954 |
} else { |
| 955 |
let compiled = compile_inner(pattern, &self.options, DelegateUsage::anchored(false))?; |
| 956 |
self.b.add(Insn::Delegate(Delegate { |
| 957 |
inner: compiled, |
| 958 |
pattern: pattern.to_string(), |
| 959 |
capture_groups: None, |
| 960 |
})); |
| 961 |
} |
| 962 |
|
| 963 |
// Fix the jump target |
| 964 |
let end_atomic_pc = self.b.pc(); |
| 965 |
self.b.add(Insn::EndAtomic); |
| 966 |
|
| 967 |
self.b.set_jmp_target(jmp_pc, end_atomic_pc); |
| 968 |
|
| 969 |
Ok(()) |
| 970 |
} |
| 971 |
} |
| 972 |
|
| 973 |
/// Describes how a delegated regex-automata engine will be searched, so the |
| 974 |
/// builder can skip machinery that wouldn't help for that usage. |
| 975 |
/// |
| 976 |
/// VM `Delegate` instructions are always executed anchored at the current input |
| 977 |
/// position (see `vm::run`), so prefilters — which only accelerate *unanchored* |
| 978 |
/// scans — are pure build-time and memory overhead for them. Likewise, a delegate |
| 979 |
/// whose explicit capture groups fancy-regex never reads doesn't need them |
| 980 |
/// compiled into the NFA. |
| 981 |
#[derive(Clone, Copy)] |
| 982 |
pub(crate) struct DelegateUsage { |
| 983 |
/// True if the engine should spend build time constructing a prefilter. |
| 984 |
/// Only useful for engines that are actually searched unanchored. |
| 985 |
prefilter: bool, |
| 986 |
/// True if explicit capture-group spans must be reported by the engine. |
| 987 |
needs_captures: bool, |
| 988 |
} |
| 989 |
|
| 990 |
impl DelegateUsage { |
| 991 |
/// An engine searched unanchored and expected to report full captures: the |
| 992 |
/// top-level `Wrap` engine and the seek pre-filter. Matches the historical |
| 993 |
/// default (prefilter on, all captures). |
| 994 |
pub(crate) const fn unanchored() -> Self { |
| 995 |
DelegateUsage { |
| 996 |
prefilter: true, |
| 997 |
needs_captures: true, |
| 998 |
} |
| 999 |
} |
| 1000 |
|
| 1001 |
/// An engine that reports full captures but is only ever searched anchored |
| 1002 |
/// in practice, so a prefilter would never be consulted: `Wrap` engines for |
| 1003 |
/// regexes built as members of a `RegexSet`, which the set only runs |
| 1004 |
/// anchored at candidate positions. |
| 1005 |
pub(crate) const fn unanchored_no_prefilter() -> Self { |
| 1006 |
DelegateUsage { |
| 1007 |
prefilter: false, |
| 1008 |
needs_captures: true, |
| 1009 |
} |
| 1010 |
} |
| 1011 |
|
| 1012 |
/// An anchored VM delegate. `needs_captures` says whether fancy-regex reads |
| 1013 |
/// the delegate's explicit capture groups. |
| 1014 |
pub(crate) const fn anchored(needs_captures: bool) -> Self { |
| 1015 |
DelegateUsage { |
| 1016 |
prefilter: false, |
| 1017 |
needs_captures, |
| 1018 |
} |
| 1019 |
} |
| 1020 |
} |
| 1021 |
|
| 1022 |
pub(crate) fn compile_inner( |
| 1023 |
inner_re: &str, |
| 1024 |
options: &CompileOptions, |
| 1025 |
usage: DelegateUsage, |
| 1026 |
) -> Result<RaRegex> { |
| 1027 |
let builder = options_to_rabuilder(options, usage); |
| 1028 |
|
| 1029 |
let re = builder |
| 1030 |
.build(inner_re) |
| 1031 |
.map_err(CompileError::InnerError) |
| 1032 |
.map_err(|e| Error::CompileError(Box::new(e)))?; |
| 1033 |
|
| 1034 |
Ok(re) |
| 1035 |
} |
| 1036 |
|
| 1037 |
/// Like [`compile_inner`], but from an already-built `Hir`, so the engine |
| 1038 |
/// doesn't parse the pattern a second time. The syntax config set by |
| 1039 |
/// `options_to_rabuilder` is ignored on this path — the `Hir` must already |
| 1040 |
/// encode it (see `to_hir`). |
| 1041 |
pub(crate) fn compile_inner_from_hir( |
| 1042 |
hir: ®ex_syntax::hir::Hir, |
| 1043 |
options: &CompileOptions, |
| 1044 |
usage: DelegateUsage, |
| 1045 |
) -> Result<RaRegex> { |
| 1046 |
let builder = options_to_rabuilder(options, usage); |
| 1047 |
|
| 1048 |
let re = builder |
| 1049 |
.build_from_hir(hir) |
| 1050 |
.map_err(CompileError::InnerError) |
| 1051 |
.map_err(|e| Error::CompileError(Box::new(e)))?; |
| 1052 |
|
| 1053 |
Ok(re) |
| 1054 |
} |
| 1055 |
|
| 1056 |
pub(crate) fn options_to_rabuilder(options: &CompileOptions, usage: DelegateUsage) -> RaBuilder { |
| 1057 |
use regex_automata::util::syntax::Config as SyntaxConfig; |
| 1058 |
|
| 1059 |
let mut config = RaConfig::new(); |
| 1060 |
if let Some(limit) = options.delegate_size_limit { |
| 1061 |
config = config.nfa_size_limit(Some(limit)); |
| 1062 |
} |
| 1063 |
if let Some(limit) = options.delegate_dfa_size_limit { |
| 1064 |
config = config.dfa_size_limit(Some(limit)); |
| 1065 |
} |
| 1066 |
if !usage.prefilter { |
| 1067 |
// Anchored searches never consult a prefilter, so don't spend build time |
| 1068 |
// (literal extraction, Aho-Corasick/Teddy tables) or memory constructing one. |
| 1069 |
// |
| 1070 |
// NOTE: we deliberately do *not* disable the lazy-DFA (`hybrid`) / DFA |
| 1071 |
// engines here, even though a VM delegate is only searched anchored. |
| 1072 |
// Doing so lets regex-automata skip building the reverse NFA and roughly |
| 1073 |
// halves per-delegate build time, but benchmarking showed it regresses |
| 1074 |
// *match* performance — the lazy DFA has lower per-search overhead than |
| 1075 |
// the PikeVM, and delegates (especially short char classes) are searched |
| 1076 |
// repeatedly inside the backtracking VM. The reverse-NFA build cost is |
| 1077 |
// therefore coupled to match speed; see the compile benches. |
| 1078 |
config = config.auto_prefilter(false); |
| 1079 |
} |
| 1080 |
if !usage.needs_captures { |
| 1081 |
// We only need to know whether (and where) the overall match is, via |
| 1082 |
// search_half/search; skip compiling explicit capture-group slots. |
| 1083 |
config = config.which_captures(WhichCaptures::Implicit); |
| 1084 |
} |
| 1085 |
|
| 1086 |
let mut builder = RaBuilder::new(); |
| 1087 |
builder.configure(config); |
| 1088 |
// NOTE: our Expr to_str function handles creating the correct pattern string for regex-automata |
| 1089 |
// using the default SyntaxConfig. If we were to set i.e. case sensitivity directly on |
| 1090 |
// the SyntaxConfig here, and the pattern includes the (?-i) flag, then that flag would |
| 1091 |
// effectively be ignored unless to_str would encode the flag for every node, even when it |
| 1092 |
// is the default, which feels too verbose and hurts readability, is more to parse etc. |
| 1093 |
let utf8 = matches!(options.bytes_mode, BytesMode::Unicode); |
| 1094 |
|
| 1095 |
let syntax = SyntaxConfig::new().utf8(utf8).unicode(options.unicode); |
| 1096 |
builder.syntax(syntax); |
| 1097 |
|
| 1098 |
builder |
| 1099 |
} |
| 1100 |
|
| 1101 |
/// Strip the `(?i:` prefix and `)` suffix that `Expr::to_str` wraps around |
| 1102 |
/// case-insensitive delegate expressions. This keeps the stored `CharClassMatcher` |
| 1103 |
/// name readable (e.g. `\w` instead of `(?i:\w)`). |
| 1104 |
fn strip_delegate_flags(s: &str) -> &str { |
| 1105 |
s.strip_prefix("(?i:") |
| 1106 |
.and_then(|s| s.strip_suffix(')')) |
| 1107 |
.unwrap_or(s) |
| 1108 |
} |
| 1109 |
|
| 1110 |
/// Try to compile a delegated fragment to a native [`CharClassMatcher`] instead |
| 1111 |
/// of a regex-automata engine. |
| 1112 |
/// |
| 1113 |
/// Most delegates are a single character class (`\d`, `[a-z]`, ...). Building a |
| 1114 |
/// full `meta::Regex` for each one dominates compile time and memory, and the |
| 1115 |
/// engine is then searched once per character inside the backtracking loop. A |
| 1116 |
/// class matches exactly one codepoint/byte, so we can match it directly. |
| 1117 |
/// |
| 1118 |
/// Returns `None` (so the caller builds an engine instead) when the fragment is |
| 1119 |
/// not exactly one character class, or when the class can't be matched natively |
| 1120 |
/// for the current bytes mode. |
| 1121 |
fn try_char_class_matcher(re: &str, options: &CompileOptions) -> Option<CharClassMatcher> { |
| 1122 |
use regex_syntax::ParserBuilder; |
| 1123 |
|
| 1124 |
// Parse with the same flags `options_to_rabuilder` would hand the engine, so |
| 1125 |
// the resulting class is exactly the set the delegated engine would accept |
| 1126 |
// (same case folding, same Unicode handling). |
| 1127 |
let utf8 = matches!(options.bytes_mode, BytesMode::Unicode); |
| 1128 |
let hir = ParserBuilder::new() |
| 1129 |
.utf8(utf8) |
| 1130 |
.unicode(options.unicode) |
| 1131 |
.build() |
| 1132 |
.parse(re) |
| 1133 |
.ok()?; |
| 1134 |
|
| 1135 |
char_class_matcher_from_hir(&hir, options, Some(strip_delegate_flags(re).to_string())) |
| 1136 |
} |
| 1137 |
|
| 1138 |
/// Build a [`CharClassMatcher`] from an `Hir` that is a single character class, |
| 1139 |
/// or `None` if it isn't one (or can't be matched natively in this bytes mode). |
| 1140 |
fn char_class_matcher_from_hir( |
| 1141 |
hir: &Hir, |
| 1142 |
options: &CompileOptions, |
| 1143 |
name: Option<String>, |
| 1144 |
) -> Option<CharClassMatcher> { |
| 1145 |
use regex_syntax::hir::{Class, HirKind}; |
| 1146 |
|
| 1147 |
match hir.kind() { |
| 1148 |
HirKind::Class(Class::Unicode(cu)) => { |
| 1149 |
// A Unicode class over a possibly-invalid-UTF-8 haystack (UnicodeBytes |
| 1150 |
// mode) is matched by the engine via a UTF-8 automaton; defer to it to |
| 1151 |
// keep those exact semantics. In Unicode mode the haystack is valid |
| 1152 |
// UTF-8, so direct codepoint membership is equivalent. |
| 1153 |
if !matches!(options.bytes_mode, BytesMode::Unicode) { |
| 1154 |
return None; |
| 1155 |
} |
| 1156 |
let ranges = cu.ranges().iter().map(|r| (r.start(), r.end())).collect(); |
| 1157 |
Some(CharClassMatcher::Codepoint { ranges, name }) |
| 1158 |
} |
| 1159 |
HirKind::Class(Class::Bytes(cb)) => { |
| 1160 |
let ranges = cb.ranges().iter().map(|r| (r.start(), r.end())).collect(); |
| 1161 |
Some(CharClassMatcher::Byte { ranges, name }) |
| 1162 |
} |
| 1163 |
_ => None, |
| 1164 |
} |
| 1165 |
} |
| 1166 |
|
| 1167 |
/// Recursively populate the group_info_map with all capture groups in the Info tree |
| 1168 |
pub(crate) fn populate_group_info_map<'a>(map: &mut Map<usize, &'a Info<'a>>, info: &'a Info<'a>) { |
| 1169 |
match info.expr { |
| 1170 |
Expr::Group(_) => { |
| 1171 |
let group = info.start_group(); |
| 1172 |
map.insert(group, info); |
| 1173 |
// Continue recursing into children |
| 1174 |
for child in &info.children { |
| 1175 |
populate_group_info_map(map, child); |
| 1176 |
} |
| 1177 |
} |
| 1178 |
_ => { |
| 1179 |
// Recurse into all children |
| 1180 |
for child in &info.children { |
| 1181 |
populate_group_info_map(map, child); |
| 1182 |
} |
| 1183 |
} |
| 1184 |
} |
| 1185 |
} |
| 1186 |
|
| 1187 |
/// Options for compiling analyzed expressions into a program. |
| 1188 |
#[derive(Clone)] |
| 1189 |
pub struct CompileOptions { |
| 1190 |
/// Whether the regex is anchored (starts matching at the beginning of the input). |
| 1191 |
/// When `false`, a `SplitUnanchored` preamble is emitted to allow matching at any position. |
| 1192 |
pub anchored: bool, |
| 1193 |
/// Whether the regex contains subroutine calls, requiring group info to be pre-populated. |
| 1194 |
pub contains_subroutines: bool, |
| 1195 |
/// Optional filter function for the Seek pre-filter optimization. |
| 1196 |
/// When `Some(f)` and a seek pattern can be derived, `f` is called with the pattern string |
| 1197 |
/// to decide whether it is useful enough to replace the `SplitUnanchored` preamble with a |
| 1198 |
/// `Seek` instruction. When `None`, seek is disabled entirely. |
| 1199 |
pub seek_filter: Option<fn(&str) -> bool>, |
| 1200 |
/// To match Oniguruma behavior where only \z can match at EOF if preceeded by a newline character |
| 1201 |
pub disallow_empty_match_at_eof_after_newline: bool, |
| 1202 |
/// How the VM should advance positions: byte-level (Ascii) vs codepoint-level (Unicode/UnicodeBytes). |
| 1203 |
pub bytes_mode: BytesMode, |
| 1204 |
/// Whether Unicode mode is enabled for the regex. This is the effective value combining |
| 1205 |
/// the unicode flag and bytes_mode: `syntaxc.get_unicode() && !matches!(bytes_mode, BytesMode::Ascii)`. |
| 1206 |
/// It is always `false` in Ascii bytes mode, regardless of the unicode flag. |
| 1207 |
pub unicode: bool, |
| 1208 |
/// Optional size limit in bytes for the NFA of each delegated sub-expression. |
| 1209 |
pub delegate_size_limit: Option<usize>, |
| 1210 |
/// Optional size limit in bytes for the DFA of each delegated sub-expression. |
| 1211 |
pub delegate_dfa_size_limit: Option<usize>, |
| 1212 |
} |
| 1213 |
|
| 1214 |
impl core::fmt::Debug for CompileOptions { |
| 1215 |
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 1216 |
let seek_filter_desc = match self.seek_filter { |
| 1217 |
None => "None", |
| 1218 |
Some(f_ptr) |
| 1219 |
if (f_ptr as *const ()) == (crate::seek::seek_pattern_is_useful as *const ()) => |
| 1220 |
{ |
| 1221 |
"Some(seek_pattern_is_useful)" |
| 1222 |
} |
| 1223 |
Some(_) => "Some(<custom>)", |
| 1224 |
}; |
| 1225 |
f.debug_struct("CompileOptions") |
| 1226 |
.field("anchored", &self.anchored) |
| 1227 |
.field("contains_subroutines", &self.contains_subroutines) |
| 1228 |
.field("seek_filter", &seek_filter_desc) |
| 1229 |
.field( |
| 1230 |
"disallow_empty_match_at_eof_after_newline", |
| 1231 |
&self.disallow_empty_match_at_eof_after_newline, |
| 1232 |
) |
| 1233 |
.field("bytes_mode", &self.bytes_mode) |
| 1234 |
.field("unicode", &self.unicode) |
| 1235 |
.field("delegate_size_limit", &self.delegate_size_limit) |
| 1236 |
.field("delegate_dfa_size_limit", &self.delegate_dfa_size_limit) |
| 1237 |
.finish() |
| 1238 |
} |
| 1239 |
} |
| 1240 |
|
| 1241 |
impl Default for CompileOptions { |
| 1242 |
fn default() -> Self { |
| 1243 |
CompileOptions { |
| 1244 |
anchored: false, |
| 1245 |
contains_subroutines: false, |
| 1246 |
seek_filter: None, |
| 1247 |
disallow_empty_match_at_eof_after_newline: false, |
| 1248 |
bytes_mode: BytesMode::default(), |
| 1249 |
unicode: true, |
| 1250 |
delegate_size_limit: None, |
| 1251 |
delegate_dfa_size_limit: None, |
| 1252 |
} |
| 1253 |
} |
| 1254 |
} |
| 1255 |
|
| 1256 |
/// Compile the analyzed expressions into a program. |
| 1257 |
pub fn compile(info: &Info<'_>, options: CompileOptions) -> Result<Prog> { |
| 1258 |
let bytes_mode = options.bytes_mode; |
| 1259 |
// Pre-populate the group_info_map to support forward references |
| 1260 |
let mut group_info_map = Map::new(); |
| 1261 |
populate_group_info_map(&mut group_info_map, info); |
| 1262 |
|
| 1263 |
let mut c = Compiler { |
| 1264 |
b: VMBuilder::new(info.end_group()), |
| 1265 |
options, |
| 1266 |
inside_alternation: false, |
| 1267 |
group_info_map, |
| 1268 |
subroutine_recursion_stack: Vec::new(), |
| 1269 |
root_info: info, |
| 1270 |
delegate_memo: Map::new(), |
| 1271 |
}; |
| 1272 |
|
| 1273 |
let mut seek_pattern = String::new(); |
| 1274 |
build_seek_pattern(info, &c.group_info_map, 0, &mut seek_pattern, 0); |
| 1275 |
|
| 1276 |
if !c.options.anchored { |
| 1277 |
let mut used_seek = false; |
| 1278 |
if let Some(filter) = c.options.seek_filter { |
| 1279 |
if filter(&seek_pattern) { |
| 1280 |
// The seek engine is searched unanchored to find the next candidate |
| 1281 |
// position, so it keeps its prefilter (the whole point of seeking). |
| 1282 |
if let Ok(inner) = |
| 1283 |
compile_inner(&seek_pattern, &c.options, DelegateUsage::unanchored()) |
| 1284 |
{ |
| 1285 |
c.b.add(Insn::Seek(Seek { |
| 1286 |
inner, |
| 1287 |
pattern: seek_pattern.clone(), |
| 1288 |
})); |
| 1289 |
used_seek = true; |
| 1290 |
} |
| 1291 |
} |
| 1292 |
} |
| 1293 |
|
| 1294 |
// If compilation of the seek pattern fails for any reason, or seeking for this |
| 1295 |
// pattern is disabled, fall back to the standard SplitUnanchored preamble. |
| 1296 |
if !used_seek { |
| 1297 |
// add instructions as if \O*? was used at the start of the expression |
| 1298 |
// so that we bump the haystack index by one when failing to match at the current position |
| 1299 |
let current_pc = c.b.pc(); |
| 1300 |
// we are adding 3 instructions, so the current program counter plus 3 gives us the first real instruction |
| 1301 |
c.b.add(Insn::SplitUnanchored(current_pc + 3, current_pc + 1)); |
| 1302 |
c.b.add(Insn::Any); |
| 1303 |
c.b.add(Insn::Jmp(current_pc)); |
| 1304 |
} |
| 1305 |
} |
| 1306 |
if info.start_group() == 1 { |
| 1307 |
// add implicit capture group 0 begin |
| 1308 |
c.b.add(Insn::Save(0)); |
| 1309 |
} |
| 1310 |
c.visit(info, false)?; |
| 1311 |
if info.start_group() == 1 { |
| 1312 |
// add implicit capture group 0 end |
| 1313 |
c.b.add(Insn::Save(1)); |
| 1314 |
} |
| 1315 |
if c.options.disallow_empty_match_at_eof_after_newline { |
| 1316 |
c.b.add(Insn::RejectEmptyMatchAtEOFFollowingNewline); |
| 1317 |
} |
| 1318 |
c.b.add(Insn::End); |
| 1319 |
Ok(c.b.build(bytes_mode, seek_pattern, info.max_size)) |
| 1320 |
} |
| 1321 |
|
| 1322 |
struct DelegateBuilder { |
| 1323 |
re: String, |
| 1324 |
min_size: usize, |
| 1325 |
const_size: bool, |
| 1326 |
capture_groups: Option<CaptureGroupRange>, |
| 1327 |
/// Hir translations of the pushed fragments, built alongside `re` so the |
| 1328 |
/// engine doesn't have to re-parse the string. `None` once any fragment |
| 1329 |
/// fails to translate; the string path is used instead. |
| 1330 |
hirs: Option<Vec<Hir>>, |
| 1331 |
hir_ctx: HirCtx, |
| 1332 |
} |
| 1333 |
|
| 1334 |
impl DelegateBuilder { |
| 1335 |
fn new(options: &CompileOptions) -> Self { |
| 1336 |
let utf8 = matches!(options.bytes_mode, BytesMode::Unicode); |
| 1337 |
Self { |
| 1338 |
re: String::new(), |
| 1339 |
min_size: 0, |
| 1340 |
const_size: true, |
| 1341 |
capture_groups: None, |
| 1342 |
hirs: Some(Vec::new()), |
| 1343 |
hir_ctx: HirCtx::new(options.unicode, utf8), |
| 1344 |
} |
| 1345 |
} |
| 1346 |
|
| 1347 |
/// Returns true if the regex string built so far is empty. |
| 1348 |
fn is_empty(&self) -> bool { |
| 1349 |
self.re.is_empty() |
| 1350 |
} |
| 1351 |
|
| 1352 |
fn push(&mut self, info: &Info<'_>) -> &mut DelegateBuilder { |
| 1353 |
// TODO: might want to detect case of a group with no captures |
| 1354 |
// inside, so we can run find() instead of captures() |
| 1355 |
|
| 1356 |
self.min_size += info.min_size; |
| 1357 |
self.const_size &= info.const_size; |
| 1358 |
if self.capture_groups.is_none() { |
| 1359 |
self.capture_groups = Some(info.capture_groups); |
| 1360 |
} else { |
| 1361 |
// Update the end_group to the latest |
| 1362 |
self.capture_groups = self |
| 1363 |
.capture_groups |
| 1364 |
.map(|range| CaptureGroupRange(range.start(), info.end_group())); |
| 1365 |
} |
| 1366 |
|
| 1367 |
// Add expression. The precedence argument has to be 1 here to |
| 1368 |
// ensure correct grouping in these cases: |
| 1369 |
// |
| 1370 |
// If we have multiple expressions, we are building a concat. |
| 1371 |
// Without grouping, we'd turn ["a", "b|c"] into "^ab|c". But we |
| 1372 |
// want "^a(?:b|c)". |
| 1373 |
// |
| 1374 |
// Even with a single expression, because we add `^` at the |
| 1375 |
// beginning, we need a group. Otherwise `["a|b"]` would be turned |
| 1376 |
// into `"^a|b"` instead of `"^(?:a|b)"`. |
| 1377 |
info.expr.to_str(&mut self.re, 1); |
| 1378 |
|
| 1379 |
// Track the Hir form alongside the string. Group numbering continues |
| 1380 |
// across fragments (the ctx counter), matching how the parser would |
| 1381 |
// number the concatenated string. |
| 1382 |
if let Some(hirs) = &mut self.hirs { |
| 1383 |
match expr_to_hir(info.expr, &mut self.hir_ctx) { |
| 1384 |
Some(hir) => hirs.push(hir), |
| 1385 |
None => self.hirs = None, |
| 1386 |
} |
| 1387 |
} |
| 1388 |
self |
| 1389 |
} |
| 1390 |
|
| 1391 |
fn build( |
| 1392 |
&mut self, |
| 1393 |
options: &CompileOptions, |
| 1394 |
memo: &mut Map<(String, bool), RaRegex>, |
| 1395 |
) -> Result<Insn> { |
| 1396 |
// A single character class is matched directly, skipping engine |
| 1397 |
// construction entirely (see CharClassMatcher). A class has no capture |
| 1398 |
// groups, so this only applies when none are needed. |
| 1399 |
if self.capture_groups.map_or(false, |r| r.start() == r.end()) { |
| 1400 |
let matcher = match &self.hirs { |
| 1401 |
// A single fragment whose Hir is a class; no parse needed. |
| 1402 |
Some(hirs) if hirs.len() == 1 => char_class_matcher_from_hir( |
| 1403 |
&hirs[0], |
| 1404 |
options, |
| 1405 |
Some(strip_delegate_flags(&self.re).to_string()), |
| 1406 |
), |
| 1407 |
// Multiple fragments can't be a single class. |
| 1408 |
Some(_) => None, |
| 1409 |
// Translation bailed; fall back to parsing the string. |
| 1410 |
None => try_char_class_matcher(&self.re, options), |
| 1411 |
}; |
| 1412 |
if let Some(matcher) = matcher { |
| 1413 |
return Ok(Insn::CharClass(matcher)); |
| 1414 |
} |
| 1415 |
} |
| 1416 |
Ok(Insn::Delegate(self.build_delegate(options, memo)?)) |
| 1417 |
} |
| 1418 |
|
| 1419 |
fn build_delegate( |
| 1420 |
&mut self, |
| 1421 |
options: &CompileOptions, |
| 1422 |
memo: &mut Map<(String, bool), RaRegex>, |
| 1423 |
) -> Result<Delegate> { |
| 1424 |
let capture_groups = self |
| 1425 |
.capture_groups |
| 1426 |
.expect("Expected at least one expression"); |
| 1427 |
|
| 1428 |
// VM delegates are always run anchored. Only compile capture-group slots |
| 1429 |
// when fancy-regex actually reads them (vm.rs uses search_slots when |
| 1430 |
// capture_groups is Some, and the faster search_half otherwise). |
| 1431 |
let capture_groups = capture_groups.to_option_if_non_empty(); |
| 1432 |
let usage = DelegateUsage::anchored(capture_groups.is_some()); |
| 1433 |
// The engine is fully determined by the delegate pattern string plus |
| 1434 |
// whether capture slots are compiled in (options are fixed per compile), |
| 1435 |
// so an identical fragment seen earlier in this compile shares its |
| 1436 |
// engine. Outer group numbering may differ between the two sites; that |
| 1437 |
// lives in `capture_groups` below, not in the engine. |
| 1438 |
let memo_key = (self.re.clone(), capture_groups.is_some()); |
| 1439 |
let compiled = match memo.get(&memo_key) { |
| 1440 |
Some(engine) => engine.clone(), |
| 1441 |
None => { |
| 1442 |
let engine = match self.hirs.take() { |
| 1443 |
Some(hirs) => compile_inner_from_hir(&Hir::concat(hirs), options, usage)?, |
| 1444 |
None => compile_inner(&self.re, options, usage)?, |
| 1445 |
}; |
| 1446 |
memo.insert(memo_key, engine.clone()); |
| 1447 |
engine |
| 1448 |
} |
| 1449 |
}; |
| 1450 |
|
| 1451 |
Ok(Delegate { |
| 1452 |
inner: compiled, |
| 1453 |
pattern: self.re.clone(), |
| 1454 |
capture_groups, |
| 1455 |
}) |
| 1456 |
} |
| 1457 |
} |
| 1458 |
|
| 1459 |
#[cfg(test)] |
| 1460 |
mod tests { |
| 1461 |
use super::*; |
| 1462 |
use crate::analyze::{analyze, AnalyzeContext}; |
| 1463 |
use crate::parse::ExprTree; |
| 1464 |
use crate::vm::Insn::*; |
| 1465 |
|
| 1466 |
use matches::assert_matches; |
| 1467 |
|
| 1468 |
#[cfg_attr(feature = "track_caller", track_caller)] |
| 1469 |
fn assert_compile_error<T, F>(result: crate::Result<T>, check: F) |
| 1470 |
where |
| 1471 |
F: FnOnce(&CompileError) -> bool, |
| 1472 |
{ |
| 1473 |
match result { |
| 1474 |
Err(Error::CompileError(ref e)) if check(e) => {} |
| 1475 |
other => panic!( |
| 1476 |
"expected a matching CompileError, but got: {:?}", |
| 1477 |
other.err() |
| 1478 |
), |
| 1479 |
} |
| 1480 |
} |
| 1481 |
|
| 1482 |
#[test] |
| 1483 |
fn casei_literal_compiles_to_native_insn() { |
| 1484 |
// A case-insensitive literal inside a hard pattern becomes a single |
| 1485 |
// native LitCasei instruction, not a delegated engine. |
| 1486 |
let prog = compile_prog_forced_hard("(?i)abc"); |
| 1487 |
assert_eq!(prog.len(), 2, "prog: {:?}", prog); |
| 1488 |
assert_matches!(prog[0], LitCasei(_)); |
| 1489 |
assert_matches!(prog[1], End); |
| 1490 |
} |
| 1491 |
|
| 1492 |
#[test] |
| 1493 |
fn casei_alternation_branches_compile_to_native_insns() { |
| 1494 |
// A hard element in one branch forces the alternation to compile |
| 1495 |
// branch by branch on the VM (a fully-easy alternation would be |
| 1496 |
// delegated whole). The literal branches must become native LitCasei |
| 1497 |
// instructions instead of one delegated engine each. |
| 1498 |
let prog = compile_prog_forced_hard("(?i)(abort|absent|z(?<=q)z)"); |
| 1499 |
let count = prog |
| 1500 |
.iter() |
| 1501 |
.filter(|insn| matches!(insn, LitCasei(_))) |
| 1502 |
.count(); |
| 1503 |
assert!( |
| 1504 |
count >= 2, |
| 1505 |
"literal branches should compile to LitCasei: {:?}", |
| 1506 |
prog |
| 1507 |
); |
| 1508 |
assert!( |
| 1509 |
prog.iter().all(|insn| !matches!(insn, Insn::Delegate(_))), |
| 1510 |
"no branch should need a forward delegate: {:?}", |
| 1511 |
prog |
| 1512 |
); |
| 1513 |
} |
| 1514 |
|
| 1515 |
#[test] |
| 1516 |
fn jumps_for_alternation() { |
| 1517 |
let prog = compile_prog_forced_hard("a|b|c"); |
| 1518 |
|
| 1519 |
assert_eq!(prog.len(), 8, "prog: {:?}", prog); |
| 1520 |
assert_matches!(prog[0], Split(1, 3)); |
| 1521 |
assert_matches!(prog[1], Lit(ref l) if l == "a"); |
| 1522 |
assert_matches!(prog[2], Jmp(7)); |
| 1523 |
assert_matches!(prog[3], Split(4, 6)); |
| 1524 |
assert_matches!(prog[4], Lit(ref l) if l == "b"); |
| 1525 |
assert_matches!(prog[5], Jmp(7)); |
| 1526 |
assert_matches!(prog[6], Lit(ref l) if l == "c"); |
| 1527 |
assert_matches!(prog[7], End); |
| 1528 |
} |
| 1529 |
|
| 1530 |
#[test] |
| 1531 |
fn look_around_pattern_can_be_delegated() { |
| 1532 |
let prog = compile_prog("(?=ab*)c"); |
| 1533 |
|
| 1534 |
assert_eq!(prog.len(), 5, "prog: {:?}", prog); |
| 1535 |
assert_matches!(prog[0], Save(0)); |
| 1536 |
assert_delegate_insn(&prog[1], "ab*", None); |
| 1537 |
assert_matches!(prog[2], Restore(0)); |
| 1538 |
assert_matches!(prog[3], Lit(ref l) if l == "c"); |
| 1539 |
assert_matches!(prog[4], End); |
| 1540 |
} |
| 1541 |
|
| 1542 |
#[test] |
| 1543 |
fn easy_concat_can_delegate_end() { |
| 1544 |
let prog = compile_prog("(?!x)(?:a|ab)x*"); |
| 1545 |
|
| 1546 |
assert_eq!(prog.len(), 5, "prog: {:?}", prog); |
| 1547 |
assert_matches!(prog[0], Split(1, 3)); |
| 1548 |
assert_matches!(prog[1], Lit(ref l) if l == "x"); |
| 1549 |
assert_matches!(prog[2], FailNegativeLookAround); |
| 1550 |
assert_delegate_insn(&prog[3], "(?:a|ab)x*", None); |
| 1551 |
assert_matches!(prog[4], End); |
| 1552 |
} |
| 1553 |
|
| 1554 |
#[test] |
| 1555 |
fn hard_concat_can_delegate_const_size_end() { |
| 1556 |
let prog = compile_prog("(?:(?!x)(?:a|b)c)x*"); |
| 1557 |
|
| 1558 |
assert_eq!(prog.len(), 6, "prog: {:?}", prog); |
| 1559 |
assert_matches!(prog[0], Split(1, 3)); |
| 1560 |
assert_matches!(prog[1], Lit(ref l) if l == "x"); |
| 1561 |
assert_matches!(prog[2], FailNegativeLookAround); |
| 1562 |
assert_delegate_insn(&prog[3], "(?:a|b)c", None); |
| 1563 |
assert_delegate_insn(&prog[4], "x*", None); |
| 1564 |
assert_matches!(prog[5], End); |
| 1565 |
} |
| 1566 |
|
| 1567 |
#[test] |
| 1568 |
fn hard_concat_can_not_delegate_variable_end() { |
| 1569 |
let prog = compile_prog("(?:(?!x)(?:a|ab))x*"); |
| 1570 |
|
| 1571 |
assert_eq!(prog.len(), 9, "prog: {:?}", prog); |
| 1572 |
assert_matches!(prog[0], Split(1, 3)); |
| 1573 |
assert_matches!(prog[1], Lit(ref l) if l == "x"); |
| 1574 |
assert_matches!(prog[2], FailNegativeLookAround); |
| 1575 |
assert_matches!(prog[3], Split(4, 6)); |
| 1576 |
assert_matches!(prog[4], Lit(ref l) if l == "a"); |
| 1577 |
assert_matches!(prog[5], Jmp(7)); |
| 1578 |
assert_matches!(prog[6], Lit(ref l) if l == "ab"); |
| 1579 |
assert_delegate_insn(&prog[7], "x*", None); |
| 1580 |
assert_matches!(prog[8], End); |
| 1581 |
} |
| 1582 |
|
| 1583 |
#[test] |
| 1584 |
fn conditional_expression_can_be_compiled() { |
| 1585 |
let prog = compile_prog(r"(?(ab)c|d)"); |
| 1586 |
|
| 1587 |
assert_eq!(prog.len(), 8, "prog: {:?}", prog); |
| 1588 |
|
| 1589 |
assert_matches!(prog[0], BeginAtomic); |
| 1590 |
assert_matches!(prog[1], Split(2, 6)); |
| 1591 |
assert_matches!(prog[2], Lit(ref l) if l == "ab"); |
| 1592 |
assert_matches!(prog[3], EndAtomic); |
| 1593 |
assert_matches!(prog[4], Lit(ref l) if l == "c"); |
| 1594 |
assert_matches!(prog[5], Jmp(7)); |
| 1595 |
assert_matches!(prog[6], Lit(ref l) if l == "d"); |
| 1596 |
assert_matches!(prog[7], End); |
| 1597 |
} |
| 1598 |
|
| 1599 |
#[test] |
| 1600 |
fn lazy_any_can_be_compiled_explicit_capture_group_zero() { |
| 1601 |
let prog = compile_prog(r"\O*?((?!a))"); |
| 1602 |
|
| 1603 |
assert_eq!(prog.len(), 9, "prog: {:?}", prog); |
| 1604 |
|
| 1605 |
assert_matches!(prog[0], Split(3, 1)); |
| 1606 |
assert_matches!(prog[1], Any); |
| 1607 |
assert_matches!(prog[2], Jmp(0)); |
| 1608 |
assert_matches!(prog[3], SaveCaptureGroupStart(0)); |
| 1609 |
assert_matches!(prog[4], Split(5, 7)); |
| 1610 |
assert_matches!(prog[5], Lit(ref l) if l == "a"); |
| 1611 |
assert_matches!(prog[6], FailNegativeLookAround); |
| 1612 |
assert_matches!(prog[7], Save(1)); |
| 1613 |
assert_matches!(prog[8], End); |
| 1614 |
} |
| 1615 |
|
| 1616 |
#[test] |
| 1617 |
fn backtracking_control_verb_fail_can_be_compiled() { |
| 1618 |
let prog = compile_prog(r"(*FAIL)"); |
| 1619 |
|
| 1620 |
assert_eq!(prog.len(), 2, "prog: {:?}", prog); |
| 1621 |
|
| 1622 |
assert_matches!(prog[0], Fail); |
| 1623 |
assert_matches!(prog[1], End); |
| 1624 |
} |
| 1625 |
|
| 1626 |
#[test] |
| 1627 |
fn other_backtracking_control_verbs_error() { |
| 1628 |
let tree = Expr::parse_tree(r"(*ACCEPT)").unwrap(); |
| 1629 |
let info = analyze( |
| 1630 |
&tree, |
| 1631 |
AnalyzeContext { |
| 1632 |
explicit_capture_group_0: true, |
| 1633 |
..Default::default() |
| 1634 |
}, |
| 1635 |
) |
| 1636 |
.unwrap(); |
| 1637 |
assert_compile_error( |
| 1638 |
compile( |
| 1639 |
&info, |
| 1640 |
CompileOptions { |
| 1641 |
anchored: true, |
| 1642 |
contains_subroutines: tree.contains_subroutines, |
| 1643 |
..CompileOptions::default() |
| 1644 |
}, |
| 1645 |
), |
| 1646 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1647 |
); |
| 1648 |
|
| 1649 |
let tree = Expr::parse_tree(r"(*COMMIT)").unwrap(); |
| 1650 |
let info = analyze( |
| 1651 |
&tree, |
| 1652 |
AnalyzeContext { |
| 1653 |
explicit_capture_group_0: true, |
| 1654 |
..Default::default() |
| 1655 |
}, |
| 1656 |
) |
| 1657 |
.unwrap(); |
| 1658 |
assert_compile_error( |
| 1659 |
compile( |
| 1660 |
&info, |
| 1661 |
CompileOptions { |
| 1662 |
anchored: true, |
| 1663 |
contains_subroutines: tree.contains_subroutines, |
| 1664 |
..CompileOptions::default() |
| 1665 |
}, |
| 1666 |
), |
| 1667 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1668 |
); |
| 1669 |
|
| 1670 |
let tree = Expr::parse_tree(r"(*SKIP)").unwrap(); |
| 1671 |
let info = analyze( |
| 1672 |
&tree, |
| 1673 |
AnalyzeContext { |
| 1674 |
explicit_capture_group_0: true, |
| 1675 |
..Default::default() |
| 1676 |
}, |
| 1677 |
) |
| 1678 |
.unwrap(); |
| 1679 |
assert_compile_error( |
| 1680 |
compile( |
| 1681 |
&info, |
| 1682 |
CompileOptions { |
| 1683 |
anchored: true, |
| 1684 |
contains_subroutines: tree.contains_subroutines, |
| 1685 |
..CompileOptions::default() |
| 1686 |
}, |
| 1687 |
), |
| 1688 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1689 |
); |
| 1690 |
|
| 1691 |
let tree = Expr::parse_tree(r"(*PRUNE)").unwrap(); |
| 1692 |
let info = analyze( |
| 1693 |
&tree, |
| 1694 |
AnalyzeContext { |
| 1695 |
explicit_capture_group_0: true, |
| 1696 |
..Default::default() |
| 1697 |
}, |
| 1698 |
) |
| 1699 |
.unwrap(); |
| 1700 |
assert_compile_error( |
| 1701 |
compile( |
| 1702 |
&info, |
| 1703 |
CompileOptions { |
| 1704 |
anchored: true, |
| 1705 |
contains_subroutines: tree.contains_subroutines, |
| 1706 |
..CompileOptions::default() |
| 1707 |
}, |
| 1708 |
), |
| 1709 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1710 |
); |
| 1711 |
} |
| 1712 |
|
| 1713 |
#[test] |
| 1714 |
fn backref_exists_condition_with_recursion_level_not_yet_supported() { |
| 1715 |
for pattern in &[ |
| 1716 |
r"(a)(?(1+0)b|c)d", |
| 1717 |
r"(?<n>a)(?(<n+0>)b|c)d", |
| 1718 |
r"(?<n>a)(?('n+0')b|c)d", |
| 1719 |
] { |
| 1720 |
let tree = Expr::parse_tree(pattern).unwrap(); |
| 1721 |
let info = analyze( |
| 1722 |
&tree, |
| 1723 |
AnalyzeContext { |
| 1724 |
explicit_capture_group_0: false, |
| 1725 |
..Default::default() |
| 1726 |
}, |
| 1727 |
) |
| 1728 |
.unwrap(); |
| 1729 |
assert_compile_error( |
| 1730 |
compile( |
| 1731 |
&info, |
| 1732 |
CompileOptions { |
| 1733 |
anchored: true, |
| 1734 |
contains_subroutines: tree.contains_subroutines, |
| 1735 |
..CompileOptions::default() |
| 1736 |
}, |
| 1737 |
), |
| 1738 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1739 |
); |
| 1740 |
} |
| 1741 |
} |
| 1742 |
|
| 1743 |
#[test] |
| 1744 |
#[cfg(not(feature = "variable-lookbehinds"))] |
| 1745 |
fn variable_lookbehind_requires_feature() { |
| 1746 |
// Without the feature flag, variable-length lookbehinds should error |
| 1747 |
let tree = Expr::parse_tree(r"(?<=ab+)x").unwrap(); |
| 1748 |
let info = analyze( |
| 1749 |
&tree, |
| 1750 |
AnalyzeContext { |
| 1751 |
explicit_capture_group_0: true, |
| 1752 |
..Default::default() |
| 1753 |
}, |
| 1754 |
) |
| 1755 |
.unwrap(); |
| 1756 |
assert_compile_error( |
| 1757 |
compile( |
| 1758 |
&info, |
| 1759 |
CompileOptions { |
| 1760 |
anchored: true, |
| 1761 |
contains_subroutines: tree.contains_subroutines, |
| 1762 |
..CompileOptions::default() |
| 1763 |
}, |
| 1764 |
), |
| 1765 |
|e| matches!(e, CompileError::VariableLookBehindRequiresFeature), |
| 1766 |
); |
| 1767 |
|
| 1768 |
let tree = Expr::parse_tree(r"(?<=\bab+)x").unwrap(); |
| 1769 |
let info = analyze( |
| 1770 |
&tree, |
| 1771 |
AnalyzeContext { |
| 1772 |
explicit_capture_group_0: true, |
| 1773 |
..Default::default() |
| 1774 |
}, |
| 1775 |
) |
| 1776 |
.unwrap(); |
| 1777 |
assert_compile_error( |
| 1778 |
compile( |
| 1779 |
&info, |
| 1780 |
CompileOptions { |
| 1781 |
anchored: true, |
| 1782 |
contains_subroutines: tree.contains_subroutines, |
| 1783 |
..CompileOptions::default() |
| 1784 |
}, |
| 1785 |
), |
| 1786 |
|e| matches!(e, CompileError::VariableLookBehindRequiresFeature), |
| 1787 |
); |
| 1788 |
} |
| 1789 |
|
| 1790 |
#[test] |
| 1791 |
#[cfg(feature = "variable-lookbehinds")] |
| 1792 |
fn variable_lookbehind_with_required_feature_no_captures_easy() { |
| 1793 |
let prog = compile_prog(r"(?<=ab+)x"); |
| 1794 |
|
| 1795 |
assert_eq!(prog.len(), 5, "prog: {:?}", prog); |
| 1796 |
|
| 1797 |
assert_matches!(prog[0], Save(0)); |
| 1798 |
assert_matches!(&prog[1], BackwardsDelegate(ReverseBackwardsDelegate { pattern, dfa: _, cache_pool: _, capture_group_extraction_inner: None, capture_groups: None }) if pattern == "ab+"); |
| 1799 |
assert_matches!(prog[2], Restore(0)); |
| 1800 |
assert_matches!(prog[3], Lit(ref l) if l == "x"); |
| 1801 |
assert_matches!(prog[4], End); |
| 1802 |
} |
| 1803 |
|
| 1804 |
#[test] |
| 1805 |
#[cfg(feature = "variable-lookbehinds")] |
| 1806 |
fn variable_lookbehind_with_required_feature_no_captures_hard_const_size_zero_length() { |
| 1807 |
let prog = compile_prog(r"(?<=\bab+)x"); |
| 1808 |
|
| 1809 |
assert_eq!(prog.len(), 6, "prog: {:?}", prog); |
| 1810 |
|
| 1811 |
assert_matches!(prog[0], Save(0)); |
| 1812 |
assert_matches!(&prog[1], BackwardsDelegate(ReverseBackwardsDelegate { pattern, dfa: _, cache_pool: _, capture_group_extraction_inner: None, capture_groups: None }) if pattern == "ab+"); |
| 1813 |
assert_matches!(prog[2], Insn::Assertion(crate::Assertion::WordBoundary)); |
| 1814 |
assert_matches!(prog[3], Restore(0)); |
| 1815 |
assert_matches!(prog[4], Lit(ref l) if l == "x"); |
| 1816 |
assert_matches!(prog[5], End); |
| 1817 |
} |
| 1818 |
|
| 1819 |
#[test] |
| 1820 |
#[cfg(feature = "variable-lookbehinds")] |
| 1821 |
fn variable_lookbehind_with_required_feature_no_captures_hard_const_size_non_zero_length() { |
| 1822 |
let prog = compile_prog(r"((.)b+(?<=\1\1b+)x)"); |
| 1823 |
|
| 1824 |
assert_eq!(prog.len(), 16, "prog: {:?}", prog); |
| 1825 |
|
| 1826 |
assert_matches!(prog[0], SaveCaptureGroupStart(0)); |
| 1827 |
assert_matches!(prog[1], SaveCaptureGroupStart(1)); |
| 1828 |
assert_matches!(prog[2], AnyNoNL); |
| 1829 |
assert_matches!(prog[3], Save(3)); |
| 1830 |
assert_matches!(prog[4], Lit(ref l) if l == "b"); |
| 1831 |
assert_matches!(prog[5], Split(4, 6)); |
| 1832 |
assert_matches!(prog[6], Save(4)); |
| 1833 |
assert_matches!(&prog[7], BackwardsDelegate(ReverseBackwardsDelegate { pattern, dfa: _, cache_pool: _, capture_group_extraction_inner: None, capture_groups: None }) if pattern == "b+"); |
| 1834 |
assert_matches!(prog[8], GoBack(1)); |
| 1835 |
assert_matches!( |
| 1836 |
prog[9], |
| 1837 |
Backref { |
| 1838 |
slot: 2, |
| 1839 |
casei: false, |
| 1840 |
unicode: true, |
| 1841 |
} |
| 1842 |
); |
| 1843 |
assert_matches!(prog[10], GoBack(2)); |
| 1844 |
assert_matches!( |
| 1845 |
prog[11], |
| 1846 |
Backref { |
| 1847 |
slot: 2, |
| 1848 |
casei: false, |
| 1849 |
unicode: true, |
| 1850 |
} |
| 1851 |
); |
| 1852 |
assert_matches!(prog[12], Restore(4)); |
| 1853 |
assert_matches!(prog[13], Lit(ref l) if l == "x"); |
| 1854 |
assert_matches!(prog[14], Save(1)); |
| 1855 |
assert_matches!(prog[15], End); |
| 1856 |
} |
| 1857 |
|
| 1858 |
#[test] |
| 1859 |
#[cfg(feature = "variable-lookbehinds")] |
| 1860 |
fn variable_lookbehind_with_required_feature_captures() { |
| 1861 |
let prog = compile_prog(r"(?<=a(b+))x"); |
| 1862 |
|
| 1863 |
assert_eq!(prog.len(), 5, "prog: {:?}", prog); |
| 1864 |
|
| 1865 |
assert_matches!(prog[0], Save(2)); |
| 1866 |
assert_matches!(&prog[1], BackwardsDelegate(ReverseBackwardsDelegate { pattern, dfa: _, cache_pool: _, capture_group_extraction_inner: ref inner, capture_groups: Some(CaptureGroupRange(0, 1)) }) if pattern == "a(b+)" && inner.is_some()); |
| 1867 |
assert_matches!(prog[2], Restore(2)); |
| 1868 |
assert_matches!(prog[3], Lit(ref l) if l == "x"); |
| 1869 |
assert_matches!(prog[4], End); |
| 1870 |
} |
| 1871 |
|
| 1872 |
#[test] |
| 1873 |
#[cfg(feature = "variable-lookbehinds")] |
| 1874 |
fn variable_lookbehind_with_required_feature_backref_captures() { |
| 1875 |
// currently hard variable lookbehinds are unsupported. |
| 1876 |
// the backref to a capture group inside the variable lookbehind makes the capture group hard |
| 1877 |
let tree = Expr::parse_tree(r"(?<=a(b+))\1").unwrap(); |
| 1878 |
let info = analyze(&tree, AnalyzeContext::default()).unwrap(); |
| 1879 |
assert_compile_error( |
| 1880 |
compile( |
| 1881 |
&info, |
| 1882 |
CompileOptions { |
| 1883 |
anchored: true, |
| 1884 |
contains_subroutines: tree.contains_subroutines, |
| 1885 |
..CompileOptions::default() |
| 1886 |
}, |
| 1887 |
), |
| 1888 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1889 |
); |
| 1890 |
} |
| 1891 |
|
| 1892 |
#[test] |
| 1893 |
fn absent_repeater_with_easy_inner_compiles() { |
| 1894 |
let prog = compile_prog(r"((?~abc))"); |
| 1895 |
|
| 1896 |
assert_eq!(prog.len(), 4, "prog: {:?}", prog); |
| 1897 |
assert_matches!(prog[0], SaveCaptureGroupStart(0)); |
| 1898 |
assert_absent_repeater_insn(&prog[1], "abc", None); |
| 1899 |
assert_matches!(prog[2], Save(1)); |
| 1900 |
assert_matches!(prog[3], End); |
| 1901 |
} |
| 1902 |
|
| 1903 |
#[test] |
| 1904 |
fn absent_repeater_with_hard_inner_compiles() { |
| 1905 |
// A hard absent repeater (?~\1) expands to (?((?!\1))\O|)* |
| 1906 |
// Use explicit_capture_group_0=false so that (\w) = group 1 and \1 refers to it |
| 1907 |
let prog = compile_prog_no_explicit_group0(r"(\w)(?~\1)"); |
| 1908 |
|
| 1909 |
assert_eq!(prog.len(), 20, "prog: {:?}", prog); |
| 1910 |
|
| 1911 |
assert_matches!(prog[0], SplitUnanchored(3, 1)); |
| 1912 |
assert_matches!(prog[1], Any); |
| 1913 |
assert_matches!(prog[2], Jmp(0)); |
| 1914 |
assert_matches!(prog[3], Save(0)); |
| 1915 |
assert_matches!(prog[4], SaveCaptureGroupStart(1)); |
| 1916 |
assert_char_class_insn(&prog[5], r"\w"); |
| 1917 |
assert_matches!(prog[6], Save(3)); |
| 1918 |
assert_matches!(prog[7], Save0(4)); |
| 1919 |
assert_matches!( |
| 1920 |
prog[8], |
| 1921 |
RepeatEpsilonGr { |
| 1922 |
lo: 0, |
| 1923 |
next: 18, |
| 1924 |
repeat: 4, |
| 1925 |
check: 5 |
| 1926 |
} |
| 1927 |
); |
| 1928 |
assert_matches!(prog[9], BeginAtomic); |
| 1929 |
assert_matches!(prog[10], Split(11, 17)); |
| 1930 |
assert_matches!(prog[11], Split(12, 14)); |
| 1931 |
assert_matches!( |
| 1932 |
prog[12], |
| 1933 |
Backref { |
| 1934 |
slot: 2, |
| 1935 |
casei: false, |
| 1936 |
unicode: true, |
| 1937 |
} |
| 1938 |
); |
| 1939 |
assert_matches!(prog[13], FailNegativeLookAround); |
| 1940 |
assert_matches!(prog[14], EndAtomic); |
| 1941 |
assert_matches!(prog[15], Any); |
| 1942 |
assert_matches!(prog[16], Jmp(17)); |
| 1943 |
assert_matches!(prog[17], Jmp(8)); |
| 1944 |
assert_matches!(prog[18], Save(1)); |
| 1945 |
assert_matches!(prog[19], End); |
| 1946 |
} |
| 1947 |
|
| 1948 |
#[test] |
| 1949 |
fn absent_repeater_nested_absent_error() { |
| 1950 |
// Nested absent operators are not yet supported (direct child) |
| 1951 |
let tree = Expr::parse_tree(r"(?~(?~abc))").unwrap(); |
| 1952 |
let info = analyze(&tree, AnalyzeContext::default()).unwrap(); |
| 1953 |
assert_compile_error( |
| 1954 |
compile( |
| 1955 |
&info, |
| 1956 |
CompileOptions { |
| 1957 |
anchored: true, |
| 1958 |
contains_subroutines: tree.contains_subroutines, |
| 1959 |
..CompileOptions::default() |
| 1960 |
}, |
| 1961 |
), |
| 1962 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1963 |
); |
| 1964 |
|
| 1965 |
// Nested absent operators are not yet supported (indirect descendant) |
| 1966 |
let tree = Expr::parse_tree(r"(?~a(?<=b(?~c)))").unwrap(); |
| 1967 |
let info = analyze(&tree, AnalyzeContext::default()).unwrap(); |
| 1968 |
assert_compile_error( |
| 1969 |
compile( |
| 1970 |
&info, |
| 1971 |
CompileOptions { |
| 1972 |
anchored: true, |
| 1973 |
contains_subroutines: tree.contains_subroutines, |
| 1974 |
..CompileOptions::default() |
| 1975 |
}, |
| 1976 |
), |
| 1977 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 1978 |
); |
| 1979 |
} |
| 1980 |
|
| 1981 |
#[test] |
| 1982 |
fn absent_operators_error() { |
| 1983 |
// Test that absent expression returns feature not supported |
| 1984 |
let tree = Expr::parse_tree(r"(?~|abc|\d*)").unwrap(); |
| 1985 |
let info = analyze( |
| 1986 |
&tree, |
| 1987 |
AnalyzeContext { |
| 1988 |
explicit_capture_group_0: true, |
| 1989 |
..Default::default() |
| 1990 |
}, |
| 1991 |
) |
| 1992 |
.unwrap(); |
| 1993 |
assert_compile_error( |
| 1994 |
compile( |
| 1995 |
&info, |
| 1996 |
CompileOptions { |
| 1997 |
anchored: true, |
| 1998 |
contains_subroutines: tree.contains_subroutines, |
| 1999 |
..CompileOptions::default() |
| 2000 |
}, |
| 2001 |
), |
| 2002 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 2003 |
); |
| 2004 |
|
| 2005 |
// Test that absent stopper returns feature not supported |
| 2006 |
let tree = Expr::parse_tree(r"(?~|abc)").unwrap(); |
| 2007 |
let info = analyze( |
| 2008 |
&tree, |
| 2009 |
AnalyzeContext { |
| 2010 |
explicit_capture_group_0: true, |
| 2011 |
..Default::default() |
| 2012 |
}, |
| 2013 |
) |
| 2014 |
.unwrap(); |
| 2015 |
assert_compile_error( |
| 2016 |
compile( |
| 2017 |
&info, |
| 2018 |
CompileOptions { |
| 2019 |
anchored: true, |
| 2020 |
contains_subroutines: tree.contains_subroutines, |
| 2021 |
..CompileOptions::default() |
| 2022 |
}, |
| 2023 |
), |
| 2024 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 2025 |
); |
| 2026 |
|
| 2027 |
// Test that range clear returns feature not supported |
| 2028 |
let tree = Expr::parse_tree(r"(?~|)").unwrap(); |
| 2029 |
let info = analyze( |
| 2030 |
&tree, |
| 2031 |
AnalyzeContext { |
| 2032 |
explicit_capture_group_0: true, |
| 2033 |
..Default::default() |
| 2034 |
}, |
| 2035 |
) |
| 2036 |
.unwrap(); |
| 2037 |
assert_compile_error( |
| 2038 |
compile( |
| 2039 |
&info, |
| 2040 |
CompileOptions { |
| 2041 |
anchored: true, |
| 2042 |
contains_subroutines: tree.contains_subroutines, |
| 2043 |
..CompileOptions::default() |
| 2044 |
}, |
| 2045 |
), |
| 2046 |
|e| matches!(e, CompileError::FeatureNotYetSupported(_)), |
| 2047 |
); |
| 2048 |
} |
| 2049 |
|
| 2050 |
#[test] |
| 2051 |
fn single_delegate_with_capture_groups_can_be_compiled() { |
| 2052 |
let prog = compile_prog(r"(.(b)([^a]+))c"); |
| 2053 |
|
| 2054 |
assert_eq!(prog.len(), 2, "prog: {:?}", prog); |
| 2055 |
assert_delegate_insn(&prog[0], "(.(b)([^a]+))c", Some(CaptureGroupRange(0, 3))); |
| 2056 |
assert_matches!(prog[1], End); |
| 2057 |
} |
| 2058 |
|
| 2059 |
#[test] |
| 2060 |
fn delegated_capture_groups_can_be_compiled() { |
| 2061 |
let prog = compile_prog(r"(.(b)([^a]+)(?!c)(\w))"); |
| 2062 |
|
| 2063 |
assert_eq!(prog.len(), 12, "prog: {:?}", prog); |
| 2064 |
|
| 2065 |
assert_matches!(prog[0], SaveCaptureGroupStart(0)); |
| 2066 |
assert_delegate_insn(&prog[1], ".(b)", Some(CaptureGroupRange(1, 2))); |
| 2067 |
assert_matches!(prog[2], SaveCaptureGroupStart(2)); |
| 2068 |
assert_char_class_insn(&prog[3], "[^a]"); |
| 2069 |
assert_matches!(prog[4], Split(3, 5)); |
| 2070 |
assert_matches!(prog[5], Save(5)); |
| 2071 |
assert_matches!(prog[6], Split(7, 9)); |
| 2072 |
assert_matches!(prog[7], Lit(ref l) if l == "c"); |
| 2073 |
assert_matches!(prog[8], FailNegativeLookAround); |
| 2074 |
assert_delegate_insn(&prog[9], r"(\w)", Some(CaptureGroupRange(3, 4))); |
| 2075 |
assert_matches!(prog[10], Save(1)); |
| 2076 |
assert_matches!(prog[11], End); |
| 2077 |
} |
| 2078 |
|
| 2079 |
#[test] |
| 2080 |
fn subroutine_call_can_be_compiled() { |
| 2081 |
let prog = compile_prog(r"((.)\g<1>)"); |
| 2082 |
|
| 2083 |
assert_eq!(prog.len(), 7, "prog: {:?}", prog); |
| 2084 |
|
| 2085 |
assert_matches!(prog[0], SaveCaptureGroupStart(0)); |
| 2086 |
assert_delegate_insn(&prog[1], "(.)", Some(CaptureGroupRange(1, 2))); |
| 2087 |
assert_matches!(prog[2], SaveCaptureGroupStart(1)); |
| 2088 |
assert_matches!(prog[3], AnyNoNL); |
| 2089 |
assert_matches!(prog[4], Save(3)); |
| 2090 |
assert_matches!(prog[5], Save(1)); |
| 2091 |
assert_matches!(prog[6], End); |
| 2092 |
} |
| 2093 |
|
| 2094 |
#[test] |
| 2095 |
fn forward_reference_subroutine_call_can_be_compiled() { |
| 2096 |
let prog = compile_prog(r"(\g<1>(.))"); |
| 2097 |
|
| 2098 |
assert_eq!(prog.len(), 7, "prog: {:?}", prog); |
| 2099 |
|
| 2100 |
assert_matches!(prog[0], SaveCaptureGroupStart(0)); |
| 2101 |
assert_matches!(prog[1], SaveCaptureGroupStart(1)); |
| 2102 |
assert_matches!(prog[2], AnyNoNL); |
| 2103 |
assert_matches!(prog[3], Save(3)); |
| 2104 |
assert_delegate_insn(&prog[4], "(.)", Some(CaptureGroupRange(1, 2))); |
| 2105 |
assert_matches!(prog[5], Save(1)); |
| 2106 |
assert_matches!(prog[6], End); |
| 2107 |
} |
| 2108 |
|
| 2109 |
#[test] |
| 2110 |
fn define_group_is_a_no_op() { |
| 2111 |
// A DEFINE block is not hard but produces an empty delegate regex, |
| 2112 |
// so compilation skips it entirely — only the End instruction remains. |
| 2113 |
let prog = compile_prog(r"(?(DEFINE)(?<word>\w+))"); |
| 2114 |
|
| 2115 |
assert_eq!(prog.len(), 1, "prog: {:?}", prog); |
| 2116 |
assert_matches!(prog[0], End); |
| 2117 |
} |
| 2118 |
|
| 2119 |
#[test] |
| 2120 |
fn continue_from_prev_match_inside_variable_lookbehind_alt_can_be_compiled() { |
| 2121 |
let prog = compile_prog(r"(?<=\G|\s)\d"); |
| 2122 |
|
| 2123 |
assert_eq!(prog.len(), 12, "prog: {:?}", prog); |
| 2124 |
|
| 2125 |
assert_matches!(prog[0], Split(1, 6)); |
| 2126 |
assert_matches!(prog[1], Save(0)); |
| 2127 |
assert_matches!(prog[2], GoBack(0)); |
| 2128 |
assert_matches!(prog[3], ContinueFromPreviousMatchEnd { at_start: false }); |
| 2129 |
assert_matches!(prog[4], Restore(0)); |
| 2130 |
assert_matches!(prog[5], Jmp(10)); |
| 2131 |
assert_matches!(prog[6], Save(1)); |
| 2132 |
assert_matches!(prog[7], GoBack(1)); |
| 2133 |
assert_char_class_insn(&prog[8], r"\s"); |
| 2134 |
assert_matches!(prog[9], Restore(1)); |
| 2135 |
assert_char_class_insn(&prog[10], r"\d"); |
| 2136 |
assert_matches!(prog[11], End); |
| 2137 |
} |
| 2138 |
|
| 2139 |
#[test] |
| 2140 |
fn continue_from_prev_match_inside_alt_can_be_compiled() { |
| 2141 |
let prog = compile_prog(r"(?:\G|\s)\d"); |
| 2142 |
|
| 2143 |
assert_eq!(prog.len(), 6, "prog: {:?}", prog); |
| 2144 |
|
| 2145 |
assert_matches!(prog[0], Split(1, 3)); |
| 2146 |
assert_matches!(prog[1], ContinueFromPreviousMatchEnd { at_start: false }); |
| 2147 |
assert_matches!(prog[2], Jmp(4)); |
| 2148 |
assert_char_class_insn(&prog[3], r"\s"); |
| 2149 |
assert_char_class_insn(&prog[4], r"\d"); |
| 2150 |
assert_matches!(prog[5], End); |
| 2151 |
} |
| 2152 |
|
| 2153 |
#[test] |
| 2154 |
fn continue_from_prev_match_first_instruction_can_be_compiled() { |
| 2155 |
let prog = compile_prog(r"\G\s\d"); |
| 2156 |
|
| 2157 |
assert_eq!(prog.len(), 3, "prog: {:?}", prog); |
| 2158 |
|
| 2159 |
assert_matches!(prog[0], ContinueFromPreviousMatchEnd { at_start: true }); |
| 2160 |
assert_delegate_insn(&prog[1], r"\s\d", None); |
| 2161 |
assert_matches!(prog[2], End); |
| 2162 |
|
| 2163 |
let prog = compile_prog(r"^\G\s\d"); |
| 2164 |
|
| 2165 |
assert_eq!(prog.len(), 4, "prog: {:?}", prog); |
| 2166 |
|
| 2167 |
assert_matches!(prog[1], ContinueFromPreviousMatchEnd { at_start: true }); |
| 2168 |
assert_delegate_insn(&prog[2], r"\s\d", None); |
| 2169 |
assert_matches!(prog[3], End); |
| 2170 |
} |
| 2171 |
|
| 2172 |
#[test] |
| 2173 |
fn continue_from_prev_match_not_first_instruction_can_be_compiled() { |
| 2174 |
let prog = compile_prog(r"\w\G\s\d"); |
| 2175 |
|
| 2176 |
assert_eq!(prog.len(), 4, "prog: {:?}", prog); |
| 2177 |
|
| 2178 |
assert_char_class_insn(&prog[0], r"\w"); |
| 2179 |
assert_matches!(prog[1], ContinueFromPreviousMatchEnd { at_start: false }); |
| 2180 |
assert_delegate_insn(&prog[2], r"\s\d", None); |
| 2181 |
assert_matches!(prog[3], End); |
| 2182 |
} |
| 2183 |
|
| 2184 |
#[test] |
| 2185 |
fn continue_from_prev_match_inside_conditional_can_be_compiled() { |
| 2186 |
let prog = compile_prog(r"(?(\G)\s\d|$)"); |
| 2187 |
|
| 2188 |
assert_eq!(prog.len(), 8, "prog: {:?}", prog); |
| 2189 |
|
| 2190 |
assert_matches!(prog[0], BeginAtomic); |
| 2191 |
assert_matches!(prog[1], Split(2, 6)); |
| 2192 |
assert_matches!(prog[2], ContinueFromPreviousMatchEnd { at_start: false }); |
| 2193 |
assert_matches!(prog[3], EndAtomic); |
| 2194 |
assert_delegate_insn(&prog[4], r"\s\d", None); |
| 2195 |
assert_matches!(prog[5], Jmp(7)); |
| 2196 |
assert_delegate_insn(&prog[6], r"$", None); |
| 2197 |
assert_matches!(prog[7], End); |
| 2198 |
} |
| 2199 |
|
| 2200 |
fn compile_prog(re: &str) -> Vec<Insn> { |
| 2201 |
compile_prog_with( |
| 2202 |
re, |
| 2203 |
AnalyzeContext { |
| 2204 |
explicit_capture_group_0: true, |
| 2205 |
..Default::default() |
| 2206 |
}, |
| 2207 |
|info, tree| { |
| 2208 |
compile( |
| 2209 |
info, |
| 2210 |
CompileOptions { |
| 2211 |
anchored: true, |
| 2212 |
contains_subroutines: tree.contains_subroutines, |
| 2213 |
..CompileOptions::default() |
| 2214 |
}, |
| 2215 |
) |
| 2216 |
.unwrap() |
| 2217 |
.body |
| 2218 |
}, |
| 2219 |
) |
| 2220 |
} |
| 2221 |
|
| 2222 |
fn compile_prog_no_explicit_group0(re: &str) -> Vec<Insn> { |
| 2223 |
compile_prog_with(re, AnalyzeContext::default(), |info, tree| { |
| 2224 |
compile( |
| 2225 |
info, |
| 2226 |
CompileOptions { |
| 2227 |
anchored: false, |
| 2228 |
contains_subroutines: tree.contains_subroutines, |
| 2229 |
..CompileOptions::default() |
| 2230 |
}, |
| 2231 |
) |
| 2232 |
.unwrap() |
| 2233 |
.body |
| 2234 |
}) |
| 2235 |
} |
| 2236 |
|
| 2237 |
fn compile_prog_forced_hard(re: &str) -> Vec<Insn> { |
| 2238 |
compile_prog_with( |
| 2239 |
re, |
| 2240 |
AnalyzeContext { |
| 2241 |
explicit_capture_group_0: true, |
| 2242 |
..Default::default() |
| 2243 |
}, |
| 2244 |
|info, tree| { |
| 2245 |
info.hard = true; |
| 2246 |
compile( |
| 2247 |
info, |
| 2248 |
CompileOptions { |
| 2249 |
anchored: true, |
| 2250 |
contains_subroutines: tree.contains_subroutines, |
| 2251 |
..CompileOptions::default() |
| 2252 |
}, |
| 2253 |
) |
| 2254 |
.unwrap() |
| 2255 |
.body |
| 2256 |
}, |
| 2257 |
) |
| 2258 |
} |
| 2259 |
|
| 2260 |
fn compile_prog_with<F>(re: &str, analyze_context: AnalyzeContext, compile_fn: F) -> Vec<Insn> |
| 2261 |
where |
| 2262 |
F: FnOnce(&mut Info<'_>, &ExprTree) -> Vec<Insn>, |
| 2263 |
{ |
| 2264 |
let tree = Expr::parse_tree(re).unwrap(); |
| 2265 |
let mut info = analyze(&tree, analyze_context).unwrap(); |
| 2266 |
compile_fn(&mut info, &tree) |
| 2267 |
} |
| 2268 |
|
| 2269 |
fn assert_delegate_insn(insn: &Insn, re: &str, captures: Option<CaptureGroupRange>) { |
| 2270 |
match insn { |
| 2271 |
Insn::Delegate(delegate) => assert_delegate(delegate, re, captures), |
| 2272 |
_ => { |
| 2273 |
panic!("Expected Insn::Delegate but was {:#?}", insn); |
| 2274 |
} |
| 2275 |
} |
| 2276 |
} |
| 2277 |
|
| 2278 |
/// Assert that `insn` is a native `CharClass` matching the single character |
| 2279 |
/// class `re` (compiled with default options, matching `compile_prog`). |
| 2280 |
fn assert_char_class_insn(insn: &Insn, re: &str) { |
| 2281 |
let expected = try_char_class_matcher(re, &CompileOptions::default()) |
| 2282 |
.unwrap_or_else(|| panic!("test re {:?} is not a single char class", re)); |
| 2283 |
match insn { |
| 2284 |
Insn::CharClass(matcher) => assert_eq!( |
| 2285 |
matcher, &expected, |
| 2286 |
"char class mismatch for {:?}: {:#?}", |
| 2287 |
re, matcher |
| 2288 |
), |
| 2289 |
_ => panic!("Expected Insn::CharClass but was {:#?}", insn), |
| 2290 |
} |
| 2291 |
} |
| 2292 |
|
| 2293 |
fn assert_absent_repeater_insn(insn: &Insn, re: &str, captures: Option<CaptureGroupRange>) { |
| 2294 |
match insn { |
| 2295 |
Insn::AbsentRepeater(delegate) => assert_delegate(delegate, re, captures), |
| 2296 |
_ => { |
| 2297 |
panic!("Expected Insn::AbsentRepeater but was {:#?}", insn); |
| 2298 |
} |
| 2299 |
} |
| 2300 |
} |
| 2301 |
|
| 2302 |
fn assert_delegate( |
| 2303 |
delegate: &crate::vm::Delegate, |
| 2304 |
re: &str, |
| 2305 |
captures: Option<CaptureGroupRange>, |
| 2306 |
) { |
| 2307 |
assert_eq!(delegate.pattern, re); |
| 2308 |
assert_eq!(captures, delegate.capture_groups); |
| 2309 |
} |
| 2310 |
} |