pdb-bindgen-codegen 0.1.0

Build-time discovery, PDB acquisition, and binding generation for pdb-bindgen.
Documentation
use super::policy::validate_symbol_server;
use super::{CachePolicy, ConfigError, Image, SymbolServer};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

/// Collects image configuration and builder-wide PDB acquisition policy.
///
/// The default policy has no images, permits online acquisition from Microsoft's
/// Symbol Server, and represents the cache as `OUT_DIR/pdb-bindgen/cache` without
/// reading `OUT_DIR`. Offline mode suppresses Symbol Server requests during generation;
/// it remains valid without a local PDB because the cache may satisfy the request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Builder {
    images: Vec<Image>,
    offline: bool,
    cache: CachePolicy,
    symbol_server: SymbolServer,
    source_roots: Vec<PathBuf>,
    custom_cfg_flags: BTreeSet<String>,
    pub(crate) custom_cfg_values: BTreeMap<String, BTreeSet<String>>,
}

impl Builder {
    /// Creates a builder with the documented default acquisition policy.
    #[must_use]
    pub fn new() -> Self {
        Self {
            images: Vec::new(),
            offline: false,
            cache: CachePolicy::out_dir(),
            symbol_server: SymbolServer::microsoft(),
            source_roots: Vec::new(),
            custom_cfg_flags: BTreeSet::new(),
            custom_cfg_values: BTreeMap::new(),
        }
    }

    /// Adds an explicit package-local Rust source root.
    ///
    /// Explicit roots replace the default `src` root and retain insertion order.
    /// Exact duplicate paths are ignored. No filesystem access occurs here.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::EmptySourceRoot`] when `path` is empty.
    pub fn source_root(&mut self, path: impl AsRef<Path>) -> Result<&mut Self, ConfigError> {
        let path = path.as_ref();
        if path.as_os_str().is_empty() {
            return Err(ConfigError::EmptySourceRoot);
        }
        if !self.source_roots.iter().any(|root| root == path) {
            self.source_roots.push(path.to_path_buf());
        }
        Ok(self)
    }

    /// Adds an exact custom cfg flag atom.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::InvalidCfgName`] when `name` is not one Rust cfg
    /// identifier.
    pub fn cfg_flag(&mut self, name: impl Into<String>) -> Result<&mut Self, ConfigError> {
        let name = name.into();
        validate_cfg_name(&name)?;
        self.custom_cfg_flags.insert(name);
        Ok(self)
    }

