use crate::Builder;
use std::collections::{BTreeMap, BTreeSet};
use std::error::Error as StdError;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GenerateErrorKind {
Environment,
CargoDirective,
Discovery,
Acquisition,
Pdb,
Codegen,
Output,
}
#[derive(Debug)]
pub struct GenerateError {
kind: GenerateErrorKind,
image: Option<String>,
source: Box<GenerateSource>,
}
#[derive(Debug)]
enum GenerateSource {
Environment {
name: &'static str,
reason: &'static str,
},
CargoDirective(std::io::Error),
Discovery(crate::discovery::Diagnostic),
Acquisition(crate::acquisition::Error),
Pdb(crate::pdb::error::Error),
Codegen(crate::codegen::Error),
Output(crate::output::OutputError),
}
impl GenerateError {
#[must_use]
pub const fn kind(&self) -> GenerateErrorKind {
self.kind
}
#[must_use]
pub fn image(&self) -> Option<&str> {
self.image.as_deref()
}
fn environment(name: &'static str, reason: &'static str) -> Self {
Self {
kind: GenerateErrorKind::Environment,
image: None,
source: Box::new(GenerateSource::Environment { name, reason }),
}
}
fn with_image(kind: GenerateErrorKind, image: &str, source: GenerateSource) -> Self {
Self {
kind,
image: Some(image.to_owned()),
source: Box::new(source),
}
}
fn codegen(source: crate::codegen::Error) -> Self {
Self {
kind: GenerateErrorKind::Codegen,
image: source.image().map(str::to_owned),
source: Box::new(GenerateSource::Codegen(source)),
}
}
}
impl fmt::Display for GenerateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &*self.source {
GenerateSource::Environment { name, reason } => {
write!(f, "Cargo environment {name} {reason}")
}
GenerateSource::CargoDirective(_) => f.write_str("cannot write Cargo rerun directive"),
GenerateSource::Discovery(source) => write!(f, "source discovery failed: {source}"),
GenerateSource::Acquisition(source) => write!(
f,
"PDB acquisition failed for image {}: {source}",
self.image
.as_deref()
.expect("acquisition errors have an image")
),
GenerateSource::Pdb(source) => write!(
f,
"PDB normalization failed for image {}: {source}",
self.image.as_deref().expect("PDB errors have an image")
),
GenerateSource::Codegen(source) => write!(f, "binding generation failed: {source}"),
GenerateSource::Output(source) => {
write!(f, "generated output publication failed: {source}")
}
}
}
}
impl StdError for GenerateError {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match &*self.source {
GenerateSource::Environment { .. } => None,
GenerateSource::CargoDirective(source) => Some(source),
GenerateSource::Discovery(source) => Some(source),
GenerateSource::Acquisition(source) => Some(source),
GenerateSource::Pdb(source) => Some(source),
GenerateSource::Codegen(source) => Some(source),
GenerateSource::Output(source) => Some(source),
}
}
}
impl Builder {
pub fn generate(&self) -> Result<(), GenerateError> {
let environment = std::env::vars_os().collect::<BTreeMap<_, _>>();
let package = required_path(&environment, "CARGO_MANIFEST_DIR")?;
let out_dir = required_path(&environment, "OUT_DIR")?;
let builder = self.resolve_paths(&package);
let roots = effective_roots(&package, &builder);
let discovery_environment = environment.into_iter().collect::<Vec<_>>();
let discovery =
crate::discovery::discover(&package, &builder, discovery_environment.clone()).map_err(
|source| GenerateError {
kind: GenerateErrorKind::Discovery,
image: None,
source: Box::new(GenerateSource::Discovery(source)),
},
)?;
let images = discovery
.resolved
.iter()
.map(|item| item.image.image.clone())
.collect::<BTreeSet<_>>();
let mut directives = BTreeSet::new();
directives.insert(package.join("Cargo.toml"));
directives.extend(roots);
for image in &images {
let configured = builder
.images()
.iter()
.find(|candidate| candidate.key() == image)
.expect("discovery validates image keys");
if let Some(path) = configured.local_pdb_path() {
directives.insert(path.to_path_buf());
}
}
emit_directives(directives, &discovery_environment)?;
let mut databases = BTreeMap::new();
for image in images {
let configured = builder
.images()
.iter()
.find(|candidate| candidate.key() == image)
.expect("discovery validates image keys");
let acquired =
crate::acquisition::acquire(&builder, configured, &out_dir).map_err(|source| {
GenerateError::with_image(
GenerateErrorKind::Acquisition,
&image,
GenerateSource::Acquisition(source),
)
})?;
let database = crate::pdb::read(&acquired.path).map_err(|source| {
GenerateError::with_image(
GenerateErrorKind::Pdb,
&image,
GenerateSource::Pdb(source),
)
})?;
databases.insert(image, database);
}
let generated = crate::codegen::generate(&discovery.resolved, &databases)
.map_err(GenerateError::codegen)?;
generated.publish(&out_dir).map_err(|source| GenerateError {
kind: GenerateErrorKind::Output,
image: None,
source: Box::new(GenerateSource::Output(source)),
})
}
}
fn required_path(
environment: &BTreeMap<OsString, OsString>,
name: &'static str,
) -> Result<PathBuf, GenerateError> {
let value = environment
.get(OsStr::new(name))
.ok_or_else(|| GenerateError::environment(name, "is missing"))?;
let value = value
.to_str()
.ok_or_else(|| GenerateError::environment(name, "is not UTF-8"))?;
Ok(PathBuf::from(value))
}
fn effective_roots(package: &Path, builder: &Builder) -> BTreeSet<PathBuf> {
let roots = builder
.source_roots()
.map(Path::to_path_buf)
.collect::<Vec<_>>();
if roots.is_empty() {
[package.join("src")].into_iter().collect()
} else {
roots.into_iter().map(|root| package.join(root)).collect()
}
}
fn emit_directives(
paths: BTreeSet<PathBuf>,
environment: &[(OsString, OsString)],
) -> Result<(), GenerateError> {
let mut output = std::io::stdout().lock();
emit_directives_to(&mut output, paths, environment)
}
fn emit_directives_to(
output: &mut impl std::io::Write,
paths: BTreeSet<PathBuf>,
environment: &[(OsString, OsString)],
) -> Result<(), GenerateError> {
for path in paths {
directive(output, "cargo::rerun-if-changed", &path)?;
}
let names = environment
.iter()
.filter_map(|(name, _)| name.to_str())
.filter(|name| name.starts_with("CARGO_CFG_") || name.starts_with("CARGO_FEATURE_"))
.collect::<BTreeSet<_>>();
for name in names {
directive(output, "cargo::rerun-if-env-changed", Path::new(name))?;
}
Ok(())
}
fn directive(
output: &mut impl std::io::Write,
prefix: &str,
value: &Path,
) -> Result<(), GenerateError> {
let value = value.to_str().ok_or_else(|| GenerateError {
kind: GenerateErrorKind::CargoDirective,
image: None,
source: Box::new(GenerateSource::CargoDirective(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Cargo directive text is not UTF-8",
))),
})?;
writeln!(output, "{prefix}={value}").map_err(|source| GenerateError {
kind: GenerateErrorKind::CargoDirective,
image: None,
source: Box::new(GenerateSource::CargoDirective(source)),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_required_environment_is_typed() {
let error = required_path(&BTreeMap::new(), "OUT_DIR").unwrap_err();
assert_eq!(error.kind(), GenerateErrorKind::Environment);
assert_eq!(error.image(), None);
assert!(error.to_string().contains("OUT_DIR is missing"));
}
#[cfg(unix)]
#[test]
fn non_utf8_environment_is_typed() {
use std::os::unix::ffi::OsStringExt as _;
let mut environment = BTreeMap::new();
environment.insert(OsString::from("OUT_DIR"), OsString::from_vec(vec![0xff]));
let error = required_path(&environment, "OUT_DIR").unwrap_err();
assert_eq!(error.kind(), GenerateErrorKind::Environment);
assert!(error.to_string().contains("not UTF-8"));
}
#[test]
fn directives_are_sorted_and_deduplicated() {
let paths = [PathBuf::from("z"), PathBuf::from("a"), PathBuf::from("a")]
.into_iter()
.collect();
let environment = vec![
(OsString::from("CARGO_FEATURE_Z"), OsString::new()),
(OsString::from("IGNORED"), OsString::new()),
(OsString::from("CARGO_CFG_A"), OsString::new()),
(OsString::from("CARGO_CFG_A"), OsString::new()),
];
let mut output = Vec::new();
emit_directives_to(&mut output, paths, &environment).unwrap();
assert_eq!(
String::from_utf8(output).unwrap(),
"cargo::rerun-if-changed=a\ncargo::rerun-if-changed=z\ncargo::rerun-if-env-changed=CARGO_CFG_A\ncargo::rerun-if-env-changed=CARGO_FEATURE_Z\n"
);
}
#[test]
fn writer_failure_is_a_cargo_directive_error() {
struct Broken;
impl std::io::Write for Broken {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("broken"))
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let error =
emit_directives_to(&mut Broken, [PathBuf::from("a")].into_iter().collect(), &[])
.unwrap_err();
assert_eq!(error.kind(), GenerateErrorKind::CargoDirective);
assert!(error.source().is_some());
}
#[cfg(unix)]
#[test]
fn non_utf8_directive_is_a_cargo_directive_error() {
use std::os::unix::ffi::OsStringExt as _;
let error = emit_directives_to(
&mut Vec::new(),
[PathBuf::from(OsString::from_vec(vec![0xff]))]
.into_iter()
.collect(),
&[],
)
.unwrap_err();
assert_eq!(error.kind(), GenerateErrorKind::CargoDirective);
assert!(error.source().is_some());
}
#[test]
fn image_context_is_displayed_and_inspectable() {
let error = GenerateError::with_image(
GenerateErrorKind::Pdb,
"primary",
GenerateSource::Pdb(crate::pdb::error::Error::Parse {
operation: "read",
detail: "bad".into(),
}),
);
assert_eq!(error.image(), Some("primary"));
assert!(error.to_string().contains("image primary"));
assert!(error.source().is_some());
}
#[test]
fn codegen_errors_preserve_item_image_and_source_chain() {
let error = GenerateError::codegen(crate::codegen::Error::context(
"primary".into(),
crate::codegen::Error::KindMismatch {
pdb_name: "R".into(),
expected: "struct",
actual: "union",
},
));
assert_eq!(error.kind(), GenerateErrorKind::Codegen);
assert_eq!(error.image(), Some("primary"));
let source = error.source().expect("codegen source");
assert!(source.source().is_some());
}
}