aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2026-06-14 13:02:59 +0900
committernsfisis <nsfisis@gmail.com>2026-06-14 13:02:59 +0900
commitcfd2a4488797ddaabd0087aa0021b26892663ffb (patch)
treeed2c030dded78355e0721d5458c2c6b12a3c2f2c /crates
parentc1070afe69f53b621adea232527080d2c922e1a9 (diff)
downloadphp-shirabe-cfd2a4488797ddaabd0087aa0021b26892663ffb.tar.gz
php-shirabe-cfd2a4488797ddaabd0087aa0021b26892663ffb.tar.zst
php-shirabe-cfd2a4488797ddaabd0087aa0021b26892663ffb.zip
refactor(pcre): treat regex compile failure as fatal in shim
The preg_* shim helpers wrapped their results in Option/Result solely to signal a regex that failed to compile. Composer never feeds a pattern that fails at runtime, so such a failure is a programming error: panic instead and drop the Option/Result wrappers, updating all callers. preg_replace_callback keeps its Result return type since the callback itself is fallible. preg_match_groups is removed in favor of preg_match at its sole call site. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'crates')
-rw-r--r--crates/shirabe-external-packages/src/composer/pcre/preg.rs26
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/formatter/output_formatter.rs10
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/helper/helper.rs6
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/input/argv_input.rs9
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/input/input_option.rs2
-rw-r--r--crates/shirabe-external-packages/src/symfony/console/input/string_input.rs13
-rw-r--r--crates/shirabe-php-shim/src/preg.rs81
-rw-r--r--crates/shirabe-semver/src/version_parser.rs11
-rw-r--r--crates/shirabe/src/console/application.rs4
9 files changed, 63 insertions, 99 deletions
diff --git a/crates/shirabe-external-packages/src/composer/pcre/preg.rs b/crates/shirabe-external-packages/src/composer/pcre/preg.rs
index f72835d..d35a3aa 100644
--- a/crates/shirabe-external-packages/src/composer/pcre/preg.rs
+++ b/crates/shirabe-external-packages/src/composer/pcre/preg.rs
@@ -44,8 +44,7 @@ impl Preg {
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL,
offset,
- )
- .unwrap_or_else(|| invalid_regex());
+ );
if let Some(out) = matches {
*out = drop_null_matches(internal);
@@ -83,8 +82,7 @@ impl Preg {
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL,
offset,
- )
- .unwrap_or_else(|| invalid_regex());
+ );
if let Some(out) = matches {
*out = null_to_empty_match_all(internal);
@@ -109,8 +107,7 @@ impl Preg {
Some(&mut internal),
flags | PREG_UNMATCHED_AS_NULL | PREG_OFFSET_CAPTURE,
offset,
- )
- .unwrap_or_else(|| invalid_regex());
+ );
if let Some(out) = matches {
*out = null_to_empty_offset_match_all(internal);
@@ -148,7 +145,6 @@ impl Preg {
// guards (ARRAY_MSG / INVALID_TYPE_MSG) of the PHP original are
// unreachable and not reproduced.
shirabe_php_shim::preg_replace2(pattern, replacement, subject, limit, count)
- .unwrap_or_else(|| invalid_regex())
}
pub fn replace_callback<F: FnMut(&IndexMap<CaptureKey, String>) -> String>(
@@ -172,7 +168,6 @@ impl Preg {
};
shirabe_php_shim::preg_replace_callback2(pattern, adapter, subject, limit, count, flags)
- .unwrap_or_else(|| invalid_regex())
}
pub fn split(pattern: &str, subject: &str) -> Vec<String> {
@@ -186,7 +181,6 @@ impl Preg {
);
shirabe_php_shim::preg_split2(pattern, subject, limit, flags)
- .unwrap_or_else(|| invalid_regex())
}
pub fn grep(pattern: &str, array: &[&str]) -> Vec<String> {
@@ -194,7 +188,7 @@ impl Preg {
}
pub fn grep3(pattern: &str, array: &[&str], flags: i64) -> Vec<String> {
- shirabe_php_shim::preg_grep2(pattern, array, flags).unwrap_or_else(|| invalid_regex())
+ shirabe_php_shim::preg_grep2(pattern, array, flags)
}
pub fn is_match(pattern: &str, subject: &str) -> bool {
@@ -231,8 +225,7 @@ impl Preg {
Some(&mut internal),
PREG_UNMATCHED_AS_NULL,
0,
- )
- .unwrap_or_else(|| invalid_regex());
+ );
matches.clear();
for (key, value) in internal {
@@ -248,8 +241,7 @@ impl Preg {
// Classic preg_match semantics (no PREG_UNMATCHED_AS_NULL): trailing
// unmatched groups are truncated, interior unmatched groups become "".
let mut internal: IndexMap<CaptureKey, Option<String>> = IndexMap::new();
- let result = shirabe_php_shim::preg_match2(pattern, subject, Some(&mut internal), 0, 0)
- .unwrap_or_else(|| invalid_regex());
+ let result = shirabe_php_shim::preg_match2(pattern, subject, Some(&mut internal), 0, 0);
if result == 0 {
return None;
@@ -363,9 +355,3 @@ fn null_to_empty_offset_match_all(
})
.collect()
}
-
-/// Panics if a pattern is invalid instead of throwing a PcreException.
-/// TODO: takes regex::Error and shows its message
-fn invalid_regex() -> ! {
- panic!("invalid regex");
-}
diff --git a/crates/shirabe-external-packages/src/symfony/console/formatter/output_formatter.rs b/crates/shirabe-external-packages/src/symfony/console/formatter/output_formatter.rs
index 0de90be..6736ada 100644
--- a/crates/shirabe-external-packages/src/symfony/console/formatter/output_formatter.rs
+++ b/crates/shirabe-external-packages/src/symfony/console/formatter/output_formatter.rs
@@ -19,8 +19,7 @@ pub struct OutputFormatter {
impl OutputFormatter {
/// Escapes "<" and ">" special chars in given text.
pub fn escape(text: &str) -> anyhow::Result<String> {
- let text = shirabe_php_shim::preg_replace("/([^\\\\]|^)([<>])/", "$1\\\\$2", text)
- .expect("preg_replace failed");
+ let text = shirabe_php_shim::preg_replace("/([^\\\\]|^)([<>])/", "$1\\\\$2", text);
Ok(Self::escape_trailing_backslash(&text))
}
@@ -106,7 +105,7 @@ impl OutputFormatter {
"/([^=]+)=([^;]+)(;|$)/",
string,
&mut matches,
- )? == 0
+ ) == 0
{
return Ok(None);
}
@@ -122,8 +121,7 @@ impl OutputFormatter {
} else if r#match[0] == "bg" {
style.set_background(Some(&shirabe_php_shim::strtolower(&r#match[1])));
} else if r#match[0] == "href" {
- let url = shirabe_php_shim::preg_replace("{\\\\([<>])}", "$1", &r#match[1])
- .expect("preg_replace failed");
+ let url = shirabe_php_shim::preg_replace("{\\\\([<>])}", "$1", &r#match[1]);
style.set_href(&url);
} else if r#match[0] == "options" {
let mut options = shirabe_php_shim::preg_match_all(
@@ -292,7 +290,7 @@ impl WrappableOutputFormatterInterface for OutputFormatter {
&format!("#<(({open_tag_regex}) | /({close_tag_regex})?)>#ix"),
message,
&mut matches,
- )?;
+ );
let count = matches.group(0).len();
for i in 0..count {
let (text, pos) = matches.group(0)[i].clone();
diff --git a/crates/shirabe-external-packages/src/symfony/console/helper/helper.rs b/crates/shirabe-external-packages/src/symfony/console/helper/helper.rs
index 40a8f85..07b1f77 100644
--- a/crates/shirabe-external-packages/src/symfony/console/helper/helper.rs
+++ b/crates/shirabe-external-packages/src/symfony/console/helper/helper.rs
@@ -147,12 +147,10 @@ impl Helper {
// remove <...> formatting
let string = formatter.format(Some(string)).unwrap().unwrap_or_default();
// remove already formatted characters
- let string =
- shirabe_php_shim::preg_replace("/\u{1b}\\[[^m]*m/", "", &string).unwrap_or_default();
+ let string = shirabe_php_shim::preg_replace("/\u{1b}\\[[^m]*m/", "", &string);
// remove terminal hyperlinks
let string =
- shirabe_php_shim::preg_replace("/\u{1b}]8;[^;]*;[^\u{1b}]*\u{1b}\\\\/", "", &string)
- .unwrap_or_default();
+ shirabe_php_shim::preg_replace("/\u{1b}]8;[^;]*;[^\u{1b}]*\u{1b}\\\\/", "", &string);
formatter.set_decorated(is_decorated);
string
diff --git a/crates/shirabe-external-packages/src/symfony/console/input/argv_input.rs b/crates/shirabe-external-packages/src/symfony/console/input/argv_input.rs
index ea36e26..2b1102c 100644
--- a/crates/shirabe-external-packages/src/symfony/console/input/argv_input.rs
+++ b/crates/shirabe-external-packages/src/symfony/console/input/argv_input.rs
@@ -528,8 +528,13 @@ impl ArgvInput {
.tokens
.iter()
.map(|token| {
- if let Some(m) = shirabe_php_shim::preg_match_groups("{^(-[^=]+=)(.+)}", token) {
- return format!("{}{}", m[1], self.inner.escape_token(&m[2]));
+ let mut r#match: Vec<Option<String>> = Vec::new();
+ if shirabe_php_shim::preg_match("{^(-[^=]+=)(.+)}", token, &mut r#match) != 0 {
+ return format!(
+ "{}{}",
+ r#match[1].as_deref().unwrap_or(""),
+ self.inner.escape_token(r#match[2].as_deref().unwrap_or(""))
+ );
}
if !token.is_empty() && token.as_bytes()[0] != b'-' {
diff --git a/crates/shirabe-external-packages/src/symfony/console/input/input_option.rs b/crates/shirabe-external-packages/src/symfony/console/input/input_option.rs
index 7e2d086..5ef265e 100644
--- a/crates/shirabe-external-packages/src/symfony/console/input/input_option.rs
+++ b/crates/shirabe-external-packages/src/symfony/console/input/input_option.rs
@@ -110,7 +110,7 @@ impl InputOption {
fn normalize_shortcut(s: String) -> anyhow::Result<Option<String>> {
let stripped = shirabe_php_shim::ltrim(&s, Some("-"));
- let parts = shirabe_php_shim::preg_split(r"\|(-?)", &stripped).unwrap_or_default();
+ let parts = shirabe_php_shim::preg_split(r"\|(-?)", &stripped);
let filtered: Vec<String> =
shirabe_php_shim::array_filter(&parts, |s: &String| !s.is_empty());
let result = shirabe_php_shim::implode("|", &filtered);
diff --git a/crates/shirabe-external-packages/src/symfony/console/input/string_input.rs b/crates/shirabe-external-packages/src/symfony/console/input/string_input.rs
index 952a18e..f57fcf6 100644
--- a/crates/shirabe-external-packages/src/symfony/console/input/string_input.rs
+++ b/crates/shirabe-external-packages/src/symfony/console/input/string_input.rs
@@ -56,7 +56,6 @@ impl StringInput {
let mut m: IndexMap<CaptureKey, Option<String>> = IndexMap::new();
if shirabe_php_shim::preg_match2(r"/\s+/A", input, Some(&mut m), 0, cursor as usize)
- .expect("invalid regex")
== 1
{
if token.is_some() {
@@ -70,9 +69,7 @@ impl StringInput {
Some(&mut m),
0,
cursor as usize,
- )
- .expect("invalid regex")
- == 1
+ ) == 1
{
let inner = shirabe_php_shim::substr(
m[&CaptureKey::ByIndex(3)].as_deref().unwrap_or(""),
@@ -96,9 +93,7 @@ impl StringInput {
Some(&mut m),
0,
cursor as usize,
- )
- .expect("invalid regex")
- == 1
+ ) == 1
{
token = Some(format!(
"{}{}",
@@ -117,9 +112,7 @@ impl StringInput {
Some(&mut m),
0,
cursor as usize,
- )
- .expect("invalid regex")
- == 1
+ ) == 1
{
token = Some(format!(
"{}{}",
diff --git a/crates/shirabe-php-shim/src/preg.rs b/crates/shirabe-php-shim/src/preg.rs
index 48b81ed..dc91fd6 100644
--- a/crates/shirabe-php-shim/src/preg.rs
+++ b/crates/shirabe-php-shim/src/preg.rs
@@ -56,13 +56,11 @@ pub fn preg_match(pattern: &str, subject: &str, matches: &mut Vec<Option<String>
}
}
-// Returns Some(result) on success, None on error.
-pub fn preg_replace(pattern: &str, replacement: &str, subject: &str) -> Option<String> {
+pub fn preg_replace(pattern: &str, replacement: &str, subject: &str) -> String {
preg_replace2(pattern, replacement, subject, -1, None)
}
-// Returns Some(parts) on success, None on error.
-pub fn preg_split(pattern: &str, subject: &str) -> Option<Vec<String>> {
+pub fn preg_split(pattern: &str, subject: &str) -> Vec<String> {
preg_split2(pattern, subject, -1, 0)
}
@@ -90,21 +88,15 @@ pub fn preg_match_all_set_order(
pattern: &str,
subject: &str,
matches: &mut Vec<Vec<String>>,
-) -> anyhow::Result<i64> {
- let re = compile_php_pattern(pattern)?;
+) -> i64 {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let mut rows: Vec<Vec<String>> = Vec::new();
for caps in re.captures_iter(subject) {
rows.push(php_match_row(&caps));
}
let count = rows.len() as i64;
*matches = rows;
- Ok(count)
-}
-
-pub fn preg_match_groups(pattern: &str, subject: &str) -> Option<Vec<String>> {
- let re = compile_php_pattern(pattern).ok()?;
- let caps = re.captures(subject)?;
- Some(php_match_row(&caps))
+ count
}
pub fn preg_grep(pattern: &str, input: &Vec<String>) -> Vec<String> {
@@ -116,8 +108,8 @@ pub fn preg_match_all_offset_capture(
pattern: &str,
subject: &str,
matches: &mut PregOffsetCaptureMatches,
-) -> anyhow::Result<i64> {
- let re = compile_php_pattern(pattern)?;
+) -> i64 {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let group_count = re.captures_len();
matches.groups = vec![Vec::new(); group_count];
@@ -136,7 +128,7 @@ pub fn preg_match_all_offset_capture(
}
}
- Ok(count)
+ count
}
pub fn preg_replace_callback<F>(
pattern: &str,
@@ -146,7 +138,7 @@ pub fn preg_replace_callback<F>(
where
F: FnMut(&[Option<String>]) -> anyhow::Result<String>,
{
- let re = compile_php_pattern(pattern)?;
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let mut out: Vec<u8> = Vec::new();
let mut last = 0;
for caps in re.captures_iter(subject) {
@@ -163,16 +155,15 @@ where
Ok(String::from_utf8_lossy(&out).into_owned())
}
-// Returns Some(0|1) on success or None when the underlying preg_match returned
-// false. Unmatched groups are reported as None (PREG_UNMATCHED_AS_NULL).
+// Returns 0|1. Unmatched groups are reported as None (PREG_UNMATCHED_AS_NULL).
pub fn preg_match2(
pattern: &str,
subject: &str,
matches: Option<&mut indexmap::IndexMap<CaptureKey, Option<String>>>,
flags: i64,
offset: usize,
-) -> Option<i64> {
- let re = compile_php_pattern(pattern).ok()?;
+) -> i64 {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let unmatched_as_null = flags & PREG_UNMATCHED_AS_NULL != 0;
let caps = re.captures_at(subject, offset);
@@ -184,7 +175,7 @@ pub fn preg_match2(
}
}
- Some(if caps.is_some() { 1 } else { 0 })
+ if caps.is_some() { 1 } else { 0 }
}
pub fn preg_match_all2(
@@ -193,8 +184,8 @@ pub fn preg_match_all2(
matches: Option<&mut indexmap::IndexMap<CaptureKey, Vec<Option<String>>>>,
flags: i64,
offset: usize,
-) -> Option<i64> {
- let re = compile_php_pattern(pattern).ok()?;
+) -> i64 {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let unmatched_as_null = flags & PREG_UNMATCHED_AS_NULL != 0;
let group_count = re.captures_len();
let names: Vec<Option<&str>> = re.capture_names().collect();
@@ -224,7 +215,7 @@ pub fn preg_match_all2(
}
}
- Some(count)
+ count
}
pub fn preg_match_all_offset_capture2(
@@ -233,8 +224,8 @@ pub fn preg_match_all_offset_capture2(
matches: Option<&mut indexmap::IndexMap<CaptureKey, Vec<(Option<String>, i64)>>>,
flags: i64,
offset: usize,
-) -> Option<i64> {
- let re = compile_php_pattern(pattern).ok()?;
+) -> i64 {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let unmatched_as_null = flags & PREG_UNMATCHED_AS_NULL != 0;
let group_count = re.captures_len();
let names: Vec<Option<&str>> = re.capture_names().collect();
@@ -263,7 +254,7 @@ pub fn preg_match_all_offset_capture2(
}
}
- Some(count)
+ count
}
pub fn preg_replace2(
@@ -272,8 +263,8 @@ pub fn preg_replace2(
subject: &str,
limit: i64,
count: Option<&mut usize>,
-) -> Option<String> {
- let re = compile_php_pattern(pattern).ok()?;
+) -> String {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let limit = if limit < 0 {
usize::MAX
} else {
@@ -298,7 +289,7 @@ pub fn preg_replace2(
if let Some(count) = count {
*count = n;
}
- Some(String::from_utf8_lossy(&out).into_owned())
+ String::from_utf8_lossy(&out).into_owned()
}
pub fn preg_replace_callback2<
@@ -310,8 +301,8 @@ pub fn preg_replace_callback2<
limit: i64,
count: Option<&mut usize>,
flags: i64,
-) -> Option<String> {
- let re = compile_php_pattern(pattern).ok()?;
+) -> String {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let unmatched_as_null = flags & PREG_UNMATCHED_AS_NULL != 0;
let names: Vec<Option<&str>> = re.capture_names().collect();
let limit = if limit < 0 {
@@ -339,11 +330,11 @@ pub fn preg_replace_callback2<
if let Some(count) = count {
*count = n;
}
- Some(String::from_utf8_lossy(&out).into_owned())
+ String::from_utf8_lossy(&out).into_owned()
}
-pub fn preg_split2(pattern: &str, subject: &str, limit: i64, flags: i64) -> Option<Vec<String>> {
- let re = compile_php_pattern(pattern).ok()?;
+pub fn preg_split2(pattern: &str, subject: &str, limit: i64, flags: i64) -> Vec<String> {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let no_empty = flags & PREG_SPLIT_NO_EMPTY != 0;
let delim_capture = flags & PREG_SPLIT_DELIM_CAPTURE != 0;
// `limit` counts the resulting pieces; a non-positive value means no limit.
@@ -382,19 +373,17 @@ pub fn preg_split2(pattern: &str, subject: &str, limit: i64, flags: i64) -> Opti
}
push(&subject[last..], &mut result);
- Some(result)
+ result
}
-pub fn preg_grep2(pattern: &str, array: &[&str], flags: i64) -> Option<Vec<String>> {
- let re = compile_php_pattern(pattern).ok()?;
+pub fn preg_grep2(pattern: &str, array: &[&str], flags: i64) -> Vec<String> {
+ let re = compile_php_pattern(pattern).unwrap_or_else(|e| panic!("invalid regex: {e}"));
let invert = flags & PREG_GREP_INVERT != 0;
- Some(
- array
- .iter()
- .filter(|s| re.is_match(s) != invert)
- .map(|s| s.to_string())
- .collect(),
- )
+ array
+ .iter()
+ .filter(|s| re.is_match(s) != invert)
+ .map(|s| s.to_string())
+ .collect()
}
// Translates a PHP PCRE pattern (delimiters + trailing modifiers) into a regex
diff --git a/crates/shirabe-semver/src/version_parser.rs b/crates/shirabe-semver/src/version_parser.rs
index bbd359e..bb4656c 100644
--- a/crates/shirabe-semver/src/version_parser.rs
+++ b/crates/shirabe-semver/src/version_parser.rs
@@ -25,7 +25,7 @@ pub struct VersionParser;
impl VersionParser {
pub fn parse_stability(version: &str) -> String {
- let version = php::preg_replace("{#.+$}", "", version).unwrap_or_default();
+ let version = php::preg_replace("{#.+$}", "", version);
if version.starts_with("dev-") || version.ends_with("-dev") {
return "dev".to_string();
@@ -143,8 +143,7 @@ impl VersionParser {
MODIFIER_REGEX
);
if php::preg_match(&datetime_pattern, &version, &mut matches) > 0 {
- version = php::preg_replace("{\\D}", ".", matches[1].as_deref().unwrap_or(""))
- .unwrap_or_default();
+ version = php::preg_replace("{\\D}", ".", matches[1].as_deref().unwrap_or(""));
index = Some(2);
}
}
@@ -297,8 +296,7 @@ impl VersionParser {
pub fn parse_constraints(&self, constraints: &str) -> anyhow::Result<AnyConstraint> {
let pretty_constraint = constraints.to_string();
- let or_constraints = php::preg_split("{\\s*\\|\\|?\\s*}", &php::trim(constraints, None))
- .ok_or_else(|| anyhow::anyhow!("Failed to preg_split string: {}", constraints))?;
+ let or_constraints = php::preg_split("{\\s*\\|\\|?\\s*}", &php::trim(constraints, None));
let mut or_groups: Vec<AnyConstraint> = Vec::new();
@@ -306,8 +304,7 @@ impl VersionParser {
let and_constraints = php::preg_split(
"{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}",
or_constraint,
- )
- .ok_or_else(|| anyhow::anyhow!("Failed to preg_split string: {}", or_constraint))?;
+ );
let constraint_objects: Vec<AnyConstraint> = if and_constraints.len() > 1 {
let mut objs: Vec<AnyConstraint> = Vec::new();
diff --git a/crates/shirabe/src/console/application.rs b/crates/shirabe/src/console/application.rs
index 4be2f90..ad0073f 100644
--- a/crates/shirabe/src/console/application.rs
+++ b/crates/shirabe/src/console/application.rs
@@ -2711,9 +2711,7 @@ impl Application {
Some(&mut m),
0,
offset as usize,
- )
- .expect("invalid regex")
- == 1
+ ) == 1
{
let m0 = m[&shirabe_php_shim::CaptureKey::ByIndex(0)]
.as_deref()