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