Skip to main content

nativeview_codegen/
error.rs

1use std::fmt;
2
3/// Error returned by the bi-directional RN <-> NV code generator.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum CodegenError {
6    /// Lexical or syntactic error while parsing a React Native TypeScript/Flow spec.
7    Parse {
8        line: usize,
9        col: usize,
10        message: String,
11    },
12    /// Semantic or validation error in a parsed RN spec or `#[nv_hybrid_view]` spec.
13    Validation(String),
14    /// Filesystem I/O failure when reading specs or writing generated outputs.
15    Io { path: String, message: String },
16    /// This build was compiled from other templates than the checkout's (a stale cached build).
17    StaleTemplates(crate::TemplateDrift),
18}
19
20impl CodegenError {
21    pub fn parse(line: usize, col: usize, message: impl Into<String>) -> Self {
22        Self::Parse {
23            line,
24            col,
25            message: message.into(),
26        }
27    }
28
29    pub fn validation(message: impl Into<String>) -> Self {
30        Self::Validation(message.into())
31    }
32
33    pub fn io(path: impl Into<String>, err: impl fmt::Display) -> Self {
34        Self::Io {
35            path: path.into(),
36            message: err.to_string(),
37        }
38    }
39
40    pub fn io_path(path: &std::path::Path, err: impl fmt::Display) -> Self {
41        Self::io(path.display().to_string(), err)
42    }
43}
44
45impl fmt::Display for CodegenError {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::Parse { line, col, message } => {
49                write!(f, "spec parse error at {line}:{col}: {message}")
50            }
51            Self::Validation(msg) => write!(f, "spec validation error: {msg}"),
52            Self::Io { path, message } => write!(f, "I/O error for '{path}': {message}"),
53            Self::StaleTemplates(drift) => drift.fmt(f),
54        }
55    }
56}
57
58impl From<nativeview_hybrid_spec::SpecError> for CodegenError {
59    fn from(err: nativeview_hybrid_spec::SpecError) -> Self {
60        match err {
61            nativeview_hybrid_spec::SpecError::Parse {
62                line, col, message, ..
63            } => Self::Parse { line, col, message },
64            nativeview_hybrid_spec::SpecError::Validation { message, .. } => Self::Validation(message),
65            nativeview_hybrid_spec::SpecError::Io { path, message } => Self::Io { path, message },
66        }
67    }
68}
69
70impl std::error::Error for CodegenError {}