]> git.lizzy.rs Git - rust.git/blob - src/rustdoc-json-types/lib.rs
Rollup merge of #96334 - devnexen:socket_mark, r=dtolnay
[rust.git] / src / 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 use std::collections::HashMap;
7 use std::path::PathBuf;
8
9 use serde::{Deserialize, Serialize};
10
11 /// rustdoc format-version.
12 pub const FORMAT_VERSION: u32 = 18;
13
14 /// A `Crate` is the root of the emitted JSON blob. It contains all type/documentation information
15 /// about the language items in the local crate, as well as info about external items to allow
16 /// tools to find or link to them.
17 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
18 pub struct Crate {
19     /// The id of the root [`Module`] item of the local crate.
20     pub root: Id,
21     /// The version string given to `--crate-version`, if any.
22     pub crate_version: Option<String>,
23     /// Whether or not the output includes private items.
24     pub includes_private: bool,
25     /// A collection of all items in the local crate as well as some external traits and their
26     /// items that are referenced locally.
27     pub index: HashMap<Id, Item>,
28     /// Maps IDs to fully qualified paths and other info helpful for generating links.
29     pub paths: HashMap<Id, ItemSummary>,
30     /// Maps `crate_id` of items to a crate name and html_root_url if it exists.
31     pub external_crates: HashMap<u32, ExternalCrate>,
32     /// A single version number to be used in the future when making backwards incompatible changes
33     /// to the JSON output.
34     pub format_version: u32,
35 }
36
37 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
38 pub struct ExternalCrate {
39     pub name: String,
40     pub html_root_url: Option<String>,
41 }
42
43 /// For external (not defined in the local crate) items, you don't get the same level of
44 /// information. This struct should contain enough to generate a link/reference to the item in
45 /// question, or can be used by a tool that takes the json output of multiple crates to find
46 /// the actual item definition with all the relevant info.
47 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
48 pub struct ItemSummary {
49     /// Can be used to look up the name and html_root_url of the crate this item came from in the
50     /// `external_crates` map.
51     pub crate_id: u32,
52     /// The list of path components for the fully qualified path of this item (e.g.
53     /// `["std", "io", "lazy", "Lazy"]` for `std::io::lazy::Lazy`).
54     pub path: Vec<String>,
55     /// Whether this item is a struct, trait, macro, etc.
56     pub kind: ItemKind,
57 }
58
59 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60 pub struct Item {
61     /// The unique identifier of this item. Can be used to find this item in various mappings.
62     pub id: Id,
63     /// This can be used as a key to the `external_crates` map of [`Crate`] to see which crate
64     /// this item came from.
65     pub crate_id: u32,
66     /// Some items such as impls don't have names.
67     pub name: Option<String>,
68     /// The source location of this item (absent if it came from a macro expansion or inline
69     /// assembly).
70     pub span: Option<Span>,
71     /// By default all documented items are public, but you can tell rustdoc to output private items
72     /// so this field is needed to differentiate.
73     pub visibility: Visibility,
74     /// The full markdown docstring of this item. Absent if there is no documentation at all,
75     /// Some("") if there is some documentation but it is empty (EG `#[doc = ""]`).
76     pub docs: Option<String>,
77     /// 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
78     pub links: HashMap<String, Id>,
79     /// Stringified versions of the attributes on this item (e.g. `"#[inline]"`)
80     pub attrs: Vec<String>,
81     pub deprecation: Option<Deprecation>,
82     #[serde(flatten)]
83     pub inner: ItemEnum,
84 }
85
86 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
87 pub struct Span {
88     /// The path to the source file for this span relative to the path `rustdoc` was invoked with.
89     pub filename: PathBuf,
90     /// Zero indexed Line and Column of the first character of the `Span`
91     pub begin: (usize, usize),
92     /// Zero indexed Line and Column of the last character of the `Span`
93     pub end: (usize, usize),
94 }
95
96 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
97 pub struct Deprecation {
98     pub since: Option<String>,
99     pub note: Option<String>,
100 }
101
102 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
103 #[serde(rename_all = "snake_case")]
104 pub enum Visibility {
105     Public,
106     /// For the most part items are private by default. The exceptions are associated items of
107     /// public traits and variants of public enums.
108     Default,
109     Crate,
110     /// For `pub(in path)` visibility. `parent` is the module it's restricted to and `path` is how
111     /// that module was referenced (like `"super::super"` or `"crate::foo::bar"`).
112     Restricted {
113         parent: Id,
114         path: String,
115     },
116 }
117
118 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
119 pub struct DynTrait {
120     /// All the traits implemented. One of them is the vtable, and the rest must be auto traits.
121     pub traits: Vec<PolyTrait>,
122     /// The lifetime of the whole dyn object
123     /// ```text
124     /// dyn Debug + 'static
125     ///             ^^^^^^^
126     ///             |
127     ///             this part
128     /// ```
129     pub lifetime: Option<String>,
130 }
131
132 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
133 /// A trait and potential HRTBs
134 pub struct PolyTrait {
135     #[serde(rename = "trait")]
136     pub trait_: Path,
137     /// Used for Higher-Rank Trait Bounds (HRTBs)
138     /// ```text
139     /// dyn for<'a> Fn() -> &'a i32"
140     ///     ^^^^^^^
141     ///       |
142     ///       this part
143     /// ```
144     pub generic_params: Vec<GenericParamDef>,
145 }
146
147 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
148 #[serde(rename_all = "snake_case")]
149 pub enum GenericArgs {
150     /// <'a, 32, B: Copy, C = u32>
151     AngleBracketed { args: Vec<GenericArg>, bindings: Vec<TypeBinding> },
152     /// Fn(A, B) -> C
153     Parenthesized { inputs: Vec<Type>, output: Option<Type> },
154 }
155
156 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
157 #[serde(rename_all = "snake_case")]
158 pub enum GenericArg {
159     Lifetime(String),
160     Type(Type),
161     Const(Constant),
162     Infer,
163 }
164
165 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
166 pub struct Constant {
167     #[serde(rename = "type")]
168     pub type_: Type,
169     pub expr: String,
170     pub value: Option<String>,
171     pub is_literal: bool,
172 }
173
174 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
175 pub struct TypeBinding {
176     pub name: String,
177     pub args: GenericArgs,
178     pub binding: TypeBindingKind,
179 }
180
181 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
182 #[serde(rename_all = "snake_case")]
183 pub enum TypeBindingKind {
184     Equality(Term),
185     Constraint(Vec<GenericBound>),
186 }
187
188 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
189 pub struct Id(pub String);
190
191 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
192 #[serde(rename_all = "snake_case")]
193 pub enum ItemKind {
194     Module,
195     ExternCrate,
196     Import,
197     Struct,
198     StructField,
199     Union,
200     Enum,
201     Variant,
202     Function,
203     Typedef,
204     OpaqueTy,
205     Constant,
206     Trait,
207     TraitAlias,
208     Method,
209     Impl,
210     Static,
211     ForeignType,
212     Macro,
213     ProcAttribute,
214     ProcDerive,
215     AssocConst,
216     AssocType,
217     Primitive,
218     Keyword,
219 }
220
221 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
222 #[serde(tag = "kind", content = "inner", rename_all = "snake_case")]
223 pub enum ItemEnum {
224     Module(Module),
225     ExternCrate {
226         name: String,
227         rename: Option<String>,
228     },
229     Import(Import),
230
231     Union(Union),
232     Struct(Struct),
233     StructField(Type),
234     Enum(Enum),
235     Variant(Variant),
236
237     Function(Function),
238
239     Trait(Trait),
240     TraitAlias(TraitAlias),
241     Method(Method),
242     Impl(Impl),
243
244     Typedef(Typedef),
245     OpaqueTy(OpaqueTy),
246     Constant(Constant),
247
248     Static(Static),
249
250     /// `type`s from an extern block
251     ForeignType,
252
253     /// Declarative macro_rules! macro
254     Macro(String),
255     ProcMacro(ProcMacro),
256
257     PrimitiveType(String),
258
259     AssocConst {
260         #[serde(rename = "type")]
261         type_: Type,
262         /// e.g. `const X: usize = 5;`
263         default: Option<String>,
264     },
265     AssocType {
266         generics: Generics,
267         bounds: Vec<GenericBound>,
268         /// e.g. `type X = usize;`
269         default: Option<Type>,
270     },
271 }
272
273 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
274 pub struct Module {
275     pub is_crate: bool,
276     pub items: Vec<Id>,
277     /// If `true`, this module is not part of the public API, but it contains
278     /// items that are re-exported as public API.
279     pub is_stripped: bool,
280 }
281
282 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
283 pub struct Union {
284     pub generics: Generics,
285     pub fields_stripped: bool,
286     pub fields: Vec<Id>,
287     pub impls: Vec<Id>,
288 }
289
290 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
291 pub struct Struct {
292     pub struct_type: StructType,
293     pub generics: Generics,
294     pub fields_stripped: bool,
295     pub fields: Vec<Id>,
296     pub impls: Vec<Id>,
297 }
298
299 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
300 pub struct Enum {
301     pub generics: Generics,
302     pub variants_stripped: bool,
303     pub variants: Vec<Id>,
304     pub impls: Vec<Id>,
305 }
306
307 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
308 #[serde(rename_all = "snake_case")]
309 #[serde(tag = "variant_kind", content = "variant_inner")]
310 pub enum Variant {
311     Plain,
312     Tuple(Vec<Type>),
313     Struct(Vec<Id>),
314 }
315
316 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
317 #[serde(rename_all = "snake_case")]
318 pub enum StructType {
319     Plain,
320     Tuple,
321     Unit,
322 }
323
324 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
325 pub struct Header {
326     #[serde(rename = "const")]
327     pub const_: bool,
328     #[serde(rename = "unsafe")]
329     pub unsafe_: bool,
330     #[serde(rename = "async")]
331     pub async_: bool,
332     pub abi: Abi,
333 }
334
335 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
336 pub enum Abi {
337     // We only have a concrete listing here for stable ABI's because their are so many
338     // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
339     Rust,
340     C { unwind: bool },
341     Cdecl { unwind: bool },
342     Stdcall { unwind: bool },
343     Fastcall { unwind: bool },
344     Aapcs { unwind: bool },
345     Win64 { unwind: bool },
346     SysV64 { unwind: bool },
347     System { unwind: bool },
348     Other(String),
349 }
350
351 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
352 pub struct Function {
353     pub decl: FnDecl,
354     pub generics: Generics,
355     pub header: Header,
356 }
357
358 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
359 pub struct Method {
360     pub decl: FnDecl,
361     pub generics: Generics,
362     pub header: Header,
363     pub has_body: bool,
364 }
365
366 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
367 pub struct Generics {
368     pub params: Vec<GenericParamDef>,
369     pub where_predicates: Vec<WherePredicate>,
370 }
371
372 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
373 pub struct GenericParamDef {
374     pub name: String,
375     pub kind: GenericParamDefKind,
376 }
377
378 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
379 #[serde(rename_all = "snake_case")]
380 pub enum GenericParamDefKind {
381     Lifetime {
382         outlives: Vec<String>,
383     },
384     Type {
385         bounds: Vec<GenericBound>,
386         default: Option<Type>,
387         /// This is normally `false`, which means that this generic parameter is
388         /// declared in the Rust source text.
389         ///
390         /// If it is `true`, this generic parameter has been introduced by the
391         /// compiler behind the scenes.
392         ///
393         /// # Example
394         ///
395         /// Consider
396         ///
397         /// ```ignore (pseudo-rust)
398         /// pub fn f(_: impl Trait) {}
399         /// ```
400         ///
401         /// The compiler will transform this behind the scenes to
402         ///
403         /// ```ignore (pseudo-rust)
404         /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
405         /// ```
406         ///
407         /// In this example, the generic parameter named `impl Trait` (and which
408         /// is bound by `Trait`) is synthetic, because it was not originally in
409         /// the Rust source text.
410         synthetic: bool,
411     },
412     Const {
413         #[serde(rename = "type")]
414         type_: Type,
415         default: Option<String>,
416     },
417 }
418
419 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
420 #[serde(rename_all = "snake_case")]
421 pub enum WherePredicate {
422     BoundPredicate {
423         #[serde(rename = "type")]
424         type_: Type,
425         bounds: Vec<GenericBound>,
426         /// Used for Higher-Rank Trait Bounds (HRTBs)
427         /// ```text
428         /// where for<'a> &'a T: Iterator,"
429         ///       ^^^^^^^
430         ///       |
431         ///       this part
432         /// ```
433         generic_params: Vec<GenericParamDef>,
434     },
435     RegionPredicate {
436         lifetime: String,
437         bounds: Vec<GenericBound>,
438     },
439     EqPredicate {
440         lhs: Type,
441         rhs: Term,
442     },
443 }
444
445 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
446 #[serde(rename_all = "snake_case")]
447 pub enum GenericBound {
448     TraitBound {
449         #[serde(rename = "trait")]
450         trait_: Path,
451         /// Used for Higher-Rank Trait Bounds (HRTBs)
452         /// ```text
453         /// where F: for<'a, 'b> Fn(&'a u8, &'b u8)
454         ///          ^^^^^^^^^^^
455         ///          |
456         ///          this part
457         /// ```
458         generic_params: Vec<GenericParamDef>,
459         modifier: TraitBoundModifier,
460     },
461     Outlives(String),
462 }
463
464 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
465 #[serde(rename_all = "snake_case")]
466 pub enum TraitBoundModifier {
467     None,
468     Maybe,
469     MaybeConst,
470 }
471
472 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
473 #[serde(rename_all = "snake_case")]
474 pub enum Term {
475     Type(Type),
476     Constant(Constant),
477 }
478
479 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
480 #[serde(rename_all = "snake_case")]
481 #[serde(tag = "kind", content = "inner")]
482 pub enum Type {
483     /// Structs, enums, and traits
484     ResolvedPath(Path),
485     DynTrait(DynTrait),
486     /// Parameterized types
487     Generic(String),
488     /// Fixed-size numeric types (plus int/usize/float), char, arrays, slices, and tuples
489     Primitive(String),
490     /// `extern "ABI" fn`
491     FunctionPointer(Box<FunctionPointer>),
492     /// `(String, u32, Box<usize>)`
493     Tuple(Vec<Type>),
494     /// `[u32]`
495     Slice(Box<Type>),
496     /// [u32; 15]
497     Array {
498         #[serde(rename = "type")]
499         type_: Box<Type>,
500         len: String,
501     },
502     /// `impl TraitA + TraitB + ...`
503     ImplTrait(Vec<GenericBound>),
504     /// `_`
505     Infer,
506     /// `*mut u32`, `*u8`, etc.
507     RawPointer {
508         mutable: bool,
509         #[serde(rename = "type")]
510         type_: Box<Type>,
511     },
512     /// `&'a mut String`, `&str`, etc.
513     BorrowedRef {
514         lifetime: Option<String>,
515         mutable: bool,
516         #[serde(rename = "type")]
517         type_: Box<Type>,
518     },
519     /// `<Type as Trait>::Name` or associated types like `T::Item` where `T: Iterator`
520     QualifiedPath {
521         name: String,
522         args: Box<GenericArgs>,
523         self_type: Box<Type>,
524         #[serde(rename = "trait")]
525         trait_: Path,
526     },
527 }
528
529 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
530 pub struct Path {
531     pub name: String,
532     pub id: Id,
533     /// Generic arguments to the type
534     /// ```test
535     /// std::borrow::Cow<'static, str>
536     ///                 ^^^^^^^^^^^^^^
537     ///                 |
538     ///                 this part
539     /// ```
540     pub args: Option<Box<GenericArgs>>,
541 }
542
543 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
544 pub struct FunctionPointer {
545     pub decl: FnDecl,
546     /// Used for Higher-Rank Trait Bounds (HRTBs)
547     /// ```text
548     /// for<'c> fn(val: &'c i32) -> i32
549     /// ^^^^^^^
550     ///       |
551     ///       this part
552     /// ```
553     pub generic_params: Vec<GenericParamDef>,
554     pub header: Header,
555 }
556
557 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
558 pub struct FnDecl {
559     pub inputs: Vec<(String, Type)>,
560     pub output: Option<Type>,
561     pub c_variadic: bool,
562 }
563
564 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
565 pub struct Trait {
566     pub is_auto: bool,
567     pub is_unsafe: bool,
568     pub items: Vec<Id>,
569     pub generics: Generics,
570     pub bounds: Vec<GenericBound>,
571     pub implementations: Vec<Id>,
572 }
573
574 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
575 pub struct TraitAlias {
576     pub generics: Generics,
577     pub params: Vec<GenericBound>,
578 }
579
580 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
581 pub struct Impl {
582     pub is_unsafe: bool,
583     pub generics: Generics,
584     pub provided_trait_methods: Vec<String>,
585     #[serde(rename = "trait")]
586     pub trait_: Option<Path>,
587     #[serde(rename = "for")]
588     pub for_: Type,
589     pub items: Vec<Id>,
590     pub negative: bool,
591     pub synthetic: bool,
592     pub blanket_impl: Option<Type>,
593 }
594
595 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
596 #[serde(rename_all = "snake_case")]
597 pub struct Import {
598     /// The full path being imported.
599     pub source: String,
600     /// May be different from the last segment of `source` when renaming imports:
601     /// `use source as name;`
602     pub name: String,
603     /// The ID of the item being imported. Will be `None` in case of re-exports of primitives:
604     /// ```rust
605     /// pub use i32 as my_i32;
606     /// ```
607     pub id: Option<Id>,
608     /// Whether this import uses a glob: `use source::*;`
609     pub glob: bool,
610 }
611
612 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
613 pub struct ProcMacro {
614     pub kind: MacroKind,
615     pub helpers: Vec<String>,
616 }
617
618 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
619 #[serde(rename_all = "snake_case")]
620 pub enum MacroKind {
621     /// A bang macro `foo!()`.
622     Bang,
623     /// An attribute macro `#[foo]`.
624     Attr,
625     /// A derive macro `#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]`
626     Derive,
627 }
628
629 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
630 pub struct Typedef {
631     #[serde(rename = "type")]
632     pub type_: Type,
633     pub generics: Generics,
634 }
635
636 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
637 pub struct OpaqueTy {
638     pub bounds: Vec<GenericBound>,
639     pub generics: Generics,
640 }
641
642 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
643 pub struct Static {
644     #[serde(rename = "type")]
645     pub type_: Type,
646     pub mutable: bool,
647     pub expr: String,
648 }
649
650 #[cfg(test)]
651 mod tests;