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