public_api/
lib.rs

1//! This library gives you the public API of a library crate, in the form of a
2//! list of public items in the crate. Public items are items that other crates
3//! can use. Diffing is also supported.
4//!
5//! If you want a convenient CLI for this library, you should use [cargo
6//! public-api](https://github.com/cargo-public-api/cargo-public-api).
7//!
8//! As input to the library, a special output format from `rustdoc +nightly` is
9//! used, which goes by the name **rustdoc JSON**. Currently, only the nightly
10//! toolchain can build **rustdoc JSON**.
11//!
12//! You use the [`rustdoc-json`](https://crates.io/crates/rustdoc_json) library
13//! to programmatically build rustdoc JSON. See below for example code. To
14//! manually build rustdoc JSON you would typically do something like this:
15//! ```sh
16//! cargo +nightly rustdoc -- -Z unstable-options --output-format json
17//! ```
18//!
19//! # Examples
20//!
21//! The two main use cases are listing the public API and diffing different
22//! versions of the same public APIs.
23//!
24//! ## List all public items of a crate (the public API)
25//! ```no_run
26#![doc = include_str!("../examples/list_public_api.rs")]
27//! ```
28//!
29//! ## Diff two versions of a public API
30//! ```no_run
31#![doc = include_str!("../examples/diff_public_api.rs")]
32//! ```
33
34// deny in CI, only warn here
35#![warn(clippy::all, missing_docs)]
36
37mod crate_wrapper;
38mod error;
39mod intermediate_public_item;
40mod item_processor;
41mod nameable_item;
42mod path_component;
43mod public_item;
44mod render;
45pub mod tokens;
46
47pub mod diff;
48
49use std::path::PathBuf;
50
51// Documented at the definition site so cargo doc picks it up
52pub use error::{Error, Result};
53
54// Documented at the definition site so cargo doc picks it up
55pub use public_item::PublicItem;
56
57/// This constant defines the minimum version of nightly that is required in
58/// order for the rustdoc JSON output to be parsable by this library. Note that
59/// this library is implemented with stable Rust. But the rustdoc JSON that this
60/// library parses can currently only be produced by nightly.
61///
62/// The rustdoc JSON format is still changing, so every now and then we update
63/// this library to support the latest format. If you use this version of
64/// nightly or later, you should be fine.
65pub const MINIMUM_NIGHTLY_RUST_VERSION: &str = "nightly-2025-08-02";
66// End-marker for scripts/release-helper/src/bin/update-version-info/main.rs
67
68/// See [`Builder`] method docs for what each field means.
69#[derive(Copy, Clone, Debug)]
70struct BuilderOptions {
71    sorted: bool,
72    debug_sorting: bool,
73    omit_blanket_impls: bool,
74    omit_auto_trait_impls: bool,
75    omit_auto_derived_impls: bool,
76}
77
78/// Builds [`PublicApi`]s. See the [top level][`crate`] module docs for example
79/// code.
80#[derive(Debug, Clone)]
81pub struct Builder {
82    rustdoc_json: PathBuf,
83    options: BuilderOptions,
84}
85
86impl Builder {
87    /// Create a new [`PublicApi`] builder from a rustdoc JSON file. See the
88    /// [top level][`crate`] module docs for example code.
89    #[must_use]
90    pub fn from_rustdoc_json(path: impl Into<PathBuf>) -> Self {
91        let options = BuilderOptions {
92            sorted: true,
93            debug_sorting: false,
94            omit_blanket_impls: false,
95            omit_auto_trait_impls: false,
96            omit_auto_derived_impls: false,
97        };
98        Self {
99            rustdoc_json: path.into(),
100            options,
101        }
102    }
103
104    /// If `true`, items will be sorted before being returned. If you will pass
105    /// on the return value to [`diff::PublicApiDiff::between`], it is
106    /// currently unnecessary to sort first, because the sorting will be
107    /// performed/ensured inside of that function.
108    ///
109    /// The default value is `true`, because usually the performance impact is
110    /// negligible, and is is generally more practical to work with sorted data.
111    #[must_use]
112    pub fn sorted(mut self, sorted: bool) -> Self {
113        self.options.sorted = sorted;
114        self
115    }
116
117    /// If `true`, item paths include the so called "sorting prefix" that makes
118    /// them grouped in a nice way. Only intended for debugging this library.
119    ///
120    /// The default value is `false`
121    #[must_use]
122    pub fn debug_sorting(mut self, debug_sorting: bool) -> Self {
123        self.options.debug_sorting = debug_sorting;
124        self
125    }
126
127    /// If `true`, items that belongs to Blanket Implementations are omitted
128    /// from the output. This makes the output less noisy, at the cost of not
129    /// fully describing the public API.
130    ///
131    /// Examples of Blanket Implementations: `impl<T> Any for T`, `impl<T>
132    /// Borrow<T> for T`, and `impl<T, U> Into<U> for T where U: From<T>`
133    ///
134    /// The default value is `false` so that the listed public API is complete
135    /// by default.
136    #[must_use]
137    pub fn omit_blanket_impls(mut self, omit_blanket_impls: bool) -> Self {
138        self.options.omit_blanket_impls = omit_blanket_impls;
139        self
140    }
141
142    /// If `true`, items that belongs to Auto Trait Implementations are omitted
143    /// from the output. This makes the output less noisy, at the cost of not
144    /// fully describing the public API.
145    ///
146    /// Examples of Auto Trait Implementations: `impl Send for Foo`, `impl Sync
147    /// for Foo`, and `impl Unpin for Foo`
148    ///
149    /// The default value is `false` so that the listed public API is complete
150    /// by default.
151    #[must_use]
152    pub fn omit_auto_trait_impls(mut self, omit_auto_trait_impls: bool) -> Self {
153        self.options.omit_auto_trait_impls = omit_auto_trait_impls;
154        self
155    }
156
157    /// If `true`, items that belongs to automatically derived implementations
158    /// (`Clone`, `Debug`, `Eq`, etc) are omitted from the output. This makes
159    /// the output less noisy, at the cost of not fully describing the public
160    /// API.
161    ///
162    /// The default value is `false` so that the listed public API is complete
163    /// by default.
164    #[must_use]
165    pub fn omit_auto_derived_impls(mut self, omit_auto_derived_impls: bool) -> Self {
166        self.options.omit_auto_derived_impls = omit_auto_derived_impls;
167        self
168    }
169
170    /// Builds [`PublicApi`]. See the [top level][`crate`] module docs for
171    /// example code.
172    ///
173    /// # Errors
174    ///
175    /// E.g. if the [JSON](Builder::from_rustdoc_json) is invalid or if the file
176    /// can't be read.
177    pub fn build(self) -> Result<PublicApi> {
178        from_rustdoc_json_str(std::fs::read_to_string(self.rustdoc_json)?, self.options)
179    }
180}
181
182/// The public API of a crate
183///
184/// Create an instance with [`Builder`].
185///
186/// ## Rendering the items
187///
188/// To render the items in the public API you can iterate over the [items](PublicItem).
189///
190/// You get the `rustdoc_json_str` in the example below as explained in the [crate] documentation, either via
191/// [`rustdoc_json`](https://crates.io/crates/rustdoc_json) or by calling `cargo rustdoc` yourself.
192///
193/// ```no_run
194/// use public_api::PublicApi;
195/// use std::path::PathBuf;
196///
197/// # let rustdoc_json: PathBuf = todo!();
198/// // Gather the rustdoc content as described in this crates top-level documentation.
199/// let public_api = public_api::Builder::from_rustdoc_json(&rustdoc_json).build()?;
200///
201/// for public_item in public_api.items() {
202///     // here we print the items to stdout, we could also write to a string or a file.
203///     println!("{}", public_item);
204/// }
205///
206/// // If you want all items of the public API in a single big multi-line String then
207/// // you can do like this:
208/// let public_api_string = public_api.to_string();
209/// # Ok::<(), Box<dyn std::error::Error>>(())
210/// ```
211#[derive(Debug)]
212#[non_exhaustive] // More fields might be added in the future
213pub struct PublicApi {
214    /// The items that constitutes the public API. An "item" is for example a
215    /// function, a struct, a struct field, an enum, an enum variant, a module,
216    /// etc...
217    pub(crate) items: Vec<PublicItem>,
218
219    /// See [`Self::missing_item_ids()`]
220    pub(crate) missing_item_ids: Vec<u32>,
221}
222
223impl PublicApi {
224    /// Returns an iterator over all public items in the public API
225    pub fn items(&self) -> impl Iterator<Item = &'_ PublicItem> {
226        self.items.iter()
227    }
228
229    /// Like [`Self::items()`], but ownership of all `PublicItem`s are
230    /// transferred to the caller.
231    pub fn into_items(self) -> impl Iterator<Item = PublicItem> {
232        self.items.into_iter()
233    }
234
235    /// The rustdoc JSON IDs of missing but referenced items. Intended for use
236    /// with `--verbose` flags or similar.
237    ///
238    /// In some cases, a public item might be referenced from another public
239    /// item (e.g. a `mod`), but is missing from the rustdoc JSON file. This
240    /// occurs for example in the case of re-exports of external modules (see
241    /// <https://github.com/cargo-public-api/cargo-public-api/issues/103>). The entries
242    /// in this Vec are what IDs that could not be found.
243    ///
244    /// The exact format of IDs are to be considered an implementation detail
245    /// and must not be be relied on.
246    pub fn missing_item_ids(&self) -> impl Iterator<Item = &u32> {
247        self.missing_item_ids.iter()
248    }
249
250    /// Assert that the public API matches the snapshot at `snapshot_path`. The
251    /// function will panic with a helpful diff if the public API does not
252    /// match.
253    ///
254    /// If the env var `UPDATE_SNAPSHOTS` is set to `1`, `yes` or `true` then
255    /// the public API will be written to `snapshot_file` instead of being
256    /// asserted to match.
257    #[cfg(feature = "snapshot-testing")]
258    #[track_caller]
259    pub fn assert_eq_or_update(&self, snapshot_path: impl AsRef<std::path::Path>) {
260        snapshot_testing::assert_eq_or_update(self.to_string(), snapshot_path);
261    }
262}
263
264impl std::fmt::Display for PublicApi {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        for item in self.items() {
267            writeln!(f, "{item}")?;
268        }
269        Ok(())
270    }
271}
272
273fn from_rustdoc_json_str(
274    rustdoc_json_str: impl AsRef<str>,
275    options: BuilderOptions,
276) -> Result<PublicApi> {
277    let crate_ = deserialize_without_recursion_limit(rustdoc_json_str.as_ref())?;
278
279    let mut public_api = item_processor::public_api_in_crate(&crate_, options);
280
281    if options.sorted {
282        public_api.items.sort_by(PublicItem::grouping_cmp);
283    }
284
285    Ok(public_api)
286}
287
288/// Helper to deserialize the JSON with `serde_json`, but with the recursion
289/// limit disabled. Otherwise we hit the recursion limit on crates such as
290/// `diesel`.
291fn deserialize_without_recursion_limit(rustdoc_json_str: &str) -> Result<rustdoc_types::Crate> {
292    let mut deserializer = serde_json::Deserializer::from_str(rustdoc_json_str);
293    deserializer.disable_recursion_limit();
294    Ok(serde::de::Deserialize::deserialize(&mut deserializer)?)
295}