Hide error enum variants from cxx-gen public api
We can expose more detail on the error as the need arises, but start
with an opaque error type for now.
diff --git a/gen/lib/src/lib.rs b/gen/lib/src/lib.rs
index 3b1b3c6..ca9fabe 100644
--- a/gen/lib/src/lib.rs
+++ b/gen/lib/src/lib.rs
@@ -7,8 +7,10 @@
mod gen;
mod syntax;
-pub use crate::gen::{Error, Opt};
+pub use crate::gen::Opt;
use proc_macro2::TokenStream;
+use std::error::Error as StdError;
+use std::fmt::{self, Debug, Display};
/// Results of code generation.
pub struct GeneratedCode {
@@ -18,13 +20,34 @@
pub cxx: Vec<u8>,
}
+pub struct Error(crate::gen::Error);
+
/// Generate C++ bindings code from a Rust token stream. This should be a Rust
/// token stream which somewhere contains a `#[cxx::bridge] mod {}`.
pub fn generate_header_and_cc(rust_source: TokenStream, opt: Opt) -> Result<GeneratedCode, Error> {
- let syntax = syn::parse2(rust_source)?;
- match gen::generate(syntax, opt, true, true) {
- Ok((Some(header), Some(cxx))) => Ok(GeneratedCode { header, cxx }),
- Err(err) => Err(err),
+ let syntax = syn::parse2(rust_source)
+ .map_err(crate::gen::Error::from)
+ .map_err(Error)?;
+ match gen::generate(syntax, opt, true, true).map_err(Error)? {
+ (Some(header), Some(cxx)) => Ok(GeneratedCode { header, cxx }),
_ => panic!("Unexpected generation"),
}
}
+
+impl Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ Display::fmt(&self.0, f)
+ }
+}
+
+impl Debug for Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ Debug::fmt(&self.0, f)
+ }
+}
+
+impl StdError for Error {
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
+ self.0.source()
+ }
+}
diff --git a/gen/src/error.rs b/gen/src/error.rs
index 70dcb37..1cedab1 100644
--- a/gen/src/error.rs
+++ b/gen/src/error.rs
@@ -14,12 +14,9 @@
pub(crate) type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug)]
-pub enum Error {
- /// No `#[cxx::bridge]` module could be found.
+pub(crate) enum Error {
NoBridgeMod,
- /// An IO error occurred when reading Rust code.
Io(io::Error),
- /// A syntax error occurred when parsing Rust code.
Syn(syn::Error),
}
diff --git a/gen/src/mod.rs b/gen/src/mod.rs
index 320ff66..a5a3780 100644
--- a/gen/src/mod.rs
+++ b/gen/src/mod.rs
@@ -10,7 +10,7 @@
#[cfg(test)]
mod tests;
-pub use self::error::Error;
+pub(super) use self::error::Error;
use self::error::{format_err, Result};
use self::file::File;
use crate::syntax::report::Errors;