Skip to main content

pdb_bindgen_codegen/config/
builder.rs

1use super::policy::validate_symbol_server;
2use super::{CachePolicy, ConfigError, Image, SymbolServer};
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Path, PathBuf};
5
6/// Collects image configuration and builder-wide PDB acquisition policy.
7///
8/// The default policy has no images, permits online acquisition from Microsoft's
9/// Symbol Server, and represents the cache as `OUT_DIR/pdb-bindgen/cache` without
10/// reading `OUT_DIR`. Offline mode suppresses Symbol Server requests during generation;
11/// it remains valid without a local PDB because the cache may satisfy the request.
12#[derive(Clone, Debug, Eq, PartialEq)]
13pub struct Builder {
14    images: Vec<Image>,
15    offline: bool,
16    cache: CachePolicy,
17    symbol_server: SymbolServer,
18    source_roots: Vec<PathBuf>,
19    custom_cfg_flags: BTreeSet<String>,
20    pub(crate) custom_cfg_values: BTreeMap<String, BTreeSet<String>>,
21}
22
23impl Builder {
24    /// Creates a builder with the documented default acquisition policy.
25    #[must_use]
26    pub fn new() -> Self {
27        Self {
28            images: Vec::new(),
29            offline: false,
30            cache: CachePolicy::out_dir(),
31            symbol_server: SymbolServer::microsoft(),
32            source_roots: Vec::new(),
33            custom_cfg_flags: BTreeSet::new(),
34            custom_cfg_values: BTreeMap::new(),
35        }
36    }
37
38    /// Adds an explicit package-local Rust source root.
39    ///
40    /// Explicit roots replace the default `src` root and retain insertion order.
41    /// Exact duplicate paths are ignored. No filesystem access occurs here.
42    ///
43    /// # Errors
44    ///
45    /// Returns [`ConfigError::EmptySourceRoot`] when `path` is empty.
46    pub fn source_root(&mut self, path: impl AsRef<Path>) -> Result<&mut Self, ConfigError> {
47        let path = path.as_ref();
48        if path.as_os_str().is_empty() {
49            return Err(ConfigError::EmptySourceRoot);
50        }
51        if !self.source_roots.iter().any(|root| root == path) {
52            self.source_roots.push(path.to_path_buf());
53        }
54        Ok(self)
55    }
56
57    /// Adds an exact custom cfg flag atom.
58    ///
59    /// # Errors
60    ///
61    /// Returns [`ConfigError::InvalidCfgName`] when `name` is not one Rust cfg
62    /// identifier.
63    pub fn cfg_flag(&mut self, name: impl Into<String>) -> Result<&mut Self, ConfigError> {
64        let name = name.into();
65        validate_cfg_name(&name)?;
66        self.custom_cfg_flags.insert(name);
67        Ok(self)
68    }
69
70    /// Adds an exact custom cfg name-value atom.
71    ///
72    /// Values, including `feature` values, are retained without normalization.
73    ///
74    /// # Errors
75    ///
76    /// Returns [`ConfigError::InvalidCfgName`] when `name` is not one Rust cfg
77    /// identifier.
78    pub fn cfg_value(
79        &mut self,
80        name: impl Into<String>,
81        value: impl Into<String>,
82    ) -> Result<&mut Self, ConfigError> {
83        let name = name.into();
84        validate_cfg_name(&name)?;
85        self.custom_cfg_values
86            .entry(name)
87            .or_default()
88            .insert(value.into());
89        Ok(self)
90    }
91
92    /// Adds an image while preserving insertion order.
93    ///
94    /// # Errors
95    ///
96    /// Returns [`ConfigError::DuplicateImageKey`] when an existing image has the
97    /// same exact source-visible key. The builder is unchanged on error.
98    pub fn image(&mut self, image: Image) -> Result<&mut Self, ConfigError> {
99        if self
100            .images
101            .iter()
102            .any(|existing| existing.key() == image.key())
103        {
104            return Err(ConfigError::DuplicateImageKey {
105                key: image.key().to_owned(),
106            });
107        }
108        self.images.push(image);
109        Ok(self)
110    }
111
112    /// Enables or disables offline acquisition policy.
113    ///
114    /// Enabling offline mode leaves the configured server visible but instructs
115    /// generation not to contact it.
116    pub fn offline(&mut self, offline: bool) -> &mut Self {
117        self.offline = offline;
118        self
119    }
120
121    /// Overrides the cache with an explicit directory.
122    ///
123    /// The path is retained without reading or creating it.
124    ///
125    /// # Errors
126    ///
127    /// Returns [`ConfigError::EmptyCachePath`] when `path` is empty.
128    pub fn cache_dir(&mut self, path: impl AsRef<Path>) -> Result<&mut Self, ConfigError> {
129        let path = path.as_ref();
130        if path.as_os_str().is_empty() {
131            return Err(ConfigError::EmptyCachePath);
132        }
133        self.cache.set_directory(path.to_path_buf());
134        Ok(self)
135    }
136
137    /// Restores the unresolved `OUT_DIR/pdb-bindgen/cache` cache policy.
138    pub fn out_dir_cache(&mut self) -> &mut Self {
139        self.cache.reset_out_dir();
140        self
141    }
142
143    /// Overrides the Symbol Server base URL.
144    ///
145    /// Validation deliberately covers only invariants needed by this
146    /// configuration layer: an `http://` or `https://` scheme, a nonempty
147    /// authority, and no ASCII whitespace, control characters, query, or fragment.
148    /// No network request is made.
149    ///
150    /// # Errors
151    ///
152    /// Returns [`ConfigError::InvalidSymbolServer`] when validation fails. The
153    /// builder is unchanged on error.
154    pub fn symbol_server(&mut self, url: impl Into<String>) -> Result<&mut Self, ConfigError> {
155        let url = url.into();
156        validate_symbol_server(&url)?;
157        self.symbol_server.set_custom(url);
158        Ok(self)
159    }
160
161    /// Restores Microsoft's public Symbol Server.
162    pub fn microsoft_symbol_server(&mut self) -> &mut Self {
163        self.symbol_server.reset_microsoft();
164        self
165    }
166
167    /// Disables Symbol Server acquisition.
168    pub fn disable_symbol_server(&mut self) -> &mut Self {
169        self.symbol_server.disable();
170        self
171    }
172
173    /// Returns images in deterministic insertion order.
174    #[must_use]
175    pub fn images(&self) -> &[Image] {
176        &self.images
177    }
178
179    /// Returns whether PDB acquisition must avoid network access.
180    #[must_use]
181    pub const fn is_offline(&self) -> bool {
182        self.offline
183    }
184
185    /// Returns the configured cache policy.
186    #[must_use]
187    pub const fn cache_policy(&self) -> &CachePolicy {
188        &self.cache
189    }
190
191    /// Returns the configured Symbol Server policy.
192    ///
193    /// A configured server is not effective while [`Builder::is_offline`] is
194    /// true.
195    #[must_use]
196    pub const fn symbol_server_policy(&self) -> &SymbolServer {
197        &self.symbol_server
198    }
199
200    /// Returns explicit source roots in insertion order.
201    ///
202    /// An empty iterator means discovery uses the package's `src` directory.
203    #[must_use]
204    pub fn source_roots(&self) -> impl ExactSizeIterator<Item = &Path> {
205        self.source_roots.iter().map(PathBuf::as_path)
206    }
207
208    /// Returns exact custom cfg flags in deterministic order.
209    pub fn custom_cfg_flags(&self) -> impl Iterator<Item = &str> {
210        self.custom_cfg_flags.iter().map(String::as_str)
211    }
212
213    /// Returns exact custom values for one cfg name in deterministic order.
214    ///
215    /// An unknown name produces an empty iterator.
216    pub fn custom_cfg_values(&self, name: &str) -> impl Iterator<Item = &str> {
217        self.custom_cfg_values
218            .get(name)
219            .into_iter()
220            .flat_map(|values| values.iter().map(String::as_str))
221    }
222
223    pub(crate) fn resolve_paths(&self, package: &Path) -> Self {
224        let mut resolved = self.clone();
225        for image in &mut resolved.images {
226            image.resolve_local_pdb(package);
227        }
228        if let Some(path) = resolved.cache.directory().filter(|path| path.is_relative()) {
229            resolved.cache.set_directory(package.join(path));
230        }
231        resolved
232    }
233}
234
235impl Default for Builder {
236    fn default() -> Self {
237        Self::new()
238    }
239}
240
241fn validate_cfg_name(name: &str) -> Result<(), ConfigError> {
242    let valid = !name.starts_with("r#") && syn::parse_str::<syn::Ident>(name).is_ok();
243    if valid {
244        Ok(())
245    } else {
246        Err(ConfigError::InvalidCfgName {
247            name: name.to_owned(),
248        })
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use crate::{PdbIdentity, SymbolServerErrorKind};
256
257    const GUID_TEXT: &str = "12345678-9abc-def0-1234-56789abcdef0";
258
259    fn identity(filename: &str) -> PdbIdentity {
260        PdbIdentity::new(filename, GUID_TEXT.parse().expect("valid GUID"), 0)
261            .expect("valid identity")
262    }
263
264    fn image(key: &str) -> Image {
265        Image::new(key, identity("kernel.pdb")).expect("valid image")
266    }
267
268    #[test]
269    fn builder_defaults_are_unresolved_and_side_effect_free() {
270        let builder = Builder::new();
271
272        assert!(builder.images().is_empty());
273        assert!(!builder.is_offline());
274        assert!(builder.cache_policy().is_out_dir_relative());
275        assert_eq!(
276            builder.cache_policy().out_dir_relative_path(),
277            Some(Path::new("pdb-bindgen/cache"))
278        );
279        assert_eq!(builder.cache_policy().directory(), None);
280        assert!(builder.symbol_server_policy().is_microsoft());
281        assert_eq!(
282            builder.symbol_server_policy().url(),
283            Some("https://msdl.microsoft.com/download/symbols")
284        );
285    }
286
287    #[test]
288    fn builder_preserves_order_and_rejects_duplicate_exact_keys() {
289        let mut builder = Builder::new();
290        builder.image(image("kernel")).unwrap();
291        builder.image(image("Kernel")).unwrap();
292        let error = builder
293            .image(image("kernel"))
294            .expect_err("duplicate must fail");
295
296        assert_eq!(
297            error,
298            ConfigError::DuplicateImageKey {
299                key: "kernel".to_owned()
300            }
301        );
302        assert_eq!(
303            builder.images().iter().map(Image::key).collect::<Vec<_>>(),
304            ["kernel", "Kernel"]
305        );
306    }
307
308    #[test]
309    fn builder_policy_can_be_overridden_disabled_and_restored() {
310        let mut builder = Builder::new();
311        builder.offline(true).disable_symbol_server().offline(false);
312        builder.cache_dir("target/pdb-cache").unwrap();
313        builder
314            .symbol_server("http://symbols.example.test/store")
315            .unwrap();
316
317        assert!(!builder.is_offline());
318        assert_eq!(
319            builder.cache_policy().directory(),
320            Some(Path::new("target/pdb-cache"))
321        );
322        assert_eq!(
323            builder.symbol_server_policy().url(),
324            Some("http://symbols.example.test/store")
325        );
326
327        builder
328            .out_dir_cache()
329            .microsoft_symbol_server()
330            .offline(true);
331        assert!(builder.cache_policy().is_out_dir_relative());
332        assert!(builder.symbol_server_policy().is_microsoft());
333        assert!(builder.is_offline());
334    }
335
336    #[test]
337    fn invalid_policy_overrides_do_not_mutate_builder() {
338        let mut builder = Builder::new();
339        assert_eq!(builder.cache_dir(""), Err(ConfigError::EmptyCachePath));
340        assert!(builder.cache_policy().is_out_dir_relative());
341
342        let invalid_servers = [
343            ("symbols.example.test", SymbolServerErrorKind::Scheme),
344            ("https://", SymbolServerErrorKind::MissingAuthority),
345            ("https:///symbols", SymbolServerErrorKind::MissingAuthority),
346            (
347                "https://example.test/a b",
348                SymbolServerErrorKind::InvalidCharacter,
349            ),
350            (
351                "https://example.test/path?q",
352                SymbolServerErrorKind::InvalidCharacter,
353            ),
354        ];
355        for (url, reason) in invalid_servers {
356            assert_eq!(
357                builder.symbol_server(url),
358                Err(ConfigError::InvalidSymbolServer {
359                    url: url.to_owned(),
360                    reason,
361                })
362            );
363            assert!(builder.symbol_server_policy().is_microsoft());
364        }
365    }
366
367    #[test]
368    fn resolving_paths_uses_the_package_root_without_filesystem_access() {
369        let package = Path::new("/package");
370        let mut builder = Builder::new();
371        builder
372            .image(image("relative").local_pdb("symbols/fixture.pdb").unwrap())
373            .unwrap();
374        builder
375            .image(image("absolute").local_pdb("/symbols/fixture.pdb").unwrap())
376            .unwrap();
377        builder.cache_dir("cache").unwrap();
378        let resolved = builder.resolve_paths(package);
379        assert_eq!(
380            resolved.images()[0].local_pdb_path(),
381            Some(Path::new("/package/symbols/fixture.pdb"))
382        );
383        assert_eq!(
384            resolved.images()[1].local_pdb_path(),
385            Some(Path::new("/symbols/fixture.pdb"))
386        );
387        assert_eq!(
388            resolved.cache_policy().directory(),
389            Some(Path::new("/package/cache"))
390        );
391        assert!(builder.cache_policy().directory().unwrap().is_relative());
392        assert!(
393            Builder::new()
394                .resolve_paths(package)
395                .cache_policy()
396                .is_out_dir_relative()
397        );
398    }
399}