From f4cad2123b2af0de72bda4ce039e16e74f163f4e Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sat, 8 Aug 2026 22:14:12 +0900 Subject: feat(php-shim): give ported exceptions PHP's class hierarchy Ported exceptions were flat structs reached with `downcast_ref`, so Composer's `catch (\RuntimeException $e)` only matched the exact leaf type and `get_class($e)` had nothing to report. Each exception now embeds an instance of the class it extends and travels inside an `AnyThrowable`; `Catch::catch`/`catch_mut` walk that chain, and `PhpClass::php_class_name` yields the PHP FQCN. Dropping the `std::error::Error` impls from the exception types leaves `AnyThrowable` as the only route into an `anyhow::Error`, so the walk cannot be bypassed. A `no_exception_downcast` linter catches the `downcast::()` calls that would now silently answer `None`. Three sites change behavior as a result: the `TransportException` exit-code override reaches `MaxFileSizeExceededException`, the `catch (\LogicException)` in findSimilar() reaches its subclasses, and rendered exception titles carry the real class name rather than a guess. `get_class_err()` is no longer a `todo!()`, which re-enables FilesystemRepositoryTest::testCorruptedRepositoryFile. Co-Authored-By: Claude Opus 5 (1M context) --- crates/shirabe/src/json/json_file.rs | 71 +++++++++------------- crates/shirabe/src/json/json_manipulator.rs | 35 +++++------ .../shirabe/src/json/json_validation_exception.rs | 18 ++---- 3 files changed, 49 insertions(+), 75 deletions(-) (limited to 'crates/shirabe/src/json') diff --git a/crates/shirabe/src/json/json_file.rs b/crates/shirabe/src/json/json_file.rs index 1d6a75ce..2d061ced 100644 --- a/crates/shirabe/src/json/json_file.rs +++ b/crates/shirabe/src/json/json_file.rs @@ -11,6 +11,7 @@ use crate::util::Silencer; use indexmap::IndexMap; use shirabe_external_packages::composer::pcre::{CaptureKey, Preg}; use shirabe_external_packages::seld::json_lint::{ParsingException, ParsingExceptionDetails}; +use shirabe_php_shim::Catch as _; use shirabe_php_shim::{ InvalidArgumentException, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, PhpMixed, RuntimeException, UnexpectedValueException, dirname, file_exists, file_get_contents, @@ -108,10 +109,9 @@ impl JsonFile { io: Option>>, ) -> anyhow::Result { if http_downloader.is_none() && Preg::is_match(php_regex!(r"{^https?://}i"), &path) { - return Err(InvalidArgumentException { - message: "http urls require a HttpDownloader instance to be passed".to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "http urls require a HttpDownloader instance to be passed".to_string(), + ) .into()); } Ok(Self { @@ -145,10 +145,10 @@ impl JsonFile { .map(|s| s.to_string())) } else { if !Filesystem::is_readable(&self.path) { - return Err(RuntimeException { - message: format!("The file \"{}\" is not readable.", self.path), - code: 0, - } + return Err(RuntimeException::new(format!( + "The file \"{}\" is not readable.", + self.path + )) .into()); } if let Some(io) = &self.io @@ -173,17 +173,13 @@ impl JsonFile { Err(e) => { // TransportException keeps its message verbatim; any other exception is wrapped // with the "Could not read" prefix. - if let Some(te) = e.downcast_ref::() { - return Err(RuntimeException { - message: te.message.clone(), - code: 0, - } - .into()); - } - return Err(RuntimeException { - message: format!("Could not read {}\n\n{}", self.path, e), - code: 0, + if let Some(te) = e.catch::() { + return Err(RuntimeException::new(te.get_message().to_string()).into()); } + return Err(RuntimeException::new(format!( + "Could not read {}\n\n{}", + self.path, e + )) .into()); } }; @@ -191,11 +187,7 @@ impl JsonFile { let json = match json { Some(j) => j, None => { - return Err(RuntimeException { - message: format!("Could not read {}", self.path), - code: 0, - } - .into()); + return Err(RuntimeException::new(format!("Could not read {}", self.path)).into()); } }; @@ -230,21 +222,18 @@ impl JsonFile { let dir = dirname(&self.path); if !is_dir(&dir) { if file_exists(&dir) { - return Err(UnexpectedValueException { - message: format!( - "{} exists and is not a directory.", - realpath(&dir).unwrap_or_default(), - ), - code: 0, - } + return Err(UnexpectedValueException::new(format!( + "{} exists and is not a directory.", + realpath(&dir).unwrap_or_default(), + )) .into()); } // PHP: @mkdir($dir, 0777, true) if !Silencer::call(|| Ok(mkdir(&dir, 0o777, true))).unwrap_or(false) { - return Err(UnexpectedValueException { - message: format!("{} does not exist and could not be created.", dir), - code: 0, - } + return Err(UnexpectedValueException::new(format!( + "{} does not exist and could not be created.", + dir + )) .into()); } } @@ -305,10 +294,10 @@ impl JsonFile { /// @return true true on success pub fn validate_schema(&self, schema: i64, schema_file: Option<&str>) -> anyhow::Result { if !Filesystem::is_readable(&self.path) { - return Err(RuntimeException { - message: format!("The file \"{}\" is not readable.", self.path), - code: 0, - } + return Err(RuntimeException::new(format!( + "The file \"{}\" is not readable.", + self.path + )) .into()); } let content = file_get_contents(&self.path).unwrap_or_default(); @@ -446,10 +435,8 @@ impl JsonFile { data: &T, options: JsonEncodeOptions, ) -> anyhow::Result { - let json = json_encode_ex(data, options.to_flags()).map_err(|err| RuntimeException { - message: format!("JSON encoding failed: {}", err), - code: 0, - })?; + let json = json_encode_ex(data, options.to_flags()) + .map_err(|err| RuntimeException::new(format!("JSON encoding failed: {}", err)))?; if options.pretty_print && options.indent != Self::INDENT_DEFAULT { // Pretty printing and not using default indentation diff --git a/crates/shirabe/src/json/json_manipulator.rs b/crates/shirabe/src/json/json_manipulator.rs index eec823b6..d66fe645 100644 --- a/crates/shirabe/src/json/json_manipulator.rs +++ b/crates/shirabe/src/json/json_manipulator.rs @@ -36,10 +36,9 @@ impl JsonManipulator { contents = "{}".to_string(); } if !Preg::is_match3(php_regex!("#^\\{(.*)\\}$#s"), &contents, None) { - return Err(InvalidArgumentException { - message: "The json file must be an object ({})".to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "The json file must be an object ({})".to_string(), + ) .into()); } let newline = if strpos(&contents, "\r\n").is_some() { @@ -823,10 +822,10 @@ impl JsonManipulator { ); } } else { - return Err(LogicException { - message: format!("Nothing matched above for: {}", children), - code: 0, - } + return Err(LogicException::new(format!( + "Nothing matched above for: {}", + children + )) .into()); } } @@ -940,10 +939,7 @@ impl JsonManipulator { children_clean = Some(children.clone()); } - let children_clean = children_clean.ok_or_else(|| InvalidArgumentException { - message: "JsonManipulator: $childrenClean is not defined. Please report at https://github.com/composer/composer/issues/new.".to_string(), - code: 0, - })?; + let children_clean = children_clean.ok_or_else(|| InvalidArgumentException::new("JsonManipulator: $childrenClean is not defined. Please report at https://github.com/composer/composer/issues/new.".to_string()))?; // no child data left, $name was the only key in let mut empty_match: IndexMap = IndexMap::new(); @@ -1113,11 +1109,9 @@ impl JsonManipulator { ); } } else { - return Err(LogicException { - message: format!("Nothing matched above for: {}", children), - code: 0, - } - .into()); + return Err( + LogicException::new(format!("Nothing matched above for: {}", children)).into(), + ); } self.contents = format!("{}{}{}", node_start, children, node_end); @@ -1132,10 +1126,9 @@ impl JsonManipulator { index: i64, ) -> anyhow::Result { if index < 0 { - return Err(InvalidArgumentException { - message: "Index can only be positive integer".to_string(), - code: 0, - } + return Err(InvalidArgumentException::new( + "Index can only be positive integer".to_string(), + ) .into()); } diff --git a/crates/shirabe/src/json/json_validation_exception.rs b/crates/shirabe/src/json/json_validation_exception.rs index a63edda3..cb7370d2 100644 --- a/crates/shirabe/src/json/json_validation_exception.rs +++ b/crates/shirabe/src/json/json_validation_exception.rs @@ -11,7 +11,7 @@ pub struct JsonValidationException { impl JsonValidationException { pub fn new(message: String, errors: Vec) -> Self { Self { - inner: Exception { message, code: 0 }, + inner: Exception::new(message), errors, } } @@ -19,16 +19,10 @@ impl JsonValidationException { pub fn get_errors(&self) -> &Vec { &self.errors } - - pub fn get_message(&self) -> &str { - &self.inner.message - } -} - -impl std::fmt::Display for JsonValidationException { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.inner.message) - } } -impl std::error::Error for JsonValidationException {} +shirabe_php_shim::impl_php_exception!( + JsonValidationException, + inner, + r"Composer\Json\JsonValidationException" +); -- cgit v1.3.1-4-g156e