diff options
| author | nsfisis <nsfisis@gmail.com> | 2026-08-18 01:57:02 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2026-08-18 01:57:02 +0900 |
| commit | 34c74255d781ad0a0bf7cc5ad4ec1761bef61e04 (patch) | |
| tree | 6a4c9e11a0d8e98dccf72a5857db73e74722489b | |
| parent | 844097edf44bf1424d28e2d5fbefda90c1c8f46c (diff) | |
| download | php-shirabe-34c74255d781ad0a0bf7cc5ad4ec1761bef61e04.tar.gz php-shirabe-34c74255d781ad0a0bf7cc5ad4ec1761bef61e04.tar.zst php-shirabe-34c74255d781ad0a0bf7cc5ad4ec1761bef61e04.zip | |
refactor(pcre): drop the two bespoke isMatch variants
is_match_named and is_match_with_indexed_captures reshaped a match into
a name-keyed map or a number-positioned vec, each allocating a String
per group up front for callers that then read one or two of them. Every
one of the eleven call sites ports a plain Preg::isMatch in PHP, so they
now call is_match3 and reach for the group they want through
get(&CaptureKey::ByIndex(N)) / get(&CaptureKey::ByName(..)), the same
way the rest of the tree already reads a match.
Falling out of that: PregNamedGroups existed only to type the first
variant; PregMatches::iter() only to build both; and PregMatches::pattern
only to give iter() the capture names. PregMatches is now a plain
wrapper over regex::Captures, so preg_replace_callback no longer clones
the resolved pattern for every match, and preg_match_map! is internal to
the shim again.
SvnDriver::get_file_content and get_change_date recover the flat
`isMatch(..) && $match[2] !== null` condition the PHP has, which the vec
shape had forced into a nested if.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
| -rw-r--r-- | crates/shirabe-pcre/src/preg.rs | 38 | ||||
| -rw-r--r-- | crates/shirabe-php-shim/src/preg.rs | 54 | ||||
| -rw-r--r-- | crates/shirabe/src/command/fund_command.rs | 10 | ||||
| -rw-r--r-- | crates/shirabe/src/command/update_command.rs | 14 | ||||
| -rw-r--r-- | crates/shirabe/src/installer/binary_installer.rs | 11 | ||||
| -rw-r--r-- | crates/shirabe/src/json/json_manipulator.rs | 43 | ||||
| -rw-r--r-- | crates/shirabe/src/package/version/version_guesser.rs | 16 | ||||
| -rw-r--r-- | crates/shirabe/src/repository/vcs/svn_driver.rs | 34 | ||||
| -rw-r--r-- | crates/shirabe/src/util/hg.rs | 54 |
9 files changed, 121 insertions, 153 deletions
diff --git a/crates/shirabe-pcre/src/preg.rs b/crates/shirabe-pcre/src/preg.rs index 491e5371..753a4678 100644 --- a/crates/shirabe-pcre/src/preg.rs +++ b/crates/shirabe-pcre/src/preg.rs @@ -13,15 +13,10 @@ pub use shirabe_php_shim::{CaptureKey, PregMatches, PregMatchesAll, PregMatchesAllWithOffsets}; use shirabe_php_shim::{ - PregPattern, preg_grep, preg_match_all_offset_capture, preg_match_all2, preg_match_map, - preg_match2, preg_replace_callback, preg_replace2, + PregPattern, preg_grep, preg_match_all_offset_capture, preg_match_all2, preg_match2, + preg_replace_callback, preg_replace2, }; -preg_match_map! { - /// The named capture groups of a single match, keyed by group name alone. - pub struct PregNamedGroups(String => String); -} - #[derive(Debug)] pub struct Preg; @@ -109,35 +104,6 @@ impl Preg { Self::match4(pattern, subject, offset) } - pub fn is_match_named(pattern: impl PregPattern, subject: &str) -> Option<PregNamedGroups> { - Some( - preg_match2(pattern, subject, 0)? - .iter() - .filter_map(|(key, value)| match (key, value) { - (CaptureKey::ByName(name), Some(value)) => Some((name, value.to_string())), - _ => None, - }) - .collect(), - ) - } - - /// `is_match3` with the groups positioned by number rather than keyed, for callers that only - /// read numbered groups. Index 0 is the full match; an unmatched group is `None`. - pub fn is_match_with_indexed_captures( - pattern: impl PregPattern, - subject: &str, - ) -> Option<Vec<Option<String>>> { - Some( - preg_match2(pattern, subject, 0)? - .iter() - .filter_map(|(key, value)| match key { - CaptureKey::ByIndex(_) => Some(value.map(str::to_string)), - CaptureKey::ByName(_) => None, - }) - .collect(), - ) - } - pub fn is_match_all(pattern: impl PregPattern, subject: &str) -> PregMatchesAll { Self::match_all2(pattern, subject) } diff --git a/crates/shirabe-php-shim/src/preg.rs b/crates/shirabe-php-shim/src/preg.rs index 74b7f12d..2686bb59 100644 --- a/crates/shirabe-php-shim/src/preg.rs +++ b/crates/shirabe-php-shim/src/preg.rs @@ -8,8 +8,7 @@ pub enum CaptureKey { } /// Defines a newtype over `IndexMap` for one of the `$matches` shapes the `preg_*` functions fill -/// in. Also used by `shirabe_pcre` for the shapes `Composer\Pcre\Preg` adds on top. -#[macro_export] +/// in. macro_rules! preg_match_map { ($(#[$attr:meta])* $vis:vis struct $name:ident($key:ty => $value:ty);) => { $(#[$attr])* @@ -58,18 +57,17 @@ macro_rules! preg_match_map { }; } -/// A single match's `$matches`: the `regex::Captures` the search produced, held alongside the -/// pattern that produced it so groups can be read by both their named and their numbered form. -/// `'h` is the lifetime of the searched subject, which the group values borrow from. +/// A single match's `$matches`: the `regex::Captures` the search produced, read by either the named +/// or the numbered form of a capture group. `'h` is the lifetime of the searched subject, which the +/// group values borrow from. #[derive(Debug)] pub struct PregMatches<'h> { - pattern: ResolvedPattern, caps: regex::Captures<'h>, } impl<'h> PregMatches<'h> { - fn new(pattern: ResolvedPattern, caps: regex::Captures<'h>) -> Self { - Self { pattern, caps } + fn new(caps: regex::Captures<'h>) -> Self { + Self { caps } } /// The value of the group `key` names, or `None` if that group did not participate in the @@ -82,20 +80,6 @@ impl<'h> PregMatches<'h> { }; group.map(|group| group.as_str()) } - - /// Every capture group under both its named and its numbered key (the name preceding its - /// number), in the order PHP fills `$matches` in. - pub fn iter(&self) -> impl Iterator<Item = (CaptureKey, Option<&'h str>)> + '_ { - let (re, _anchored) = self.pattern.parts(); - re.capture_names() - .enumerate() - .flat_map(move |(index, name)| { - let value = self.caps.get(index).map(|group| group.as_str()); - name.map(|name| (CaptureKey::ByName(name.to_string()), value)) - .into_iter() - .chain(std::iter::once((CaptureKey::ByIndex(index), value))) - }) - } } preg_match_map! { @@ -169,20 +153,18 @@ pub fn preg_match2<'h>( offset: usize, ) -> Option<PregMatches<'h>> { let __resolved = pattern.resolve(); - let caps = { - let (re, anchored) = __resolved.parts(); - // An anchored (`A`) pattern must match starting exactly at `offset`; the `regex` crate - // cannot anchor a `captures_at` search, so search the sub-slice beginning at `offset` and - // require the match to start at its head. - if anchored { - re.captures(&subject[offset..]) - .filter(|c| c.get(0).map(|m| m.start()) == Some(0)) - } else { - re.captures_at(subject, offset) - } + let (re, anchored) = __resolved.parts(); + // An anchored (`A`) pattern must match starting exactly at `offset`; the `regex` crate cannot + // anchor a `captures_at` search, so search the sub-slice beginning at `offset` and require the + // match to start at its head. + let caps = if anchored { + re.captures(&subject[offset..]) + .filter(|c| c.get(0).map(|m| m.start()) == Some(0)) + } else { + re.captures_at(subject, offset) }?; - Some(PregMatches::new(__resolved, caps)) + Some(PregMatches::new(caps)) } // PREG_PATTERN_ORDER: the outer vec is indexed by capture group, the inner by @@ -381,7 +363,7 @@ where for caps in re.captures_iter(subject) { let m = caps.get(0).unwrap(); out.extend_from_slice(&subject.as_bytes()[last..m.start()]); - let matches = PregMatches::new(__resolved.clone(), caps); + let matches = PregMatches::new(caps); out.extend_from_slice(callback(&matches)?.as_bytes()); last = m.end(); } @@ -503,7 +485,7 @@ fn translate_php_pattern(pattern: &str) -> anyhow::Result<(String, bool)> { /// `LazyLock<Regex>`) rather than an owned `regex::Regex` — `regex::Regex::clone()` does not share /// the underlying meta engine's search-cache pool, so producing a fresh owned clone here would pay /// a ~10us per-call cache warmup cost regardless of which path produced it (measured). -#[derive(Debug, Clone)] +#[derive(Debug)] pub enum ResolvedPattern { Cached(Arc<(regex::Regex, bool)>), Static(&'static regex::Regex, bool), diff --git a/crates/shirabe/src/command/fund_command.rs b/crates/shirabe/src/command/fund_command.rs index 109943d6..22c94539 100644 --- a/crates/shirabe/src/command/fund_command.rs +++ b/crates/shirabe/src/command/fund_command.rs @@ -10,7 +10,7 @@ use crate::package::base_package::{self}; use crate::repository::CompositeRepository; use crate::repository::RepositoryInterface; use indexmap::IndexMap; -use shirabe_pcre::Preg; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{PhpMixed, impl_php_class, php_regex}; use shirabe_semver::constraint::AnyConstraint; use shirabe_semver::constraint::MatchAllConstraint; @@ -63,11 +63,9 @@ impl FundCommand { .and_then(|v| v.as_string()) .unwrap_or(""); if r#type == "github" - && let Some(matches) = Preg::is_match_with_indexed_captures( - php_regex!(r"{^https://github.com/([^/]+)$}"), - &url, - ) - && let Some(sponsor) = matches.into_iter().nth(1).flatten() + && let Some(matches) = + Preg::is_match3(php_regex!(r"{^https://github.com/([^/]+)$}"), &url) + && let Some(sponsor) = matches.get(&CaptureKey::ByIndex(1)).map(str::to_string) { url = format!("https://github.com/sponsors/{}", sponsor); } diff --git a/crates/shirabe/src/command/update_command.rs b/crates/shirabe/src/command/update_command.rs index 2eca6db7..5c119489 100644 --- a/crates/shirabe/src/command/update_command.rs +++ b/crates/shirabe/src/command/update_command.rs @@ -27,7 +27,7 @@ use crate::repository::PlatformRepository; use crate::repository::RepositorySet; use crate::util::HttpDownloader; use indexmap::IndexMap; -use shirabe_pcre::Preg; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{ InvalidArgumentException, PhpMixed, RuntimeException, array_filter, array_intersect, array_keys, array_merge_map, array_search_in_vec, impl_php_class, php_regex, strtolower, @@ -459,15 +459,15 @@ impl Command for UpdateCommand { if package.is_dev() { continue; } - let matches = Preg::is_match_with_indexed_captures( - php_regex!(r"{^(\d+\.\d+\.\d+)}"), - &package.get_version(), - ); + let version = package.get_version(); + let matches = Preg::is_match3(php_regex!(r"{^(\d+\.\d+\.\d+)}"), &version); let Some(matches) = matches else { continue; }; - let constraint = parser - .parse_constraints(&format!("~{}", matches[1].clone().unwrap_or_default()))?; + let constraint = parser.parse_constraints(&format!( + "~{}", + matches.get(&CaptureKey::ByIndex(1)).unwrap_or_default() + ))?; if let Some(existing) = temporary_constraints.get(&package.get_name()) { temporary_constraints.insert( package.get_name(), diff --git a/crates/shirabe/src/installer/binary_installer.rs b/crates/shirabe/src/installer/binary_installer.rs index b382f7c1..1e750439 100644 --- a/crates/shirabe/src/installer/binary_installer.rs +++ b/crates/shirabe/src/installer/binary_installer.rs @@ -316,15 +316,14 @@ impl BinaryInstaller { file_get_contents5(bin, false, PhpMixed::Null, 0, Some(500)).unwrap_or_default(); // For php files, we generate a PHP proxy instead of a shell one, // which allows calling the proxy with a custom php process - if let Some(m) = Preg::is_match_with_indexed_captures( + if let Some(m) = Preg::is_match3( php_regex!(r"{^(#!.*\r?\n)?[\r\n\t ]*<\?php}"), &bin_contents, ) { // carry over the existing shebang if present, otherwise add our own - let proxy_code = if m[1].is_none() { - "#!/usr/bin/env php".to_string() - } else { - trim(m[1].as_deref().unwrap_or(""), None) + let proxy_code = match m.get(&CaptureKey::ByIndex(1)) { + None => "#!/usr/bin/env php".to_string(), + Some(shebang) => trim(shebang, None), }; let bin_path_exported = self .filesystem @@ -370,7 +369,7 @@ impl BinaryInstaller { $data = str_replace('__FILE__', var_export($this->realpath, true), $data);" .to_string(); } - if trim(m[0].as_deref().unwrap_or(""), None) != "<?php" { + if trim(m.get(&CaptureKey::ByIndex(0)).unwrap_or(""), None) != "<?php" { stream_hint = " using a stream wrapper to prevent the shebang from being output on PHP<8\n *" .to_string(); diff --git a/crates/shirabe/src/json/json_manipulator.rs b/crates/shirabe/src/json/json_manipulator.rs index 92661d41..0f0d50de 100644 --- a/crates/shirabe/src/json/json_manipulator.rs +++ b/crates/shirabe/src/json/json_manipulator.rs @@ -737,21 +737,23 @@ impl JsonManipulator { &children[cm.value_end..] ); } else { - if let Some(leading_match) = Preg::is_match_named( + if let Some(leading_match) = Preg::is_match3( php_regex!( "#^\\{(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s" ), &children, ) { let mut whitespace = leading_match - .get("trailingspace") - .cloned() - .unwrap_or_default(); + .get(&CaptureKey::ByName("trailingspace".to_string())) + .unwrap_or_default() + .to_string(); let leading_space = leading_match - .get("leadingspace") - .cloned() - .unwrap_or_default(); - let content_present = leading_match.get("content").is_some(); + .get(&CaptureKey::ByName("leadingspace".to_string())) + .unwrap_or_default() + .to_string(); + let content_present = leading_match + .get(&CaptureKey::ByName("content".to_string())) + .is_some(); if content_present { let mut value_local = value; if let Some(ref sub) = sub_name { @@ -937,10 +939,12 @@ impl JsonManipulator { let children_clean = children_clean.ok_or_else(|| InvalidArgumentException::new("JsonManipulator: $childrenClean is not defined. Please report at https://github.com/nsfisis/php-shirabe/issues/new.".to_string()))?; // no child data left, $name was the only key in - if let Some(empty_match) = Preg::is_match_named( + if let Some(empty_match) = Preg::is_match3( php_regex!("#^\\{\\s*?(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\}$#s"), &children_clean, - ) && empty_match.get("content").is_none() + ) && empty_match + .get(&CaptureKey::ByName("content".to_string())) + .is_none() { self.contents = format!( "{}{{{}{}}}{}", @@ -1032,20 +1036,20 @@ impl JsonManipulator { return Ok(false); } - if let Some(leading_match) = Preg::is_match_named( + if let Some(leading_match) = Preg::is_match3( php_regex!( "#^\\[(?P<leadingspace>\\s*?)(?P<content>\\S+.*?)?(?P<trailingspace>\\s*)\\]$#s" ), &children, ) { let leading_whitespace = leading_match - .get("leadingspace") - .cloned() - .unwrap_or_default(); + .get(&CaptureKey::ByName("leadingspace".to_string())) + .unwrap_or_default() + .to_string(); let mut whitespace = leading_match - .get("trailingspace") - .cloned() - .unwrap_or_default(); + .get(&CaptureKey::ByName("trailingspace".to_string())) + .unwrap_or_default() + .to_string(); let mut leading_item_whitespace = format!("{}{}{}", self.newline, self.indent, self.indent); let mut trailing_item_whitespace = whitespace.clone(); @@ -1058,7 +1062,10 @@ impl JsonManipulator { item_depth = 0; } - if leading_match.get("content").is_some() { + if leading_match + .get(&CaptureKey::ByName("content".to_string())) + .is_some() + { // child missing but non empty children if append { children = Preg::replace( diff --git a/crates/shirabe/src/package/version/version_guesser.rs b/crates/shirabe/src/package/version/version_guesser.rs index daa25361..a01bf469 100644 --- a/crates/shirabe/src/package/version/version_guesser.rs +++ b/crates/shirabe/src/package/version/version_guesser.rs @@ -707,12 +707,12 @@ impl VersionGuesser { trunk_path, branches_path, tags_path, ); - if let Some(matches) = Preg::is_match_with_indexed_captures(&url_pattern, &output) { - let m1 = matches[1].clone().unwrap_or_default(); - let m2 = matches[2].clone(); - let m3 = matches[3].clone(); - if let Some(m2) = m2.as_ref() - && let Some(m3) = m3.as_ref() + if let Some(matches) = Preg::is_match3(&url_pattern, &output) { + let m1 = matches.get(&CaptureKey::ByIndex(1)).unwrap_or_default(); + let m2 = matches.get(&CaptureKey::ByIndex(2)); + let m3 = matches.get(&CaptureKey::ByIndex(3)); + if let Some(m2) = m2 + && let Some(m3) = m3 && (branches_path == *m2 || tags_path == *m2) { // we are in a branches path @@ -728,8 +728,8 @@ impl VersionGuesser { })); } - assert!(is_string(&PhpMixed::String(m1.clone()))); - let pretty_version = trim(&m1, None); + assert!(is_string(&PhpMixed::String(m1.to_string()))); + let pretty_version = trim(m1, None); let version = if pretty_version == "trunk" { "dev-trunk".to_string() } else { diff --git a/crates/shirabe/src/repository/vcs/svn_driver.rs b/crates/shirabe/src/repository/vcs/svn_driver.rs index 9426e1f3..bdd7f021 100644 --- a/crates/shirabe/src/repository/vcs/svn_driver.rs +++ b/crates/shirabe/src/repository/vcs/svn_driver.rs @@ -258,16 +258,15 @@ impl SvnDriver { let identifier = format!("/{}/", trim(identifier, Some("/"))); let (path, rev) = if let Some(m) = - Preg::is_match_with_indexed_captures(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) + Preg::is_match3(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) + && let Some(rev) = m.get(&CaptureKey::ByIndex(2)) { - if m[2].is_some() { - ( - m[1].clone().unwrap_or_default(), - m[2].clone().unwrap_or_default(), - ) - } else { - (identifier.clone(), String::new()) - } + ( + m.get(&CaptureKey::ByIndex(1)) + .unwrap_or_default() + .to_string(), + rev.to_string(), + ) } else { (identifier, String::new()) }; @@ -298,16 +297,15 @@ impl SvnDriver { let identifier = format!("/{}/", trim(identifier, Some("/"))); let (path, rev) = if let Some(m) = - Preg::is_match_with_indexed_captures(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) + Preg::is_match3(php_regex!(r"{^(.+?)(@\d+)?/$}"), &identifier) + && let Some(rev) = m.get(&CaptureKey::ByIndex(2)) { - if m[2].is_some() { - ( - m[1].clone().unwrap_or_default(), - m[2].clone().unwrap_or_default(), - ) - } else { - (identifier.clone(), String::new()) - } + ( + m.get(&CaptureKey::ByIndex(1)) + .unwrap_or_default() + .to_string(), + rev.to_string(), + ) } else { (identifier, String::new()) }; diff --git a/crates/shirabe/src/util/hg.rs b/crates/shirabe/src/util/hg.rs index 29d305f0..395ea6d5 100644 --- a/crates/shirabe/src/util/hg.rs +++ b/crates/shirabe/src/util/hg.rs @@ -5,7 +5,7 @@ use crate::io::IOInterface; use crate::io::IOInterfaceImmutable; use crate::util::ProcessExecutor; use crate::util::Url; -use shirabe_pcre::Preg; +use shirabe_pcre::{CaptureKey, Preg}; use shirabe_php_shim::{php_regex, rawurlencode}; use std::sync::OnceLock; @@ -56,7 +56,7 @@ impl Hg { } // Try with the authentication information available - let matched = Preg::is_match_named( + let matched = Preg::is_match3( php_regex!( r"{^(?P<proto>ssh|https?)://(?:(?P<user>[^:@]+)(?::(?P<pass>[^:@]+))?@)?(?P<host>[^/]+)(?P<path>/.*)?}mi" ), @@ -64,30 +64,44 @@ impl Hg { ); if let Some(matches) = matched - && self - .io - .has_authentication(matches.get("host").map(|s| s.as_str()).unwrap_or("")) + && self.io.has_authentication( + matches + .get(&CaptureKey::ByName("host".to_string())) + .unwrap_or(""), + ) { - let authenticated_url = if matches.get("proto").map(|s| s.as_str()) == Some("ssh") { - let user = if let Some(u) = matches.get("user") { + let authenticated_url = if matches.get(&CaptureKey::ByName("proto".to_string())) + == Some("ssh") + { + let user = if let Some(u) = matches.get(&CaptureKey::ByName("user".to_string())) { format!("{}@", rawurlencode(u)) } else { String::new() }; format!( "{}://{}{}{}", - matches.get("proto").unwrap_or(&String::new()), + matches + .get(&CaptureKey::ByName("proto".to_string())) + .unwrap_or(""), user, - matches.get("host").unwrap_or(&String::new()), - matches.get("path").unwrap_or(&String::new()), + matches + .get(&CaptureKey::ByName("host".to_string())) + .unwrap_or(""), + matches + .get(&CaptureKey::ByName("path".to_string())) + .unwrap_or(""), ) } else { - let auth = self - .io - .get_authentication(matches.get("host").map(|s| s.as_str()).unwrap_or("")); + let auth = self.io.get_authentication( + matches + .get(&CaptureKey::ByName("host".to_string())) + .unwrap_or(""), + ); format!( "{}://{}:{}@{}{}", - matches.get("proto").unwrap_or(&String::new()), + matches + .get(&CaptureKey::ByName("proto".to_string())) + .unwrap_or(""), rawurlencode( auth.get("username") .and_then(|s| s.as_deref()) @@ -98,8 +112,12 @@ impl Hg { .and_then(|s| s.as_deref()) .unwrap_or("") ), - matches.get("host").unwrap_or(&String::new()), - matches.get("path").unwrap_or(&String::new()), + matches + .get(&CaptureKey::ByName("host".to_string())) + .unwrap_or(""), + matches + .get(&CaptureKey::ByName("path".to_string())) + .unwrap_or(""), ) }; @@ -151,12 +169,12 @@ impl Hg { &mut output, None, ) == 0 - && let Some(matches) = Preg::is_match_with_indexed_captures( + && let Some(matches) = Preg::is_match3( php_regex!(r"/^.+? (\d+(?:\.\d+)+)(?:\+.*?)?\)?\r?\n/"), &output, ) { - return matches.into_iter().nth(1).flatten(); + return matches.get(&CaptureKey::ByIndex(1)).map(str::to_string); } None }) |
