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
685impl ItemEnum {
686 /// Returns the [`ItemKind`] of this item.
687 pub fn item_kind(&self) -> ItemKind {
688 match self {
689 ItemEnum::Module(_) => ItemKind::Module,
690 ItemEnum::ExternCrate { .. } => ItemKind::ExternCrate,
691 ItemEnum::Use(_) => ItemKind::Use,
692 ItemEnum::Union(_) => ItemKind::Union,
693 ItemEnum::Struct(_) => ItemKind::Struct,
694 ItemEnum::StructField(_) => ItemKind::StructField,
695 ItemEnum::Enum(_) => ItemKind::Enum,
696 ItemEnum::Variant(_) => ItemKind::Variant,
697 ItemEnum::Function(_) => ItemKind::Function,
698 ItemEnum::Trait(_) => ItemKind::Trait,
699 ItemEnum::TraitAlias(_) => ItemKind::TraitAlias,
700 ItemEnum::Impl(_) => ItemKind::Impl,
701 ItemEnum::TypeAlias(_) => ItemKind::TypeAlias,
702 ItemEnum::Constant { .. } => ItemKind::Constant,
703 ItemEnum::Static(_) => ItemKind::Static,
704 ItemEnum::ExternType => ItemKind::ExternType,
705 ItemEnum::Macro(_) => ItemKind::Macro,
706 ItemEnum::ProcMacro(pm) => match pm.kind {
707 MacroKind::Bang => ItemKind::Macro,
708 MacroKind::Attr => ItemKind::ProcAttribute,
709 MacroKind::Derive => ItemKind::ProcDerive,
710 },
711 ItemEnum::Primitive(_) => ItemKind::Primitive,
712 ItemEnum::AssocConst { .. } => ItemKind::AssocConst,
713 ItemEnum::AssocType { .. } => ItemKind::AssocType,
714 }
715 }
716}
717
718/// A module declaration, e.g. `mod foo;` or `mod foo {}`.
719#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
720pub struct Module {
721 /// Whether this is the root item of a crate.
722 ///
723 /// This item doesn't correspond to any construction in the source code and is generated by the
724 /// compiler.
725 pub is_crate: bool,
726 /// [`Item`]s declared inside this module.
727 pub items: Vec<Id>,
728 /// If `true`, this module is not part of the public API, but it contains
729 /// items that are re-exported as public API.
730 pub is_stripped: bool,
731}
732
733/// A `union`.
734#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
735pub struct Union {
736 /// The generic parameters and where clauses on this union.
737 pub generics: Generics,
738 /// Whether any fields have been removed from the result, due to being private or hidden.
739 pub has_stripped_fields: bool,
740 /// The list of fields in the union.
741 ///
742 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
743 pub fields: Vec<Id>,
744 /// All impls (both of traits and inherent) for this union.
745 ///
746 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
747 pub impls: Vec<Id>,
748}
749
750/// A `struct`.
751#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
752pub struct Struct {
753 /// The kind of the struct (e.g. unit, tuple-like or struct-like) and the data specific to it,
754 /// i.e. fields.
755 pub kind: StructKind,
756 /// The generic parameters and where clauses on this struct.
757 pub generics: Generics,
758 /// All impls (both of traits and inherent) for this struct.
759 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Impl`].
760 pub impls: Vec<Id>,
761}
762
763/// The kind of a [`Struct`] and the data specific to it, i.e. fields.
764#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
765#[serde(rename_all = "snake_case")]
766pub enum StructKind {
767 /// A struct with no fields and no parentheses.
768 ///
769 /// ```rust
770 /// pub struct Unit;
771 /// ```
772 Unit,
773 /// A struct with unnamed fields.
774 ///
775 /// All [`Id`]'s will point to [`ItemEnum::StructField`].
776 /// Unlike most of JSON, private and `#[doc(hidden)]` fields will be given as `None`
777 /// instead of being omitted, because order matters.
778 ///
779 /// ```rust
780 /// pub struct TupleStruct(i32);
781 /// pub struct EmptyTupleStruct();
782 /// ```
783 Tuple(Vec<Option<Id>>),
784 /// A struct with named fields.
785 ///
786 /// ```rust
787 /// pub struct PlainStruct { x: i32 }
788 /// pub struct EmptyPlainStruct {}
789 /// ```
790 Plain {
791 /// The list of fields in the struct.
792 ///
793 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::StructField`].
794 fields: Vec<Id>,
795 /// Whether any fields have been removed from the result, due to being private or hidden.
796 has_stripped_fields: bool,
797 },
798}
799
800/// An `enum`.
801#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
802pub struct Enum {
803 /// Information about the type parameters and `where` clauses of the enum.
804 pub generics: Generics,
805 /// Whether any variants have been removed from the result, due to being private or hidden.
806 pub has_stripped_variants: bool,
807 /// The list of variants in the enum.
808 ///
809 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`]
810 pub variants: Vec<Id>,
811 /// `impl`s for the enum.
812 pub impls: Vec<Id>,
813}
814
815/// A variant of an enum.
816#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
817pub struct Variant {
818 /// Whether the variant is plain, a tuple-like, or struct-like. Contains the fields.
819 pub kind: VariantKind,
820 /// The discriminant, if explicitly specified.
821 pub discriminant: Option<Discriminant>,
822}
823
824/// The kind of an [`Enum`] [`Variant`] and the data specific to it, i.e. fields.
825#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
826#[serde(rename_all = "snake_case")]
827pub enum VariantKind {
828 /// A variant with no parentheses
829 ///
830 /// ```rust
831 /// enum Demo {
832 /// PlainVariant,
833 /// PlainWithDiscriminant = 1,
834 /// }
835 /// ```
836 Plain,
837 /// A variant with unnamed fields.
838 ///
839 /// All [`Id`]'s will point to [`ItemEnum::StructField`].
840 /// Unlike most of JSON, `#[doc(hidden)]` fields will be given as `None`
841 /// instead of being omitted, because order matters.
842 ///
843 /// ```rust
844 /// enum Demo {
845 /// TupleVariant(i32),
846 /// EmptyTupleVariant(),
847 /// }
848 /// ```
849 Tuple(Vec<Option<Id>>),
850 /// A variant with named fields.
851 ///
852 /// ```rust
853 /// enum Demo {
854 /// StructVariant { x: i32 },
855 /// EmptyStructVariant {},
856 /// }
857 /// ```
858 Struct {
859 /// The list of variants in the enum.
860 /// All of the corresponding [`Item`]s are of kind [`ItemEnum::Variant`].
861 fields: Vec<Id>,
862 /// Whether any variants have been removed from the result, due to being private or hidden.
863 has_stripped_fields: bool,
864 },
865}
866
867/// The value that distinguishes a variant in an [`Enum`] from other variants.
868#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
869pub struct Discriminant {
870 /// The expression that produced the discriminant.
871 ///
872 /// Unlike `value`, this preserves the original formatting (eg suffixes,
873 /// hexadecimal, and underscores), making it unsuitable to be machine
874 /// interpreted.
875 ///
876 /// In some cases, when the value is too complex, this may be `"{ _ }"`.
877 /// When this occurs is unstable, and may change without notice.
878 pub expr: String,
879 /// The numerical value of the discriminant. Stored as a string due to
880 /// JSON's poor support for large integers, and the fact that it would need
881 /// to store from [`i128::MIN`] to [`u128::MAX`].
882 pub value: String,
883}
884
885/// A set of fundamental properties of a function.
886#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
887pub struct FunctionHeader {
888 /// Is this function marked as `const`?
889 pub is_const: bool,
890 /// Is this function unsafe?
891 pub is_unsafe: bool,
892 /// Is this function async?
893 pub is_async: bool,
894 /// The ABI used by the function.
895 pub abi: Abi,
896}
897
898/// The ABI (Application Binary Interface) used by a function.
899///
900/// If a variant has an `unwind` field, this means the ABI that it represents can be specified in 2
901/// ways: `extern "_"` and `extern "_-unwind"`, and a value of `true` for that field signifies the
902/// latter variant.
903///
904/// See the [Rustonomicon section](https://doc.rust-lang.org/nightly/nomicon/ffi.html#ffi-and-unwinding)
905/// on unwinding for more info.
906#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
907pub enum Abi {
908 // We only have a concrete listing here for stable ABI's because there are so many
909 // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
910 /// The default ABI, but that can also be written explicitly with `extern "Rust"`.
911 Rust,
912 /// Can be specified as `extern "C"` or, as a shorthand, just `extern`.
913 C { unwind: bool },
914 /// Can be specified as `extern "cdecl"`.
915 Cdecl { unwind: bool },
916 /// Can be specified as `extern "stdcall"`.
917 Stdcall { unwind: bool },
918 /// Can be specified as `extern "fastcall"`.
919 Fastcall { unwind: bool },
920 /// Can be specified as `extern "aapcs"`.
921 Aapcs { unwind: bool },
922 /// Can be specified as `extern "win64"`.
923 Win64 { unwind: bool },
924 /// Can be specified as `extern "sysv64"`.
925 SysV64 { unwind: bool },
926 /// Can be specified as `extern "system"`.
927 System { unwind: bool },
928 /// Any other ABI, including unstable ones.
929 Other(String),
930}
931
932/// A function declaration (including methods and other associated functions).
933#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
934pub struct Function {
935 /// Information about the function signature, or declaration.
936 pub sig: FunctionSignature,
937 /// Information about the function’s type parameters and `where` clauses.
938 pub generics: Generics,
939 /// Information about core properties of the function, e.g. whether it's `const`, its ABI, etc.
940 pub header: FunctionHeader,
941 /// Whether the function has a body, i.e. an implementation.
942 pub has_body: bool,
943}
944
945/// Generic parameters accepted by an item and `where` clauses imposed on it and the parameters.
946#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
947pub struct Generics {
948 /// A list of generic parameter definitions (e.g. `<T: Clone + Hash, U: Copy>`).
949 pub params: Vec<GenericParamDef>,
950 /// A list of where predicates (e.g. `where T: Iterator, T::Item: Copy`).
951 pub where_predicates: Vec<WherePredicate>,
952}
953
954/// One generic parameter accepted by an item.
955#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
956pub struct GenericParamDef {
957 /// Name of the parameter.
958 /// ```rust
959 /// fn f<'resource, Resource>(x: &'resource Resource) {}
960 /// // ^^^^^^^^ ^^^^^^^^
961 /// ```
962 pub name: String,
963 /// The kind of the parameter and data specific to a particular parameter kind, e.g. type
964 /// bounds.
965 pub kind: GenericParamDefKind,
966}
967
968/// The kind of a [`GenericParamDef`].
969#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
970#[serde(rename_all = "snake_case")]
971pub enum GenericParamDefKind {
972 /// Denotes a lifetime parameter.
973 Lifetime {
974 /// Lifetimes that this lifetime parameter is required to outlive.
975 ///
976 /// ```rust
977 /// fn f<'a, 'b, 'resource: 'a + 'b>(a: &'a str, b: &'b str, res: &'resource str) {}
978 /// // ^^^^^^^
979 /// ```
980 outlives: Vec<String>,
981 },
982
983 /// Denotes a type parameter.
984 Type {
985 /// Bounds applied directly to the type. Note that the bounds from `where` clauses
986 /// that constrain this parameter won't appear here.
987 ///
988 /// ```rust
989 /// fn default2<T: Default>() -> [T; 2] where T: Clone { todo!() }
990 /// // ^^^^^^^
991 /// ```
992 bounds: Vec<GenericBound>,
993 /// The default type for this parameter, if provided, e.g.
994 ///
995 /// ```rust
996 /// trait PartialEq<Rhs = Self> {}
997 /// // ^^^^
998 /// ```
999 default: Option<Type>,
1000 /// This is normally `false`, which means that this generic parameter is
1001 /// declared in the Rust source text.
1002 ///
1003 /// If it is `true`, this generic parameter has been introduced by the
1004 /// compiler behind the scenes.
1005 ///
1006 /// # Example
1007 ///
1008 /// Consider
1009 ///
1010 /// ```ignore (pseudo-rust)
1011 /// pub fn f(_: impl Trait) {}
1012 /// ```
1013 ///
1014 /// The compiler will transform this behind the scenes to
1015 ///
1016 /// ```ignore (pseudo-rust)
1017 /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
1018 /// ```
1019 ///
1020 /// In this example, the generic parameter named `impl Trait` (and which
1021 /// is bound by `Trait`) is synthetic, because it was not originally in
1022 /// the Rust source text.
1023 is_synthetic: bool,
1024 },
1025
1026 /// Denotes a constant parameter.
1027 Const {
1028 /// The type of the constant as declared.
1029 #[serde(rename = "type")]
1030 type_: Type,
1031 /// The stringified expression for the default value, if provided. It's not guaranteed that
1032 /// it'll match the actual source code for the default value.
1033 default: Option<String>,
1034 },
1035}
1036
1037/// One `where` clause.
1038/// ```rust
1039/// fn default<T>() -> T where T: Default { T::default() }
1040/// // ^^^^^^^^^^
1041/// ```
1042#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1043#[serde(rename_all = "snake_case")]
1044pub enum WherePredicate {
1045 /// A type is expected to comply with a set of bounds
1046 BoundPredicate {
1047 /// The type that's being constrained.
1048 ///
1049 /// ```rust
1050 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1051 /// // ^
1052 /// ```
1053 #[serde(rename = "type")]
1054 type_: Type,
1055 /// The set of bounds that constrain the type.
1056 ///
1057 /// ```rust
1058 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1059 /// // ^^^^^^^^
1060 /// ```
1061 bounds: Vec<GenericBound>,
1062 /// Used for Higher-Rank Trait Bounds (HRTBs)
1063 /// ```rust
1064 /// fn f<T>(x: T) where for<'a> &'a T: Iterator {}
1065 /// // ^^^^^^^
1066 /// ```
1067 generic_params: Vec<GenericParamDef>,
1068 },
1069
1070 /// A lifetime is expected to outlive other lifetimes.
1071 LifetimePredicate {
1072 /// The name of the lifetime.
1073 lifetime: String,
1074 /// The lifetimes that must be encompassed by the lifetime.
1075 outlives: Vec<String>,
1076 },
1077
1078 /// A type must exactly equal another type.
1079 EqPredicate {
1080 /// The left side of the equation.
1081 lhs: Type,
1082 /// The right side of the equation.
1083 rhs: Term,
1084 },
1085}
1086
1087/// Either a trait bound or a lifetime bound.
1088#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1089#[serde(rename_all = "snake_case")]
1090pub enum GenericBound {
1091 /// A trait bound.
1092 TraitBound {
1093 /// The full path to the trait.
1094 #[serde(rename = "trait")]
1095 trait_: Path,
1096 /// Used for Higher-Rank Trait Bounds (HRTBs)
1097 /// ```text
1098 /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
1099 /// ^^^^^^^^^^^
1100 /// |
1101 /// this part
1102 /// ```
1103 generic_params: Vec<GenericParamDef>,
1104 /// The context for which a trait is supposed to be used, e.g. `const
1105 modifier: TraitBoundModifier,
1106 },
1107 /// A lifetime bound, e.g.
1108 /// ```rust
1109 /// fn f<'a, T>(x: &'a str, y: &T) where T: 'a {}
1110 /// // ^^^
1111 /// ```
1112 Outlives(String),
1113 /// `use<'a, T>` precise-capturing bound syntax
1114 Use(Vec<PreciseCapturingArg>),
1115}
1116
1117/// A set of modifiers applied to a trait.
1118#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1119#[serde(rename_all = "snake_case")]
1120pub enum TraitBoundModifier {
1121 /// Marks the absence of a modifier.
1122 None,
1123 /// Indicates that the trait bound relaxes a trait bound applied to a parameter by default,
1124 /// e.g. `T: Sized?`, the `Sized` trait is required for all generic type parameters by default
1125 /// unless specified otherwise with this modifier.
1126 Maybe,
1127 /// Indicates that the trait bound must be applicable in both a run-time and a compile-time
1128 /// context.
1129 MaybeConst,
1130}
1131
1132/// One precise capturing argument. See [the rust reference](https://doc.rust-lang.org/reference/types/impl-trait.html#precise-capturing).
1133#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1134#[serde(rename_all = "snake_case")]
1135pub enum PreciseCapturingArg {
1136 /// A lifetime.
1137 /// ```rust
1138 /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1139 /// // ^^
1140 Lifetime(String),
1141 /// A type or constant parameter.
1142 /// ```rust
1143 /// pub fn hello<'a, T, const N: usize>() -> impl Sized + use<'a, T, N> {}
1144 /// // ^ ^
1145 Param(String),
1146}
1147
1148/// Either a type or a constant, usually stored as the right-hand side of an equation in places like
1149/// [`AssocItemConstraint`]
1150#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1151#[serde(rename_all = "snake_case")]
1152pub enum Term {
1153 /// A type.
1154 ///
1155 /// ```rust
1156 /// fn f(x: impl IntoIterator<Item = u32>) {}
1157 /// // ^^^
1158 /// ```
1159 Type(Type),
1160 /// A constant.
1161 ///
1162 /// ```ignore (incomplete feature in the snippet)
1163 /// trait Foo {
1164 /// const BAR: usize;
1165 /// }
1166 ///
1167 /// fn f(x: impl Foo<BAR = 42>) {}
1168 /// // ^^
1169 /// ```
1170 Constant(Constant),
1171}
1172
1173/// A type.
1174#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1175#[serde(rename_all = "snake_case")]
1176pub enum Type {
1177 /// Structs, enums, unions and type aliases, e.g. `std::option::Option<u32>`
1178 ResolvedPath(Path),
1179 /// Dynamic trait object type (`dyn Trait`).
1180 DynTrait(DynTrait),
1181 /// Parameterized types. The contained string is the name of the parameter.
1182 Generic(String),
1183 /// Built-in numeric types (e.g. `u32`, `f32`), `bool`, `char`.
1184 Primitive(String),
1185 /// A function pointer type, e.g. `fn(u32) -> u32`, `extern "C" fn() -> *const u8`
1186 FunctionPointer(Box<FunctionPointer>),
1187 /// A tuple type, e.g. `(String, u32, Box<usize>)`
1188 Tuple(Vec<Type>),
1189 /// An unsized slice type, e.g. `[u32]`.
1190 Slice(Box<Type>),
1191 /// An array type, e.g. `[u32; 15]`
1192 Array {
1193 /// The type of the contained element.
1194 #[serde(rename = "type")]
1195 type_: Box<Type>,
1196 /// The stringified expression that is the length of the array.
1197 ///
1198 /// Keep in mind that it's not guaranteed to match the actual source code of the expression.
1199 len: String,
1200 },
1201 /// A pattern type, e.g. `u32 is 1..`
1202 ///
1203 /// See [the tracking issue](https://github.com/rust-lang/rust/issues/123646)
1204 Pat {
1205 /// The base type, e.g. the `u32` in `u32 is 1..`
1206 #[serde(rename = "type")]
1207 type_: Box<Type>,
1208 #[doc(hidden)]
1209 __pat_unstable_do_not_use: String,
1210 },
1211 /// An opaque type that satisfies a set of bounds, `impl TraitA + TraitB + ...`
1212 ImplTrait(Vec<GenericBound>),
1213 /// A type that's left to be inferred, `_`
1214 Infer,
1215 /// A raw pointer type, e.g. `*mut u32`, `*const u8`, etc.
1216 RawPointer {
1217 /// This is `true` for `*mut _` and `false` for `*const _`.
1218 is_mutable: bool,
1219 /// The type of the pointee.
1220 #[serde(rename = "type")]
1221 type_: Box<Type>,
1222 },
1223 /// `&'a mut String`, `&str`, etc.
1224 BorrowedRef {
1225 /// The name of the lifetime of the reference, if provided.
1226 lifetime: Option<String>,
1227 /// This is `true` for `&mut i32` and `false` for `&i32`
1228 is_mutable: bool,
1229 /// The type of the pointee, e.g. the `i32` in `&'a mut i32`
1230 #[serde(rename = "type")]
1231 type_: Box<Type>,
1232 },
1233 /// Associated types like `<Type as Trait>::Name` and `T::Item` where
1234 /// `T: Iterator` or inherent associated types like `Struct::Name`.
1235 QualifiedPath {
1236 /// The name of the associated type in the parent type.
1237 ///
1238 /// ```ignore (incomplete expression)
1239 /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1240 /// // ^^^^
1241 /// ```
1242 name: String,
1243 /// The generic arguments provided to the associated type.
1244 ///
1245 /// ```ignore (incomplete expression)
1246 /// <core::slice::IterMut<'static, u32> as BetterIterator>::Item<'static>
1247 /// // ^^^^^^^^^
1248 /// ```
1249 args: Option<Box<GenericArgs>>,
1250 /// The type with which this type is associated.
1251 ///
1252 /// ```ignore (incomplete expression)
1253 /// <core::array::IntoIter<u32, 42> as Iterator>::Item
1254 /// // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1255 /// ```
1256 self_type: Box<Type>,
1257 /// `None` iff this is an *inherent* associated type.
1258 #[serde(rename = "trait")]
1259 trait_: Option<Path>,
1260 },
1261}
1262
1263/// A type that has a simple path to it. This is the kind of type of structs, unions, enums, etc.
1264#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1265pub struct Path {
1266 /// The path of the type.
1267 ///
1268 /// This will be the path that is *used* (not where it is defined), so
1269 /// multiple `Path`s may have different values for this field even if
1270 /// they all refer to the same item. e.g.
1271 ///
1272 /// ```rust
1273 /// pub type Vec1 = std::vec::Vec<i32>; // path: "std::vec::Vec"
1274 /// pub type Vec2 = Vec<i32>; // path: "Vec"
1275 /// pub type Vec3 = std::prelude::v1::Vec<i32>; // path: "std::prelude::v1::Vec"
1276 /// ```
1277 //
1278 // Example tested in ./tests/rustdoc-json/path_name.rs
1279 pub path: String,
1280 /// The ID of the type.
1281 pub id: Id,
1282 /// Generic arguments to the type.
1283 ///
1284 /// ```ignore (incomplete expression)
1285 /// std::borrow::Cow<'static, str>
1286 /// // ^^^^^^^^^^^^^^
1287 /// ```
1288 pub args: Option<Box<GenericArgs>>,
1289}
1290
1291/// A type that is a function pointer.
1292#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1293pub struct FunctionPointer {
1294 /// The signature of the function.
1295 pub sig: FunctionSignature,
1296 /// Used for Higher-Rank Trait Bounds (HRTBs)
1297 ///
1298 /// ```ignore (incomplete expression)
1299 /// for<'c> fn(val: &'c i32) -> i32
1300 /// // ^^^^^^^
1301 /// ```
1302 pub generic_params: Vec<GenericParamDef>,
1303 /// The core properties of the function, such as the ABI it conforms to, whether it's unsafe, etc.
1304 pub header: FunctionHeader,
1305}
1306
1307/// The signature of a function.
1308#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1309pub struct FunctionSignature {
1310 /// List of argument names and their type.
1311 ///
1312 /// Note that not all names will be valid identifiers, as some of
1313 /// them may be patterns.
1314 pub inputs: Vec<(String, Type)>,
1315 /// The output type, if specified.
1316 pub output: Option<Type>,
1317 /// Whether the function accepts an arbitrary amount of trailing arguments the C way.
1318 ///
1319 /// ```ignore (incomplete code)
1320 /// fn printf(fmt: &str, ...);
1321 /// ```
1322 pub is_c_variadic: bool,
1323}
1324
1325/// A `trait` declaration.
1326#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1327pub struct Trait {
1328 /// Whether the trait is marked `auto` and is thus implemented automatically
1329 /// for all applicable types.
1330 pub is_auto: bool,
1331 /// Whether the trait is marked as `unsafe`.
1332 pub is_unsafe: bool,
1333 /// Whether the trait is [dyn compatible](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility)[^1].
1334 ///
1335 /// [^1]: Formerly known as "object safe".
1336 pub is_dyn_compatible: bool,
1337 /// Associated [`Item`]s that can/must be implemented by the `impl` blocks.
1338 pub items: Vec<Id>,
1339 /// Information about the type parameters and `where` clauses of the trait.
1340 pub generics: Generics,
1341 /// Constraints that must be met by the implementor of the trait.
1342 pub bounds: Vec<GenericBound>,
1343 /// The implementations of the trait.
1344 pub implementations: Vec<Id>,
1345}
1346
1347/// A trait alias declaration, e.g. `trait Int = Add + Sub + Mul + Div;`
1348///
1349/// See [the tracking issue](https://github.com/rust-lang/rust/issues/41517)
1350#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1351pub struct TraitAlias {
1352 /// Information about the type parameters and `where` clauses of the alias.
1353 pub generics: Generics,
1354 /// The bounds that are associated with the alias.
1355 pub params: Vec<GenericBound>,
1356}
1357
1358/// An `impl` block.
1359#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1360pub struct Impl {
1361 /// Whether this impl is for an unsafe trait.
1362 pub is_unsafe: bool,
1363 /// Information about the impl’s type parameters and `where` clauses.
1364 pub generics: Generics,
1365 /// The list of the names of all the trait methods that weren't mentioned in this impl but
1366 /// were provided by the trait itself.
1367 ///
1368 /// For example, for this impl of the [`PartialEq`] trait:
1369 /// ```rust
1370 /// struct Foo;
1371 ///
1372 /// impl PartialEq for Foo {
1373 /// fn eq(&self, other: &Self) -> bool { todo!() }
1374 /// }
1375 /// ```
1376 /// This field will be `["ne"]`, as it has a default implementation defined for it.
1377 pub provided_trait_methods: Vec<String>,
1378 /// The trait being implemented or `None` if the impl is inherent, which means
1379 /// `impl Struct {}` as opposed to `impl Trait for Struct {}`.
1380 #[serde(rename = "trait")]
1381 pub trait_: Option<Path>,
1382 /// The type that the impl block is for.
1383 #[serde(rename = "for")]
1384 pub for_: Type,
1385 /// The list of associated items contained in this impl block.
1386 pub items: Vec<Id>,
1387 /// Whether this is a negative impl (e.g. `!Sized` or `!Send`).
1388 pub is_negative: bool,
1389 /// Whether this is an impl that’s implied by the compiler
1390 /// (for autotraits, e.g. `Send` or `Sync`).
1391 pub is_synthetic: bool,
1392 // FIXME: document this
1393 pub blanket_impl: Option<Type>,
1394}
1395
1396/// A `use` statement.
1397#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1398#[serde(rename_all = "snake_case")]
1399pub struct Use {
1400 /// The full path being imported.
1401 pub source: String,
1402 /// May be different from the last segment of `source` when renaming imports:
1403 /// `use source as name;`
1404 pub name: String,
1405 /// The ID of the item being imported. Will be `None` in case of re-exports of primitives:
1406 /// ```rust
1407 /// pub use i32 as my_i32;
1408 /// ```
1409 pub id: Option<Id>,
1410 /// Whether this statement is a wildcard `use`, e.g. `use source::*;`
1411 pub is_glob: bool,
1412}
1413
1414/// A procedural macro.
1415#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1416pub struct ProcMacro {
1417 /// How this macro is supposed to be called: `foo!()`, `#[foo]` or `#[derive(foo)]`
1418 pub kind: MacroKind,
1419 /// Helper attributes defined by a macro to be used inside it.
1420 ///
1421 /// Defined only for derive macros.
1422 ///
1423 /// E.g. the [`Default`] derive macro defines a `#[default]` helper attribute so that one can
1424 /// do:
1425 ///
1426 /// ```rust
1427 /// #[derive(Default)]
1428 /// enum Option<T> {
1429 /// #[default]
1430 /// None,
1431 /// Some(T),
1432 /// }
1433 /// ```
1434 pub helpers: Vec<String>,
1435}
1436
1437/// The way a [`ProcMacro`] is declared to be used.
1438#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1439#[serde(rename_all = "snake_case")]
1440pub enum MacroKind {
1441 /// A bang macro `foo!()`.
1442 Bang,
1443 /// An attribute macro `#[foo]`.
1444 Attr,
1445 /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]`
1446 Derive,
1447}
1448
1449/// A type alias declaration, e.g. `type Pig = std::borrow::Cow<'static, str>;`
1450#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1451pub struct TypeAlias {
1452 /// The type referred to by this alias.
1453 #[serde(rename = "type")]
1454 pub type_: Type,
1455 /// Information about the type parameters and `where` clauses of the alias.
1456 pub generics: Generics,
1457}
1458
1459/// A `static` declaration.
1460#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1461pub struct Static {
1462 /// The type of the static.
1463 #[serde(rename = "type")]
1464 pub type_: Type,
1465 /// This is `true` for mutable statics, declared as `static mut X: T = f();`
1466 pub is_mutable: bool,
1467 /// The stringified expression for the initial value.
1468 ///
1469 /// It's not guaranteed that it'll match the actual source code for the initial value.
1470 pub expr: String,
1471
1472 /// Is the static `unsafe`?
1473 ///
1474 /// This is only true if it's in an `extern` block, and not explicitly marked
1475 /// as `safe`.
1476 ///
1477 /// ```rust
1478 /// unsafe extern {
1479 /// static A: i32; // unsafe
1480 /// safe static B: i32; // safe
1481 /// }
1482 ///
1483 /// static C: i32 = 0; // safe
1484 /// static mut D: i32 = 0; // safe
1485 /// ```
1486 pub is_unsafe: bool,
1487}
1488
1489/// A primitive type declaration. Declarations of this kind can only come from the core library.
1490#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1491pub struct Primitive {
1492 /// The name of the type.
1493 pub name: String,
1494 /// The implementations, inherent and of traits, on the primitive type.
1495 pub impls: Vec<Id>,
1496}
1497
1498#[cfg(test)]
1499mod tests;