wahgex_core/
error.rs

1//! This module contains types and functions related to public-facing errors.
2
3use std::{alloc::LayoutError, error::Error, fmt};
4
5/// Represents an error that can occur during the regex compilation process.
6///
7/// This error type encapsulates various kinds of issues, from NFA construction
8/// problems to memory layout errors and unsupported regex features.
9#[derive(Debug)]
10pub struct BuildError {
11    kind: Box<BuildErrorKind>,
12}
13
14impl BuildError {
15    pub(crate) fn unsupported(feature: impl Into<String>) -> Self {
16        Self {
17            kind: Box::new(BuildErrorKind::Unsupported(feature.into())),
18        }
19    }
20
21    /// Return true if the error was caused by an unsupported feature.
22    pub fn is_unsupported(&self) -> bool {
23        matches!(&*self.kind, BuildErrorKind::Unsupported(_))
24    }
25}
26
27impl fmt::Display for BuildError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match &*self.kind {
30            BuildErrorKind::Layout(err) => err.fmt(f),
31            BuildErrorKind::NFABuild(err) => err.fmt(f),
32            BuildErrorKind::LookaroundUnicode(err) => err.fmt(f),
33            BuildErrorKind::Unsupported(feature) => write!(f, "Unsupported feature: {feature}"),
34        }
35    }
36}
37
38impl Error for BuildError {
39    fn source(&self) -> Option<&(dyn Error + 'static)> {
40        match &*self.kind {
41            BuildErrorKind::Layout(err) => Some(err),
42            BuildErrorKind::NFABuild(err) => Some(err),
43            BuildErrorKind::LookaroundUnicode(err) => Some(err),
44            BuildErrorKind::Unsupported(_) => None,
45        }
46    }
47}
48
49impl From<LayoutError> for BuildError {
50    fn from(value: LayoutError) -> Self {
51        Self {
52            kind: Box::new(BuildErrorKind::Layout(value)),
53        }
54    }
55}
56
57impl From<regex_automata::nfa::thompson::BuildError> for BuildError {
58    fn from(value: regex_automata::nfa::thompson::BuildError) -> Self {
59        Self {
60            kind: Box::new(BuildErrorKind::NFABuild(value)),
61        }
62    }
63}
64
65impl From<regex_automata::util::look::UnicodeWordBoundaryError> for BuildError {
66    fn from(value: regex_automata::util::look::UnicodeWordBoundaryError) -> Self {
67        Self {
68            kind: Box::new(BuildErrorKind::LookaroundUnicode(value)),
69        }
70    }
71}
72
73/// Represents the specific kind of a [`BuildError`].
74///
75/// This enum provides more granular information about the underlying cause of a
76/// `BuildError`.
77#[derive(Debug)]
78enum BuildErrorKind {
79    Layout(LayoutError),
80    NFABuild(regex_automata::nfa::thompson::BuildError),
81    LookaroundUnicode(regex_automata::util::look::UnicodeWordBoundaryError),
82    Unsupported(String),
83}