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