    /// Adds an exact custom cfg name-value atom.
    ///
    /// Values, including `feature` values, are retained without normalization.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::InvalidCfgName`] when `name` is not one Rust cfg
    /// identifier.
    pub fn cfg_value(
        &mut self,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<&mut Self, ConfigError> {
        let name = name.into();
        validate_cfg_name(&name)?;
        self.custom_cfg_values
            .entry(name)
            .or_default()
            .insert(value.into());
        Ok(self)
    }

    /// Adds an image while preserving insertion order.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::DuplicateImageKey`] when an existing image has the
    /// same exact source-visible key. The builder is unchanged on error.
    pub fn image(&mut self, image: Image) -> Result<&mut Self, ConfigError> {
        if self
            .images
            .iter()
            .any(|existing| existing.key() == image.key())
        {
            return Err(ConfigError::DuplicateImageKey {
                key: image.key().to_owned(),
            });
        }
        self.images.push(image);
        Ok(self)
    }

    /// Enables or disables offline acquisition policy.
    ///
    /// Enabling offline mode leaves the configured server visible but instructs
    /// generation not to contact it.
    pub fn offline(&mut self, offline: bool) -> &mut Self {
        self.offline = offline;
        self
    }

    /// Overrides the cache with an explicit directory.
    ///
    /// The path is retained without reading or creating it.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::EmptyCachePath`] when `path` is empty.
    pub fn cache_dir(&mut self, path: impl AsRef<Path>) -> Result<&mut Self, ConfigError> {
        let path = path.as_ref();
        if path.as_os_str().is_empty() {
            return Err(ConfigError::EmptyCachePath);
        }
        self.cache.set_directory(path.to_path_buf());
        Ok(self)
    }

    /// Restores the unresolved `OUT_DIR/pdb-bindgen/cache` cache policy.
    pub fn out_dir_cache(&mut self) -> &mut Self {
        self.cache.reset_out_dir();
        self
    }

    /// Overrides the Symbol Server base URL.
    ///
    /// Validation deliberately covers only invariants needed by this
    /// configuration layer: an `http://` or `https://` scheme, a nonempty
    /// authority, and no ASCII whitespace, control characters, query, or fragment.
    /// No network request is made.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::InvalidSymbolServer`] when validation fails. The
    /// builder is unchanged on error.
    pub fn symbol_server(&mut self, url: impl Into<String>) -> Result<&mut Self, ConfigError> {
        let url = url.into();
        validate_symbol_server(&url)?;
        self.symbol_server.set_custom(url);
        Ok(self)
    }

    /// Restores Microsoft's public Symbol Server.
    pub fn microsoft_symbol_server(&mut self) -> &mut Self {
        self.symbol_server.reset_microsoft();
        self
    }

    /// Disables Symbol Server acquisition.
    pub fn disable_symbol_server(&mut self) -> &mut Self {
        self.symbol_server.disable();
        self
    }

    /// Returns images in deterministic insertion order.
    #[must_use]
    pub fn images(&self) -> &[Image] {
        &self.images
    }

    /// Returns whether PDB acquisition must avoid network access.
    #[must_use]
    pub const fn is_offline(&self) -> bool {
        self.offline
    }

    /// Returns the configured cache policy.
    #[must_use]
    pub const fn cache_policy(&self) -> &CachePolicy {
        &self.cache
    }

    /// Returns the configured Symbol Server policy.
    ///
    /// A configured server is not effective while [`Builder::is_offline`] is
    /// true.
    #[must_use]
    pub const fn symbol_server_policy(&self) -> &SymbolServer {
        &self.symbol_server
    }

    /// Returns explicit source roots in insertion order.
    ///
    /// An empty iterator means discovery uses the package's `src` directory.
    #[must_use]
    pub fn source_roots(&self) -> impl ExactSizeIterator<Item = &Path> {
        self.source_roots.iter().map(PathBuf::as_path)
    }

    /// Returns exact custom cfg flags in deterministic order.
    pub fn custom_cfg_flags(&self) -> impl Iterator<Item = &str> {
        self.custom_cfg_flags.iter().map(String::as_str)
    }

    /// Returns exact custom values for one cfg name in deterministic order.
    ///
    /// An unknown name produces an empty iterator.
    pub fn custom_cfg_values(&self, name: &str) -> impl Iterator<Item = &str> {
        self.custom_cfg_values
            .get(name)
            .into_iter()
            .flat_map(|values| values.iter().map(String::as_str))
    }

    pub(crate) fn resolve_paths(&self, package: &Path) -> Self {
        let mut resolved = self.clone();
        for image in &mut resolved.images {
            image.resolve_local_pdb(package);
        }
        if let Some(path) = resolved.cache.directory().filter(|path| path.is_relative()) {
            resolved.cache.set_directory(package.join(path));
        }
        resolved
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

fn validate_cfg_name(name: &str) -> Result<(), ConfigError> {
    let valid = !name.starts_with("r#") && syn::parse_str::<syn::Ident>(name).is_ok();
    if valid {
        Ok(())
    } else {
        Err(ConfigError::InvalidCfgName {
            name: name.to_owned(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{PdbIdentity, SymbolServerErrorKind};

    const GUID_TEXT: &str = "12345678-9abc-def0-1234-56789abcdef0";

    fn identity(filename: &str) -> PdbIdentity {
        PdbIdentity::new(filename, GUID_TEXT.parse().expect("valid GUID"), 0)
            .expect("valid identity")
    }

    fn image(key: &str) -> Image {
        Image::new(key, identity("kernel.pdb")).expect("valid image")
    }

    #[test]
    fn builder_defaults_are_unresolved_and_side_effect_free() {
        let builder = Builder::new();

        assert!(builder.images().is_empty());
        assert!(!builder.is_offline());
        assert!(builder.cache_policy().is_out_dir_relative());
        assert_eq!(
            builder.cache_policy().out_dir_relative_path(),
            Some(Path::new("pdb-bindgen/cache"))
        );
        assert_eq!(builder.cache_policy().directory(), None);
        assert!(builder.symbol_server_policy().is_microsoft());
        assert_eq!(
            builder.symbol_server_policy().url(),
            Some("https://msdl.microsoft.com/download/symbols")
        );
    }

    #[test]
    fn builder_preserves_order_and_rejects_duplicate_exact_keys() {
        let mut builder = Builder::new();
        builder.image(image("kernel")).unwrap();
        builder.image(image("Kernel")).unwrap();
        let error = builder
            .image(image("kernel"))
            .expect_err("duplicate must fail");

        assert_eq!(
            error,
            ConfigError::DuplicateImageKey {
                key: "kernel".to_owned()
            }
        );
        assert_eq!(
            builder.images().iter().map(Image::key).collect::<Vec<_>>(),
            ["kernel", "Kernel"]
        );
    }

    #[test]
    fn builder_policy_can_be_overridden_disabled_and_restored() {
        let mut builder = Builder::new();
        builder.offline(true).disable_symbol_server().offline(false);
        builder.cache_dir("target/pdb-cache").unwrap();
        builder
            .symbol_server("http://symbols.example.test/store")
            .unwrap();

        assert!(!builder.is_offline());
        assert_eq!(
            builder.cache_policy().directory(),
            Some(Path::new("target/pdb-cache"))
        );
        assert_eq!(
            builder.symbol_server_policy().url(),
            Some("http://symbols.example.test/store")
        );

        builder
            .out_dir_cache()
            .microsoft_symbol_server()
            .offline(true);
        assert!(builder.cache_policy().is_out_dir_relative());
        assert!(builder.symbol_server_policy().is_microsoft());
        assert!(builder.is_offline());
    }

    #[test]
    fn invalid_policy_overrides_do_not_mutate_builder() {
        let mut builder = Builder::new();
        assert_eq!(builder.cache_dir(""), Err(ConfigError::EmptyCachePath));
        assert!(builder.cache_policy().is_out_dir_relative());

        let invalid_servers = [
            ("symbols.example.test", SymbolServerErrorKind::Scheme),
            ("https://", SymbolServerErrorKind::MissingAuthority),
            ("https:///symbols", SymbolServerErrorKind::MissingAuthority),
            (
                "https://example.test/a b",
                SymbolServerErrorKind::InvalidCharacter,
            ),
            (
                "https://example.test/path?q",
                SymbolServerErrorKind::InvalidCharacter,
            ),
        ];
        for (url, reason) in invalid_servers {
            assert_eq!(
                builder.symbol_server(url),
                Err(ConfigError::InvalidSymbolServer {
                    url: url.to_owned(),
                    reason,
                })
            );
            assert!(builder.symbol_server_policy().is_microsoft());
        }
    }

    #[test]
    fn resolving_paths_uses_the_package_root_without_filesystem_access() {
        let package = Path::new("/package");
        let mut builder = Builder::new();
        builder
            .image(image("relative").local_pdb("symbols/fixture.pdb").unwrap())
            .unwrap();
        builder
            .image(image("absolute").local_pdb("/symbols/fixture.pdb").unwrap())
            .unwrap();
        builder.cache_dir("cache").unwrap();
        let resolved = builder.resolve_paths(package);
        assert_eq!(
            resolved.images()[0].local_pdb_path(),
            Some(Path::new("/package/symbols/fixture.pdb"))
        );
        assert_eq!(
            resolved.images()[1].local_pdb_path(),
            Some(Path::new("/symbols/fixture.pdb"))
        );
        assert_eq!(
            resolved.cache_policy().directory(),
            Some(Path::new("/package/cache"))
        );
        assert!(builder.cache_policy().directory().unwrap().is_relative());
        assert!(
            Builder::new()
                .resolve_paths(package)
                .cache_policy()
                .is_out_dir_relative()
        );
    }
}