rustdoc_json_types/lib.rs
1//! Rustdoc's JSON output interface
2//!
3//! These types are the public API exposed through the `--output-format json` flag. The [`Crate`]
4//! struct is the root of the JSON blob and all other items are contained within.
5//!
6//! We expose a `rustc-hash` feature that is disabled by default. This feature switches the
7//! [`std::collections::HashMap`] for [`rustc_hash::FxHashMap`] to improve the performance of said
8//! `HashMap` in specific situations.
9//!
10//! `cargo-semver-checks` for example, saw a [-3% improvement][1] when benchmarking using the
11//! `aws_sdk_ec2` JSON output (~500MB of JSON). As always, we recommend measuring the impact before
12//! turning this feature on, as [`FxHashMap`][2] only concerns itself with hash speed, and may
13//! increase the number of collisions.
14//!
15//! [1]: https://rust-lang.zulipchat.com/#narrow/channel/266220-t-rustdoc/topic/rustc-hash.20and.20performance.20of.20rustdoc-types/near/474855731
16//! [2]: https://crates.io/crates/rustc-hash
17
18#[cfg(not(feature = "rustc-hash"))]
19use std::collections::HashMap;
20use std::path::PathBuf;
21
22#[cfg(feature = "rustc-hash")]
23use rustc_hash::FxHashMap as HashMap;
24use serde_derive::{Deserialize, Serialize};
25
26pub type FxHashMap<K, V> = HashMap<K, V>; // re-export for use in src/librustdoc
27
28/// The version of JSON output that this crate represents.
29///
30/// This integer is incremented with every breaking change to the API,
31/// and is returned along with the JSON blob as [`Crate::format_version`].
32/// Consuming code should assert that this value matches the format version(s) that it supports.
33//
34// WARNING: When you update `FORMAT_VERSION`, please also update the "Latest feature" line with a
35// description of the change. This minimizes the risk of two concurrent PRs changing
36// `FORMAT_VERSION` from N to N+1 and git merging them without conflicts; the "Latest feature" line
37// will instead cause conflicts. See #94591 for more. (This paragraph and the "Latest feature" line
38// are deliberately not in a doc comment, because they need not be in public docs.)
39//
40// Latest feature: Add `ExternCrate::path`.
41pub const FORMAT_VERSION: u32 = 57;
42
43/// The root of the emitted JSON blob.
44///
45/// It contains all type/documentation information
46/// about the language items in the local crate, as well as info about external items to allow
47/// tools to find or link to them.
48#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
49pub struct Crate {
50 /// The id of the root [`Module`] item of the local crate.
51 pub root: Id,
52 /// The version string given to `--crate-version`, if any.
53 pub crate_version: Option<String>,
54 /// Whether or not the output includes private items.
55 pub includes_private: bool,
56 /// A collection of all items in the local crate as well as some external traits and their
57 /// items that are referenced locally.
58 pub index: HashMap<Id, Item>,
59 /// Maps IDs to fully qualified paths and other info helpful for generating links.
60 pub paths: HashMap<Id, ItemSummary>,
61 /// Maps `crate_id` of items to a crate name and html_root_url if it exists.
62 pub external_crates: HashMap<u32, ExternalCrate>,
63 /// Information about the target for which this documentation was generated
64 pub target: Target,
65 /// A single version number to be used in the future when making backwards incompatible changes
66 /// to the JSON output.
67 pub format_version: u32,
68}
69
70/// Information about a target
71#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
72pub struct Target {
73 /// The target triple for which this documentation was generated
74 pub triple: String,
75 /// A list of features valid for use in `#[target_feature]` attributes
76 /// for the target where this rustdoc JSON was generated.
77 pub target_features: Vec<TargetFeature>,
78}
79
80/// Information about a target feature.
81///
82/// Rust target features are used to influence code generation, especially around selecting
83/// instructions which are not universally supported by the target architecture.
84///
85/// Target features are commonly enabled by the [`#[target_feature]` attribute][1] to influence code
86/// generation for a particular function, and less commonly enabled by compiler options like
87/// `-Ctarget-feature` or `-Ctarget-cpu`. Targets themselves automatically enable certain target
88/// features by default, for example because the target's ABI specification requires saving specific
89/// registers which only exist in an architectural extension.
90///
91/// Target features can imply other target features: for example, x86-64 `avx2` implies `avx`, and
92/// aarch64 `sve2` implies `sve`, since both of these architectural extensions depend on their
93/// predecessors.
94///
95/// Target features can be probed at compile time by [`#[cfg(target_feature)]`][2] or `cfg!(…)`
96/// conditional compilation to determine whether a target feature is enabled in a particular
97/// context.
98///
99/// [1]: https://doc.rust-lang.org/stable/reference/attributes/codegen.html#the-target_feature-attribute
100/// [2]: https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature
101#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
102pub struct TargetFeature {
103 /// The name of this target feature.
104 pub name: String,
105 /// Other target features which are implied by this target feature, if any.
106 pub implies_features: Vec<String>,
107 /// If this target feature is unstable, the name of the associated language feature gate.
108 pub unstable_feature_gate: Option<String>,
109 /// Whether this feature is globally enabled for this compilation session.
110 ///
111 /// Target features can be globally enabled implicitly as a result of the target's definition.
112 /// For example, x86-64 hardware floating point ABIs require saving x87 and SSE2 registers,
113 /// which in turn requires globally enabling the `x87` and `sse2` target features so that the
114 /// generated machine code conforms to the target's ABI.
115 ///
116 /// Target features can also be globally enabled explicitly as a result of compiler flags like
117 /// [`-Ctarget-feature`][1] or [`-Ctarget-cpu`][2].
118 ///
119 /// [1]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-feature
120 /// [2]: https://doc.rust-lang.org/beta/rustc/codegen-options/index.html#target-cpu
121 pub globally_enabled: bool,
122}
123
124/// Metadata of a crate, either the same crate on which `rustdoc` was invoked, or its dependency.
125#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
126pub struct ExternalCrate {
127 /// The name of the crate.
128 ///
129 /// Note: This is the [*crate* name][crate-name], which may not be the same as the
130 /// [*package* name][package-name]. For example, for <https://crates.io/crates/regex-syntax>,
131 /// this field will be `regex_syntax` (which uses an `_`, not a `-`).
132 ///
133 /// [crate-name]: https://doc.rust-lang.org/stable/cargo/reference/cargo-targets.html#the-name-field
134 /// [package-name]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-name-field
135 pub name: String,
136 /// The root URL at which the crate's documentation lives.
137 pub html_root_url: Option<String>,
138
139 /// A path from where this crate was loaded.
140 ///
141 /// This will typically be a `.rlib` or `.rmeta`. It can be used to determine which crate
142 /// this was in terms of whatever build-system invoked rustc.
143 pub path: PathBuf,
144}
145
146/// Information about an external (not defined in the local crate) [`Item`].
147///
148/// For external items, you don't get the same level of
149/// information. This struct should contain enough to generate a link/reference to the item in
150/// question, or can be used by a tool that takes the json output of multiple crates to find
151/// the actual item definition with all the relevant info.
152#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
153pub struct ItemSummary {
154 /// Can be used to look up the name and html_root_url of the crate this item came from in the
155 /// `external_crates` map.
156 pub crate_id: u32,
157 /// The list of path components for the fully qualified path of this item (e.g.
158 /// `["std", "io", "lazy", "Lazy"]` for `std::io::lazy::Lazy`).
159 ///
160 /// Note that items can appear in multiple paths, and the one chosen is implementation
161 /// defined. Currently, this is the full path to where the item was defined. Eg
162 /// [`String`] is currently `["alloc", "string", "String"]` and [`HashMap`][`std::collections::HashMap`]
163 /// is `["std", "collections", "hash", "map", "HashMap"]`, but this is subject to change.
164 pub path: Vec<String>,
165 /// Whether this item is a struct, trait, macro, etc.
166 pub kind: ItemKind,
167}
168
169/// Anything that can hold documentation - modules, structs, enums, functions, traits, etc.
170///
171/// The `Item` data type holds fields that can apply to any of these,
172/// and leaves kind-specific details (like function args or enum variants) to the `inner` field.
173#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
174pub struct Item {
175 /// The unique identifier of this item. Can be used to find this item in various mappings.
176 pub id: Id,
177 /// This can be used as a key to the `external_crates` map of [`Crate`] to see which crate
178 /// this item came from.
179 pub crate_id: u32,
180 /// Some items such as impls don't have names.
181 pub name: Option<String>,
182 /// The source location of this item (absent if it came from a macro expansion or inline
183 /// assembly).
184 pub span: Option<Span>,
185 /// By default all documented items are public, but you can tell rustdoc to output private items
186 /// so this field is needed to differentiate.
187 pub visibility: Visibility,
188 /// The full markdown docstring of this item. Absent if there is no documentation at all,
189 /// Some("") if there is some documentation but it is empty (EG `#[doc = ""]`).
190 pub docs: Option<String>,
191 /// This mapping resolves [intra-doc links](https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md) from the docstring to their IDs
192 pub links: HashMap<String, Id>,
193 /// Attributes on this item.
194 ///
195 /// Does not include `#[deprecated]` attributes: see the [`Self::deprecation`] field instead.
196 ///
197 /// Attributes appear in pretty-printed Rust form, regardless of their formatting
198 /// in the original source code. For example:
199 /// - `#[non_exhaustive]` and `#[must_use]` are represented as themselves.
200 /// - `#[no_mangle]` and `#[export_name]` are also represented as themselves.
201 /// - `#[repr(C)]` and other reprs also appear as themselves,
202 /// though potentially with a different order: e.g. `repr(i8, C)` may become `repr(C, i8)`.
203 /// Multiple repr attributes on the same item may be combined into an equivalent single attr.
204 pub attrs: Vec<Attribute>,
205 /// Information about the item’s deprecation, if present.
206 pub deprecation: Option<Deprecation>,
207 /// The type-specific fields describing this item.
208 pub inner: ItemEnum,
209}
210
211#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
212#[serde(rename_all = "snake_case")]
213/// An attribute, e.g. `#[repr(C)]`
214///
215/// This doesn't include:
216/// - `#[doc = "Doc Comment"]` or `/// Doc comment`. These are in [`Item::docs`] instead.
217/// - `#[deprecated]`. These are in [`Item::deprecation`] instead.
218pub enum Attribute {
219 /// `#[non_exhaustive]`
220 NonExhaustive,
221
222 /// `#[must_use]`
223 MustUse { reason: Option<String> },
224
225 /// `#[macro_export]`
226 MacroExport,
227
228 /// `#[export_name = "name"]`
229 ExportName(String),
230
231 /// `#[link_section = "name"]`
232 LinkSection(String),
233
234 /// `#[automatically_derived]`
235 AutomaticallyDerived,
236
237 /// `#[repr]`
238 Repr(AttributeRepr),
239
240 /// `#[no_mangle]`
241 NoMangle,
242
243 /// #[target_feature(enable = "feature1", enable = "feature2")]
244 TargetFeature { enable: Vec<String> },
245
246 /// Something else.
247 ///
248 /// Things here are explicitly *not* covered by the [`FORMAT_VERSION`]
249 /// constant, and may change without bumping the format version.
250 ///
251 /// As an implementation detail, this is currently either:
252 /// 1. A HIR debug printing, like `"#[attr = Optimize(Speed)]"`
253 /// 2. The attribute as it appears in source form, like
254 /// `"#[optimize(speed)]"`.
255 Other(String),
256}
257
258#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
259/// The contents of a `#[repr(...)]` attribute.
260///
261/// Used in [`Attribute::Repr`].
262pub struct AttributeRepr {
263 /// The representation, e.g. `#[repr(C)]`, `#[repr(transparent)]`
264 pub kind: ReprKind,
265
266 /// Alignment in bytes, if explicitly specified by `#[repr(align(...)]`.
267 pub align: Option<u64>,
268 /// Alignment in bytes, if explicitly specified by `#[repr(packed(...)]]`.
269 pub packed: Option<u64>,
270
271 /// The integer type for an enum descriminant, if explicitly specified.
272 ///
273 /// e.g. `"i32"`, for `#[repr(C, i32)]`
274 pub int: Option<String>,
275}
276
277#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
278#[serde(rename_all = "snake_case")]
279/// The kind of `#[repr]`.
280///
281/// See [AttributeRepr::kind]`.
282pub enum ReprKind {
283 /// `#[repr(Rust)]`
284 ///
285 /// Also the default.
286 Rust,
287 /// `#[repr(C)]`
288 C,
289 /// `#[repr(transparent)]
290 Transparent,
291 /// `#[repr(simd)]`
292 Simd,
293}
294
295/// A range of source code.
296#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
297pub struct Span {
298 /// The path to the source file for this span relative to the path `rustdoc` was invoked with.
299 pub filename: PathBuf,
300 /// One indexed Line and Column of the first character of the `Span`.
301 pub begin: (usize, usize),
302 /// One indexed Line and Column of the last character of the `Span`.
303 pub end: (usize, usize),
304}
305
306/// Information about the deprecation of an [`Item`].
307#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
308pub struct Deprecation {
309 /// Usually a version number when this [`Item`] first became deprecated.
310 pub since: Option<String>,
311 /// The reason for deprecation and/or what alternatives to use.
312 pub note: Option<String>,
313}
314
315/// Visibility of an [`Item`].
316#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
317#[serde(rename_all = "snake_case")]
318pub enum Visibility {
319 /// Explicitly public visibility set with `pub`.
320 Public,
321 /// For the most part items are private by default. The exceptions are associated items of
322 /// public traits and variants of public enums.
323 Default,
324 /// Explicitly crate-wide visibility set with `pub(crate)`
325 Crate,
326 /// For `pub(in path)` visibility.
327 Restricted {
328 /// ID of the module to which this visibility restricts items.
329 parent: Id,
330 /// The path with which [`parent`] was referenced
331 /// (like `super::super` or `crate::foo::bar`).
332 ///
333 /// [`parent`]: Visibility::Restricted::parent
334 path: String,
335 },
336}
337
338/// Dynamic trait object type (`dyn Trait`).
339#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
340pub struct DynTrait {
341 /// All the traits implemented. One of them is the vtable, and the rest must be auto traits.
342 pub traits: Vec<PolyTrait>,
343 /// The lifetime of the whole dyn object
344 /// ```text
345 /// dyn Debug + 'static
346 /// ^^^^^^^
347 /// |
348 /// this part
349 /// ```
350 pub lifetime: Option<String>,
351}
352
353/// A trait and potential HRTBs
354#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
355pub struct PolyTrait {
356 /// The path to the trait.
357 #[serde(rename = "trait")]
358 pub trait_: Path,
359 /// Used for Higher-Rank Trait Bounds (HRTBs)
360 /// ```text
361 /// dyn for<'a> Fn() -> &'a i32"
362 /// ^^^^^^^
363 /// ```
364 pub generic_params: Vec<GenericParamDef>,
365}
366
367/// A set of generic arguments provided to a path segment, e.g.
368///
369/// ```text
370/// std::option::Option<u32>
371/// ^^^^^
372/// ```
373#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
374#[serde(rename_all = "snake_case")]
375pub enum GenericArgs {
376 /// `<'a, 32, B: Copy, C = u32>`
377 AngleBracketed {
378 /// The list of each argument on this type.
379 /// ```text
380 /// <'a, 32, B: Copy, C = u32>
381 /// ^^^^^^
382 /// ```
383 args: Vec<GenericArg>,
384 /// Associated type or constant bindings (e.g. `Item=i32` or `Item: Clone`) for this type.
385 constraints: Vec<AssocItemConstraint>,
386 },
387 /// `Fn(A, B) -> C`
388 Parenthesized {
389 /// The input types, enclosed in parentheses.
390 inputs: Vec<Type>,
391 /// The output type provided after the `->`, if present.
392 output: Option<Type>,
393 },
394 /// `T::method(..)`
395 ReturnTypeNotation,
396}
397
398/// One argument in a list of generic arguments to a path segment.
399///
400/// Part of [`GenericArgs`].
401#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
402#[serde(rename_all = "snake_case")]
403pub enum GenericArg {
404 /// A lifetime argument.
405 /// ```text
406 /// std::borrow::Cow<'static, str>
407 /// ^^^^^^^
408 /// ```
409 Lifetime(String),
410 /// A type argument.
411 /// ```text
412 /// std::borrow::Cow<'static, str>
413 /// ^^^
414 /// ```
415 Type(Type),
416 /// A constant as a generic argument.
417 /// ```text
418 /// core::array::IntoIter<u32, { 640 * 1024 }>
419 /// ^^^^^^^^^^^^^^
420 /// ```
421 Const(Constant),
422 /// A generic argument that's explicitly set to be inferred.
423 /// ```text
424 /// std::vec::Vec::<_>
425 /// ^
426 /// ```
427 Infer,
428}
429
430/// A constant.
431#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
432pub struct Constant {
433 /// The stringified expression of this constant. Note that its mapping to the original
434 /// source code is unstable and it's not guaranteed that it'll match the source code.
435 pub expr: String,
436 /// The value of the evaluated expression for this constant, which is only computed for numeric
437 /// types.
438 pub value: Option<String>,
439 /// Whether this constant is a bool, numeric, string, or char literal.
440 pub is_literal: bool,
441}
442
443/// Describes a bound applied to an associated type/constant.
444///
445/// Example:
446/// ```text
447/// IntoIterator<Item = u32, IntoIter: Clone>
448/// ^^^^^^^^^^ ^^^^^^^^^^^^^^^
449/// ```
450#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
451pub struct AssocItemConstraint {
452 /// The name of the associated type/constant.
453 pub name: String,
454 /// Arguments provided to the associated type/constant.
455 pub args: Option<Box<GenericArgs>>,
456 /// The kind of bound applied to the associated type/constant.
457 pub binding: AssocItemConstraintKind,
458}
459
460/// The way in which an associate type/constant is bound.
461#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
462#[serde(rename_all = "snake_case")]
463pub enum AssocItemConstraintKind {
464 /// The required value/type is specified exactly. e.g.
465 /// ```text
466 /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
467 /// ^^^^^^^^^^
468 /// ```
469 Equality(Term),
470 /// The type is required to satisfy a set of bounds.
471 /// ```text
472 /// Iterator<Item = u32, IntoIter: DoubleEndedIterator>
473 /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
474 /// ```
475 Constraint(Vec<GenericBound>),
476}
477
478/// An opaque identifier for an item.
479///
480/// It can be used to lookup in [`Crate::index`] or [`Crate::paths`] to resolve it
481/// to an [`Item`].
482///
483/// Id's are only valid within a single JSON blob. They cannot be used to
484/// resolve references between the JSON output's for different crates.
485///
486/// Rustdoc makes no guarantees about the inner value of Id's. Applications
487/// should treat them as opaque keys to lookup items, and avoid attempting
488/// to parse them, or otherwise depend on any implementation details.
489#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
490// FIXME(aDotInTheVoid): Consider making this non-public in rustdoc-types.
491pub struct Id(pub u32);
492
493/// The fundamental kind of an item. Unlike [`ItemEnum`], this does not carry any additional info.
494///
495/// Part of [`ItemSummary`].
496#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
497#[serde(rename_all = "snake_case")]
498pub enum ItemKind {
499 /// A module declaration, e.g. `mod foo;` or `mod foo {}`
500 Module,
501 /// A crate imported via the `extern crate` syntax.
502 ExternCrate,
503 /// An import of 1 or more items into scope, using the `use` keyword.
504 Use,
505 /// A `struct` declaration.
506 Struct,
507 /// A field of a struct.
508 StructField,
509 /// A `union` declaration.
510 Union,
511 /// An `enum` declaration.
512 Enum,
513 /// A variant of a enum.
514 Variant,
515 /// A function declaration, e.g. `fn f() {}`
516 Function,
517 /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
518 TypeAlias,
519 /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
520 Constant,
521 /// A `trait` declaration.
522 Trait,
523 /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
524 ///
525 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
526 TraitAlias,
527 /// An `impl` block.
528 Impl,
529 /// A `static` declaration.
530 Static,
531 /// `type`s from an `extern` block.
532 ///
533 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
534 ExternType,
535 /// A macro declaration.
536 ///
537 /// Corresponds to either `ItemEnum::Macro(_)`
538 /// or `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Bang })`
539 Macro,
540 /// A procedural macro attribute.
541 ///
542 /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Attr })`
543 ProcAttribute,
544 /// A procedural macro usable in the `#[derive()]` attribute.
545 ///
546 /// Corresponds to `ItemEnum::ProcMacro(ProcMacro { kind: MacroKind::Derive })`
547 ProcDerive,
548 /// An associated constant of a trait or a type.
549 AssocConst,
550 /// An associated type of a trait or a type.
551 AssocType,
552 /// A primitive type, e.g. `u32`.
553 ///
554 /// [`Item`]s of this kind only come from the core library.
555 Primitive,
556 /// A keyword declaration.
557 ///
558 /// [`Item`]s of this kind only come from the come library and exist solely
559 /// to carry documentation for the respective keywords.
560 Keyword,
561 /// An attribute declaration.
562 ///
563 /// [`Item`]s of this kind only come from the core library and exist solely
564 /// to carry documentation for the respective builtin attributes.
565 Attribute,
566}
567
568/// Specific fields of an item.
569///
570/// Part of [`Item`].
571#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
572#[serde(rename_all = "snake_case")]
573pub enum ItemEnum {
574 /// A module declaration, e.g. `mod foo;` or `mod foo {}`
575 Module(Module),
576 /// A crate imported via the `extern crate` syntax.
577 ExternCrate {
578 /// The name of the imported crate.
579 name: String,
580 /// If the crate is renamed, this is its name in the crate.
581 rename: Option<String>,
582 },
583 /// An import of 1 or more items into scope, using the `use` keyword.
584 Use(Use),
585
586 /// A `union` declaration.
587 Union(Union),
588 /// A `struct` declaration.
589 Struct(Struct),
590 /// A field of a struct.
591 StructField(Type),
592 /// An `enum` declaration.
593 Enum(Enum),
594 /// A variant of a enum.
595 Variant(Variant),
596
597 /// A function declaration (including methods and other associated functions)
598 Function(Function),
599
600 /// A `trait` declaration.
601 Trait(Trait),
602 /// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
603 ///
604 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
605 TraitAlias(TraitAlias),
606 /// An `impl` block.
607 Impl(Impl),
608
609 /// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
610 TypeAlias(TypeAlias),
611 /// The declaration of a constant, e.g. `const GREETING: &str = "Hi :3";`
612 Constant {
613 /// The type of the constant.
614 #[serde(rename = "type")]
615 type_: Type,
616 /// The declared constant itself.
617 #[serde(rename = "const")]
618 const_: Constant,
619 },
620
621 /// A declaration of a `static`.
622 Static(Static),
623
624 /// `type`s from an `extern` block.
625 ///
626 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/43467)
627 ExternType,
628
629 /// A macro_rules! declarative macro. Contains a single string with the source
630 /// representation of the macro with the patterns stripped.
631 Macro(String),
632 /// A procedural macro.
633 ProcMacro(ProcMacro),
634
635 /// A primitive type, e.g. `u32`.
636 ///
637 /// [`Item`]s of this kind only come from the core library.
638 Primitive(Primitive),
639
640 /// An associated constant of a trait or a type.
641 AssocConst {
642 /// The type of the constant.
643 #[serde(rename = "type")]
644 type_: Type,
645 /// Inside a trait declaration, this is the default value for the associated constant,
646 /// if provided.
647 /// Inside an `impl` block, this is the value assigned to the associated constant,
648 /// and will always be present.
649 ///
650 /// The representation is implementation-defined and not guaranteed to be representative of
651 /// either the resulting value or of the source code.
652 ///
653 /// ```rust
654 /// const X: usize = 640 * 1024;
655 /// // ^^^^^^^^^^
656 /// ```
657 value: Option<String>,
658 },
659 /// An associated type of a trait or a type.
660 AssocType {
661 /// The generic parameters and where clauses on ahis associated type.
662 generics: Generics,
663 /// The bounds for this associated type. e.g.
664 /// ```rust
665 /// trait IntoIterator {
666 /// type Item;
667 /// type IntoIter: Iterator<Item = Self::Item>;
668 /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^
669 /// }
670 /// ```
671 bounds: Vec<GenericBound>,
672 /// Inside a trait declaration, this is the default for the associated type, if provided.
673 /// Inside an impl block, this is the type assigned to the associated type, and will always
674 /// be present.
675 ///
676 /// ```rust
677 /// type X = usize;
678 /// // ^^^^^
679 /// ```
680 #[serde(rename = "type")]
681 type_: Option<Type>,
682 },
683}
684
685/// A module declaration, e.g. `mod foo;` or `mod foo {}`.
686#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
687pub struct Module {
688 /// Whether this is the root item of a crate.
689 ///
690 /// This item doesn't correspond to any construction in the source code and is generated by the
691 /// compiler.
692 pub is_crate: bool,
693 /// [`Item`]s declared inside this module.
694 pub items: Vec<Id>,
695 /// If `true`, this module is not part of the public API, but it contains
696 /// items that are re-exported as public API.
697 pub is_stripped: bool,
698}
699
700/// A `union`.
701#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
702pub struct Union {
703 /// The generic parameters and where clauses on this union.
704 pub generics: Generics,
705 /// Whether any fields have been removed from the result, due to being private or hidden.
706 pub has_stripped_fields: bool,
707 /// The list of fields in the union.
708 ///
709 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
710 pub fields: Vec<Id>,
711 /// All impls (both of traits and inherent) for this union.
712 ///
713 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
714 pub impls: Vec<Id>,
715}
716
717/// A `struct`.
718#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
719pub struct Struct {
720 /// The kind of the struct (e.g. unit, tuple-like or struct-like) and the data specific to it,
721 /// i.e. fields.
722 pub kind: StructKind,
723 /// The generic parameters and where clauses on this struct.
724 pub generics: Generics,
725 /// All impls (both of traits and inherent) for this struct.
726 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
727 pub impls: Vec<Id>,
728}
729
730/// The kind of a [`Struct`] and the data specific to it, i.e. fields.
731#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
732#[serde(rename_all = "snake_case")]
733pub enum StructKind {
734 /// A struct with no fields and no parentheses.
735 ///
736 /// ```rust
737 /// pub struct Unit;
738 /// ```
739 Unit,
740 /// A struct with unnamed fields.
741 ///
742 /// All [`Id`]'s will point to [`ItemEnum::StructField`].
743 /// Unlike most of JSON, private and `#[doc(hidden)]` fields will be given as `None`
744 /// instead of being omitted, because order matters.
745 ///
746 /// ```rust
747 /// pub struct TupleStruct(i32);
748 /// pub struct EmptyTupleStruct();
749 /// ```
750 Tuple(Vec<Option<Id>>),
751 /// A struct with named fields.
752 ///
753 /// ```rust
754 /// pub struct PlainStruct { x: i32 }
755 /// pub struct EmptyPlainStruct {}
756 /// ```
757 Plain {
758 /// The list of fields in the struct.
759 ///
760 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
761 fields: Vec<Id>,
762 /// Whether any fields have been removed from the result, due to being private or hidden.
763 has_stripped_fields: bool,
764 },
765}
766
767/// An `enum`.
768#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
769pub struct Enum {
770 /// Information about the type parameters and `where` clauses of the enum.
771 pub generics: Generics,
772 /// Whether any variants have been removed from the result, due to being private or hidden.
773 pub has_stripped_variants: bool,
774 /// The list of variants in the enum.
775 ///
776 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`]
777 pub variants: Vec<Id>,
778 /// `impl`s for the enum.
779 pub impls: Vec<Id>,
780}
781
782/// A variant of an enum.
783#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
784pub struct Variant {
785 /// Whether the variant is plain, a tuple-like, or struct-like. Contains the fields.
786 pub kind: VariantKind,
787 /// The discriminant, if explicitly specified.
788 pub discriminant: Option<Discriminant>,
789}
790
791/// The kind of an [`Enum`] [`Variant`] and the data specific to it, i.e. fields.
792#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
793#[serde(rename_all = "snake_case")]
794pub enum VariantKind {
795 /// A variant with no parentheses
796 ///
797 /// ```rust
798 /// enum Demo {
799 /// PlainVariant,
800 /// PlainWithDiscriminant = 1,
801 /// }
802 /// ```
803 Plain,
804 /// A variant with unnamed fields.
805 ///
806 /// All [`Id`]'s will point to [`ItemEnum::StructField`].
807 /// Unlike most of JSON, `#[doc(hidden)]` fields will be given as `None`
808 /// instead of being omitted, because order matters.
809 ///
810 /// ```rust
811 /// enum Demo {
812 /// TupleVariant(i32),
813 /// EmptyTupleVariant(),
814 /// }
815 /// ```
816 Tuple(Vec<Option<Id>>),
817 /// A variant with named fields.
818 ///
819 /// ```rust
820 /// enum Demo {
821 /// StructVariant { x: i32 },
822 /// EmptyStructVariant {},
823 /// }
824 /// ```
825 Struct {
826 /// The list of variants in the enum.
827 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`].
828 fields: Vec<Id>,
829 /// Whether any variants have been removed from the result, due to being private or hidden.
830 has_stripped_fields: bool,
831 },
832}
833
834/// The value that distinguishes a variant in an [`Enum`] from other variants.
835#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
836pub struct Discriminant {
837 /// The expression that produced the discriminant.
838 ///
839 /// Unlike `value`, this preserves the original formatting (eg suffixes,
840 /// hexadecimal, and underscores), making it unsuitable to be machine
841 /// interpreted.
842 ///
843 /// In some cases, when the value is too complex, this may be `"{ _ }"`.
844 /// When this occurs is unstable, and may change without notice.
845 pub expr: String,
846 /// The numerical value of the discriminant. Stored as a string due to
847 /// JSON's poor support for large integers, and the fact that it would need
848 /// to store from [`i128::MIN`] to [`u128::MAX`].
849 pub value: String,
850}
851
852/// A set of fundamental properties of a function.
853#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
854pub struct FunctionHeader {
855 /// Is this function marked as `const`?
856 pub is_const: bool,
857 /// Is this function unsafe?
858 pub is_unsafe: bool,
859 /// Is this function async?
860 pub is_async: bool,
861 /// The ABI used by the function.
862 pub abi: Abi,
863}
864
865/// The ABI (Application Binary Interface) used by a function.
866///
867/// If a variant has an `unwind` field, this means the ABI that it represents can be specified in 2
868/// ways: `extern "_"` and `extern "_-unwind"`, and a value of `true` for that field signifies the
869/// latter variant.
870///
871/// See the [Rustonomicon section](https://doc.rust-lang.org/nightly/nomicon/ffi.html#ffi-and-unwinding)
872/// on unwinding for more info.
873#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
874pub enum Abi {
875 // We only have a concrete listing here for stable ABI's because there are so many
876 // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
877 /// The default ABI, but that can also be written explicitly with `extern "Rust"`.
878 Rust,
879 /// Can be specified as `extern "C"` or, as a shorthand, just `extern`.
880 C { unwind: bool },
881 /// Can be specified as `extern "cdecl"`.
882 Cdecl { unwind: bool },
883 /// Can be specified as `extern "stdcall"`.
884 Stdcall { unwind: bool },
885 /// Can be specified as `extern "fastcall"`.
886 Fastcall { unwind: bool },
887 /// Can be specified as `extern "aapcs"`.
888 Aapcs { unwind: bool },
889 /// Can be specified as `extern "win64"`.
890 Win64 { unwind: bool },
891 /// Can be specified as `extern "sysv64"`.
892 SysV64 { unwind: bool },
893 /// Can be specified as `extern "system"`.
894 System { unwind: bool },
895 /// Any other ABI, including unstable ones.
896 Other(String),
897}
898
899/// A function declaration (including methods and other associated functions).
900#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
901pub struct Function {
902 /// Information about the function signature, or declaration.
903 pub sig: FunctionSignature,
904 /// Information about the function’s type parameters and `where` clauses.
905 pub generics: Generics,
906 /// Information about core properties of the function, e.g. whether it's `const`, its ABI, etc.
907 pub header: FunctionHeader,
908 /// Whether the function has a body, i.e. an implementation.
909 pub has_body: bool,
910}
911
912/// Generic parameters accepted by an item and `where` clauses imposed on it and the parameters.
913#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
914pub struct Generics {
915 /// A list of generic parameter definitions (e.g. `<T: Clone + Hash, U: Copy>`).
916 pub params: Vec<GenericParamDef>,
917 /// A list of where predicates (e.g. `where T: Iterator, T::Item: Copy`).
918 pub where_predicates: Vec<WherePredicate>,
919}
920
921/// One generic parameter accepted by an item.
922#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
923pub struct GenericParamDef {
924 /// Name of the parameter.
925 /// ```rust
926 /// fn f<'resource, Resource>(x: &'resource Resource) {}
927 /// // ^^^^^^^^ ^^^^^^^^
928 /// ```
929 pub name: String,
930 /// The kind of the parameter and data specific to a particular parameter kind, e.g. type
931 /// bounds.
932 pub kind: GenericParamDefKind,
933}
934
935/// The kind of a [`GenericParamDef`].
936#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
937#[serde(rename_all = "snake_case")]
938pub enum GenericParamDefKind {
939 /// Denotes a lifetime parameter.
940 Lifetime {
941 /// Lifetimes that this lifetime parameter is required to outlive.
942 ///
943 /// ```rust
944 /// fn f<'a, 'b, 'resource: 'a + 'b>(a: &'a str, b: &'b str, res: &'resource str) {}
945 /// // ^^^^^^^
946 /// ```
947 outlives: Vec<String>,
948 },
949
950 /// Denotes a type parameter.
951 Type {
952 /// Bounds applied directly to the type. Note that the bounds from `where` clauses
953 /// that constrain this parameter won't appear here.
954 ///
955 /// ```rust
956 /// fn default2<T: Default>() -> [T; 2] where T: Clone { todo!() }
957 /// // ^^^^^^^
958 /// ```
959 bounds: Vec<GenericBound>,
960 /// The default type for this parameter, if provided, e.g.
961 ///
962 /// ```rust
963 /// trait PartialEq<Rhs = Self> {}
964 /// // ^^^^
965 /// ```
966 default: Option<Type>,
967 /// This is normally `false`, which means that this generic parameter is
968 /// declared in the Rust source text.
969 ///
970 /// If it is `true`, this generic parameter has been introduced by the
971 /// compiler behind the scenes.
972 ///
973 /// # Example
974 ///
975 /// Consider
976 ///
977 /// ```ignore (pseudo-rust)
978 /// pub fn f(_: impl Trait) {}
979 /// ```
980 ///
981 /// The compiler will transform this behind the scenes to
982 ///
983 /// ```ignore (pseudo-rust)
984 /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
985 /// ```
986 ///
987 /// In this example, the generic parameter named `impl Trait` (and which
988 /// is bound by `Trait`) is synthetic, because it was not originally in
989 /// the Rust source text.
990 is_synthetic: bool,
991 },
992
993 /// Denotes a constant parameter.
994 Const {
995 /// The type of the constant as declared.
996 #[serde(rename = "type")]
997 type_: Type,
998 /// The stringified expression for the default value, if provided. It's not guaranteed that
999 /// it'll match the actual source code for the default value.
1000 default: Option<String>,
1001 },
1002}
1003
1004/// One `where` clause.
1005/// ```rust
1006/// fn default<T>() -> T where T: Default { T::default() }
1007/// // ^^^^^^^^^^
1008/// ```
1009#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1010#[serde(rename_all = "snake_case")]
1011pub enum WherePredicate {
1012 /// A type is expected to comply with a set of bounds
1013 BoundPredicate {
1014 /// The type that's being constrained.
1015 ///
1016 /// ```rust
1017 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1018 /// // ^
1019 /// ```
1020 #[serde(rename = "type")]
1021 type_: Type,
1022 /// The set of bounds that constrain the type.
1023 ///
1024 /// ```rust
1025 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1026 /// // ^^^^^^^^
1027 /// ```
1028 bounds: Vec<GenericBound>,
1029 /// Used for Higher-Rank Trait Bounds (HRTBs)
1030 /// ```rust
1031 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1032 /// // ^^^^^^^
1033 /// ```
1034 generic_params: Vec<GenericParamDef>,
1035 },
1036
1037 /// A lifetime is expected to outlive other lifetimes.
1038 LifetimePredicate {
1039 /// The name of the lifetime.
1040 lifetime: String,
1041 /// The lifetimes that must be encompassed by the lifetime.
1042 outlives: Vec<String>,
1043 },
1044
1045 /// A type must exactly equal another type.
1046 EqPredicate {
1047 /// The left side of the equation.
1048 lhs: Type,
1049 /// The right side of the equation.
1050 rhs: Term,
1051 },
1052}
1053
1054/// Either a trait bound or a lifetime bound.
1055#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1056#[serde(rename_all = "snake_case")]
1057pub enum GenericBound {
1058 /// A trait bound.
1059 TraitBound {
1060 /// The full path to the trait.
1061 #[serde(rename = "trait")]
1062 trait_: Path,
1063 /// Used for Higher-Rank Trait Bounds (HRTBs)
1064 /// ```text
1065 /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
1066 /// ^^^^^^^^^^^
1067 /// |
1068 /// this part
1069 /// ```
1070 generic_params: Vec<GenericParamDef>,
1071 /// The context for which a trait is supposed to be used, e.g. `const
1072 modifier: TraitBoundModifier,
1073 },
1074 /// A lifetime bound, e.g.
1075 /// ```rust
1076 /// fn f<'a, T>(x: &'a str, y: &T) where T: 'a {}
1077 /// // ^^^
1078 /// ```
1079 Outlives(String),
1080 /// `use<'a, T>` precise-capturing bound syntax
1081 Use(Vec<PreciseCapturingArg>),
1082}
1083
1084/// A set of modifiers applied to a trait.
1085#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1086#[serde(rename_all = "snake_case")]
1087pub enum TraitBoundModifier {
1088 /// Marks the absence of a modifier.
1089 None,
1090 /// Indicates that the trait bound relaxes a trait bound applied to a parameter by default,
1091 /// e.g. `T: Sized?`, the `Sized` trait is required for all generic type parameters by default
1092 /// unless specified otherwise with this modifier.
1093 Maybe,
1094 /// Indicates that the trait bound must be applicable in both a run-time and a compile-time
1095 /// context.
1096 MaybeConst,
1097}
1098
1099/// One precise capturing argument. See [the rust reference](https://doc.rust-lang.org/reference/types/impl-trait.html#precise-capturing).
1100#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1101#[serde(rename_all = "snake_case")]
1102pub enum PreciseCapturingArg {
1103 /// A lifetime.
1104 /// ```rust
1105 /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1106 /// // ^^
1107 Lifetime(String),
1108 /// A type or constant parameter.
1109 /// ```rust
1110 /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1111 /// // ^ ^
1112 Param(String),
1113}
1114
1115/// Either a type or a constant, usually stored as the right-hand side of an equation in places like
1116/// [`AssocItemConstraint`]
1117#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1118#[serde(rename_all = "snake_case")]
1119pub enum Term {
1120 /// A type.
1121 ///
1122 /// ```rust
1123 /// fn f(x: impl IntoIterator<Item = u32>) {}
1124 /// // ^^^
1125 /// ```
1126 Type(Type),
1127 /// A constant.
1128 ///
1129 /// ```ignore (incomplete feature in the snippet)
1130 /// trait Foo {
1131 /// const BAR: usize;
1132 /// }
1133 ///
1134 /// fn f(x: impl Foo<BAR = 42>) {}
1135 /// // ^^
1136 /// ```
1137 Constant(Constant),
1138}
1139
1140/// A type.
1141#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1142#[serde(rename_all = "snake_case")]
1143pub enum Type {
1144 /// Structs, enums, unions and type aliases, e.g. `std::option::Option<u32>`
1145 ResolvedPath(Path),
1146 /// Dynamic trait object type (`dyn Trait`).
1147 DynTrait(DynTrait),
1148 /// Parameterized types. The contained string is the name of the parameter.
1149 Generic(String),
1150 /// Built-in numeric types (e.g. `u32`, `f32`), `bool`, `char`.
1151 Primitive(String),
1152 /// A function pointer type, e.g. `fn(u32) -> u32`, `extern "C" fn() -> *const u8`
1153 FunctionPointer(Box<FunctionPointer>),
1154 /// A tuple type, e.g. `(String, u32, Box<usize>)`
1155 Tuple(Vec<Type>),
1156 /// An unsized slice type, e.g. `[u32]`.
1157 Slice(Box<Type>),
1158 /// An array type, e.g. `[u32; 15]`
1159 Array {
1160 /// The type of the contained element.
1161 #[serde(rename = "type")]
1162 type_: Box<Type>,
1163 /// The stringified expression that is the length of the array.
1164 ///
1165 /// Keep in mind that it's not guaranteed to match the actual source code of the expression.
1166 len: String,
1167 },
1168 /// A pattern type, e.g. `u32 is 1..`
1169 ///
1170 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/123646)
1171 Pat {
1172 /// The base type, e.g. the `u32` in `u32 is 1..`
1173 #[serde(rename = "type")]
1174 type_: Box<Type>,
1175 #[doc(hidden)]
1176 __pat_unstable_do_not_use: String,
1177 },
1178 /// An opaque type that satisfies a set of bounds, `impl TraitA + TraitB + ...`
1179 ImplTrait(Vec<GenericBound>),
1180 /// A type that's left to be inferred, `_`
1181 Infer,
1182 /// A raw pointer type, e.g. `*mut u32`, `*const u8`, etc.
1183 RawPointer {
1184 /// This is `true` for `*mut _` and `false` for `*const _`.
1185 is_mutable: bool,
1186 /// The type of the pointee.
1187 #[serde(rename = "type")]
1188 type_: Box<Type>,
1189 },
1190 /// `&'a mut String`, `&str`, etc.
1191 BorrowedRef {
1192 /// The name of the lifetime of the reference, if provided.
1193 lifetime: Option<String>,
1194 /// This is `true` for `&mut i32` and `false` for `&i32`
1195 is_mutable: bool,
1196 /// The type of the pointee, e.g. the `i32` in `&'a mut i32`
1197 #[serde(rename = "type")]
1198 type_: Box<Type>,
1199 },
1200 /// Associated types like `<Type as Trait>::Name` and `T::Item` where
1201 /// `T: Iterator` or inherent associated types like `Struct::Name`.
1202 QualifiedPath {
1203 /// The name of the associated type in the parent type.
1204 ///
1205 /// ```ignore (incomplete expression)
1206 /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1207 /// // ^^^^
1208 /// ```
1209 name: String,
1210 /// The generic arguments provided to the associated type.
1211 ///
1212 /// ```ignore (incomplete expression)
1213 /// <core::slice::IterMut<'static, u32> as BetterIterator>::Item<'static>
1214 /// // ^^^^^^^^^
1215 /// ```
1216 args: Option<Box<GenericArgs>>,
1217 /// The type with which this type is associated.
1218 ///
1219 /// ```ignore (incomplete expression)
1220 /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1221 /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1222 /// ```
1223 self_type: Box<Type>,
1224 /// `None` iff this is an *inherent* associated type.
1225 #[serde(rename = "trait")]
1226 trait_: Option<Path>,
1227 },
1228}
1229
1230/// A type that has a simple path to it. This is the kind of type of structs, unions, enums, etc.
1231#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1232pub struct Path {
1233 /// The path of the type.
1234 ///
1235 /// This will be the path that is *used* (not where it is defined), so
1236 /// multiple `Path`s may have different values for this field even if
1237 /// they all refer to the same item. e.g.
1238 ///
1239 /// ```rust
1240 /// pub type Vec1 = std::vec::Vec<i32>; // path: "std::vec::Vec"
1241 /// pub type Vec2 = Vec<i32>; // path: "Vec"
1242 /// pub type Vec3 = std::prelude::v1::Vec<i32>; // path: "std::prelude::v1::Vec"
1243 /// ```
1244 //
1245 // Example tested in ./tests/rustdoc-json/path_name.rs
1246 pub path: String,
1247 /// The ID of the type.
1248 pub id: Id,
1249 /// Generic arguments to the type.
1250 ///
1251 /// ```ignore (incomplete expression)
1252 /// std::borrow::Cow<'static, str>
1253 /// // ^^^^^^^^^^^^^^
1254 /// ```
1255 pub args: Option<Box<GenericArgs>>,
1256}
1257
1258/// A type that is a function pointer.
1259#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1260pub struct FunctionPointer {
1261 /// The signature of the function.
1262 pub sig: FunctionSignature,
1263 /// Used for Higher-Rank Trait Bounds (HRTBs)
1264 ///
1265 /// ```ignore (incomplete expression)
1266 /// for<'c> fn(val: &'c i32) -> i32
1267 /// // ^^^^^^^
1268 /// ```
1269 pub generic_params: Vec<GenericParamDef>,
1270 /// The core properties of the function, such as the ABI it conforms to, whether it's unsafe, etc.
1271 pub header: FunctionHeader,
1272}
1273
1274/// The signature of a function.
1275#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1276pub struct FunctionSignature {
1277 /// List of argument names and their type.
1278 ///
1279 /// Note that not all names will be valid identifiers, as some of
1280 /// them may be patterns.
1281 pub inputs: Vec<(String, Type)>,
1282 /// The output type, if specified.
1283 pub output: Option<Type>,
1284 /// Whether the function accepts an arbitrary amount of trailing arguments the C way.
1285 ///
1286 /// ```ignore (incomplete code)
1287 /// fn printf(fmt: &str, ...);
1288 /// ```
1289 pub is_c_variadic: bool,
1290}
1291
1292/// A `trait` declaration.
1293#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1294pub struct Trait {
1295 /// Whether the trait is marked `auto` and is thus implemented automatically
1296 /// for all applicable types.
1297 pub is_auto: bool,
1298 /// Whether the trait is marked as `unsafe`.
1299 pub is_unsafe: bool,
1300 /// Whether the trait is [dyn compatible](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility)[^1].
1301 ///
1302 /// [^1]: Formerly known as "object safe".
1303 pub is_dyn_compatible: bool,
1304 /// Associated [`Item`]s that can/must be implemented by the `impl` blocks.
1305 pub items: Vec<Id>,
1306 /// Information about the type parameters and `where` clauses of the trait.
1307 pub generics: Generics,
1308 /// Constraints that must be met by the implementor of the trait.
1309 pub bounds: Vec<GenericBound>,
1310 /// The implementations of the trait.
1311 pub implementations: Vec<Id>,
1312}
1313
1314/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
1315///
1316/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
1317#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1318pub struct TraitAlias {
1319 /// Information about the type parameters and `where` clauses of the alias.
1320 pub generics: Generics,
1321 /// The bounds that are associated with the alias.
1322 pub params: Vec<GenericBound>,
1323}
1324
1325/// An `impl` block.
1326#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1327pub struct Impl {
1328 /// Whether this impl is for an unsafe trait.
1329 pub is_unsafe: bool,
1330 /// Information about the impl’s type parameters and `where` clauses.
1331 pub generics: Generics,
1332 /// The list of the names of all the trait methods that weren't mentioned in this impl but
1333 /// were provided by the trait itself.
1334 ///
1335 /// For example, for this impl of the [`PartialEq`] trait:
1336 /// ```rust
1337 /// struct Foo;
1338 ///
1339 /// impl PartialEq for Foo {
1340 /// fn eq(&self, other: &Self) -> bool { todo!() }
1341 /// }
1342 /// ```
1343 /// This field will be `["ne"]`, as it has a default implementation defined for it.
1344 pub provided_trait_methods: Vec<String>,
1345 /// The trait being implemented or `None` if the impl is inherent, which means
1346 /// `impl Struct {}` as opposed to `impl Trait for Struct {}`.
1347 #[serde(rename = "trait")]
1348 pub trait_: Option<Path>,
1349 /// The type that the impl block is for.
1350 #[serde(rename = "for")]
1351 pub for_: Type,
1352 /// The list of associated items contained in this impl block.
1353 pub items: Vec<Id>,
1354 /// Whether this is a negative impl (e.g. `!Sized` or `!Send`).
1355 pub is_negative: bool,
1356 /// Whether this is an impl that’s implied by the compiler
1357 /// (for autotraits, e.g. `Send` or `Sync`).
1358 pub is_synthetic: bool,
1359 // FIXME: document this
1360 pub blanket_impl: Option<Type>,
1361}
1362
1363/// A `use` statement.
1364#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1365#[serde(rename_all = "snake_case")]
1366pub struct Use {
1367 /// The full path being imported.
1368 pub source: String,
1369 /// May be different from the last segment of `source` when renaming imports:
1370 /// `use source as name;`
1371 pub name: String,
1372 /// The ID of the item being imported. Will be `None` in case of re-exports of primitives:
1373 /// ```rust
1374 /// pub use i32 as my_i32;
1375 /// ```
1376 pub id: Option<Id>,
1377 /// Whether this statement is a wildcard `use`, e.g. `use source::*;`
1378 pub is_glob: bool,
1379}
1380
1381/// A procedural macro.
1382#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1383pub struct ProcMacro {
1384 /// How this macro is supposed to be called: `foo!()`, `#[foo]` or `#[derive(foo)]`
1385 pub kind: MacroKind,
1386 /// Helper attributes defined by a macro to be used inside it.
1387 ///
1388 /// Defined only for derive macros.
1389 ///
1390 /// E.g. the [`Default`] derive macro defines a `#[default]` helper attribute so that one can
1391 /// do:
1392 ///
1393 /// ```rust
1394 /// #[derive(Default)]
1395 /// enum Option<T> {
1396 /// #[default]
1397 /// None,
1398 /// Some(T),
1399 /// }
1400 /// ```
1401 pub helpers: Vec<String>,
1402}
1403
1404/// The way a [`ProcMacro`] is declared to be used.
1405#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1406#[serde(rename_all = "snake_case")]
1407pub enum MacroKind {
1408 /// A bang macro `foo!()`.
1409 Bang,
1410 /// An attribute macro `#[foo]`.
1411 Attr,
1412 /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]`
1413 Derive,
1414}
1415
1416/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
1417#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1418pub struct TypeAlias {
1419 /// The type referred to by this alias.
1420 #[serde(rename = "type")]
1421 pub type_: Type,
1422 /// Information about the type parameters and `where` clauses of the alias.
1423 pub generics: Generics,
1424}
1425
1426/// A `static` declaration.
1427#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1428pub struct Static {
1429 /// The type of the static.
1430 #[serde(rename = "type")]
1431 pub type_: Type,
1432 /// This is `true` for mutable statics, declared as `static mut X: T = f();`
1433 pub is_mutable: bool,
1434 /// The stringified expression for the initial value.
1435 ///
1436 /// It's not guaranteed that it'll match the actual source code for the initial value.
1437 pub expr: String,
1438
1439 /// Is the static `unsafe`?
1440 ///
1441 /// This is only true if it's in an `extern` block, and not explicitly marked
1442 /// as `safe`.
1443 ///
1444 /// ```rust
1445 /// unsafe extern {
1446 /// static A: i32; // unsafe
1447 /// safe static B: i32; // safe
1448 /// }
1449 ///
1450 /// static C: i32 = 0; // safe
1451 /// static mut D: i32 = 0; // safe
1452 /// ```
1453 pub is_unsafe: bool,
1454}
1455
1456/// A primitive type declaration. Declarations of this kind can only come from the core library.
1457#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1458pub struct Primitive {
1459 /// The name of the type.
1460 pub name: String,
1461 /// The implementations, inherent and of traits, on the primitive type.
1462 pub impls: Vec<Id>,
1463}
1464
1465#[cfg(test)]
1466mod tests;