diff --git a/crates/oxc_span/src/source_type/error.rs b/crates/oxc_span/src/source_type/error.rs new file mode 100644 index 0000000000000..72334364aaf2e --- /dev/null +++ b/crates/oxc_span/src/source_type/error.rs @@ -0,0 +1,29 @@ +use std::{borrow::Cow, error::Error, fmt, ops::Deref}; + +/// Error returned by [`SourceType::from_path`] when the file extension is not +/// found or recognized. +/// +/// [`SourceType::from_path`]: `crate::SourceType::from_path` +#[derive(Debug)] +pub struct UnknownExtension(/* msg */ pub(crate) Cow<'static, str>); + +impl Deref for UnknownExtension { + type Target = str; + fn deref(&self) -> &str { + &self.0 + } +} +impl UnknownExtension { + #[inline] + pub(crate) fn new>>(ext: S) -> Self { + Self(ext.into()) + } +} + +impl fmt::Display for UnknownExtension { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Unknown file extension: {}", self.0) + } +} + +impl Error for UnknownExtension {} diff --git a/crates/oxc_span/src/source_type/mod.rs b/crates/oxc_span/src/source_type/mod.rs index 053268e987b48..d4caec37bc8fd 100644 --- a/crates/oxc_span/src/source_type/mod.rs +++ b/crates/oxc_span/src/source_type/mod.rs @@ -1,12 +1,11 @@ -use std::path::Path; - +mod error; mod types; + +pub use error::UnknownExtension; use oxc_allocator::{Allocator, CloneIn}; +use std::path::Path; pub use types::*; -#[derive(Debug)] -pub struct UnknownExtension(pub String); - impl Default for SourceType { fn default() -> Self { Self { @@ -160,7 +159,7 @@ impl SourceType { .as_ref() .file_name() .and_then(std::ffi::OsStr::to_str) - .ok_or_else(|| UnknownExtension("Please provide a valid file name.".to_string()))?; + .ok_or_else(|| UnknownExtension::new("Please provide a valid file name."))?; let extension = path .as_ref() @@ -169,7 +168,7 @@ impl SourceType { .filter(|s| VALID_EXTENSIONS.contains(s)) .ok_or_else(|| { let path = path.as_ref().to_string_lossy(); - UnknownExtension( + UnknownExtension::new( format!("Please provide a valid file extension for {path}: .js, .mjs, .jsx or .cjs for JavaScript, or .ts, .d.ts, .mts, .cts or .tsx for TypeScript"), ) })?; @@ -192,7 +191,7 @@ impl SourceType { #[cfg(debug_assertions)] unreachable!(); #[cfg(not(debug_assertions))] - return Err(UnknownExtension(format!("Unknown extension: {}", extension))); + return Err(UnknownExtension(format!("Unknown extension: {}", extension).into())); } };