]> git.lizzy.rs Git - rust.git/blob - src/rustdoc-json-types/lib.rs
Auto merge of #95745 - Dylan-DPC:rollup-485ajqi, r=Dylan-DPC
[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 = 14;
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, Serialize, Deserialize, PartialEq)]
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, Serialize, Deserialize, PartialEq)]
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, Serialize, Deserialize, PartialEq)]
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, Serialize, Deserialize, PartialEq)]
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, Serialize, Deserialize, PartialEq)]
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, Serialize, Deserialize, PartialEq)]
97 pub struct Deprecation {
98     pub since: Option<String>,
99     pub note: Option<String>,
100 }
101
102 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
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, Serialize, Deserialize, PartialEq)]
119 #[serde(rename_all = "snake_case")]
120 pub enum GenericArgs {
121     /// <'a, 32, B: Copy, C = u32>
122     AngleBracketed { args: Vec<GenericArg>, bindings: Vec<TypeBinding> },
123     /// Fn(A, B) -> C
124     Parenthesized { inputs: Vec<Type>, output: Option<Type> },
125 }
126
127 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
128 #[serde(rename_all = "snake_case")]
129 pub enum GenericArg {
130     Lifetime(String),
131     Type(Type),
132     Const(Constant),
133     Infer,
134 }
135
136 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
137 pub struct Constant {
138     #[serde(rename = "type")]
139     pub type_: Type,
140     pub expr: String,
141     pub value: Option<String>,
142     pub is_literal: bool,
143 }
144
145 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
146 pub struct TypeBinding {
147     pub name: String,
148     pub args: GenericArgs,
149     pub binding: TypeBindingKind,
150 }
151
152 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
153 #[serde(rename_all = "snake_case")]
154 pub enum TypeBindingKind {
155     Equality(Term),
156     Constraint(Vec<GenericBound>),
157 }
158
159 #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
160 pub struct Id(pub String);
161
162 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
163 #[serde(rename_all = "snake_case")]
164 pub enum ItemKind {
165     Module,
166     ExternCrate,
167     Import,
168     Struct,
169     StructField,
170     Union,
171     Enum,
172     Variant,
173     Function,
174     Typedef,
175     OpaqueTy,
176     Constant,
177     Trait,
178     TraitAlias,
179     Method,
180     Impl,
181     Static,
182     ForeignType,
183     Macro,
184     ProcAttribute,
185     ProcDerive,
186     AssocConst,
187     AssocType,
188     Primitive,
189     Keyword,
190 }
191
192 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
193 #[serde(tag = "kind", content = "inner", rename_all = "snake_case")]
194 pub enum ItemEnum {
195     Module(Module),
196     ExternCrate {
197         name: String,
198         rename: Option<String>,
199     },
200     Import(Import),
201
202     Union(Union),
203     Struct(Struct),
204     StructField(Type),
205     Enum(Enum),
206     Variant(Variant),
207
208     Function(Function),
209
210     Trait(Trait),
211     TraitAlias(TraitAlias),
212     Method(Method),
213     Impl(Impl),
214
215     Typedef(Typedef),
216     OpaqueTy(OpaqueTy),
217     Constant(Constant),
218
219     Static(Static),
220
221     /// `type`s from an extern block
222     ForeignType,
223
224     /// Declarative macro_rules! macro
225     Macro(String),
226     ProcMacro(ProcMacro),
227
228     PrimitiveType(String),
229
230     AssocConst {
231         #[serde(rename = "type")]
232         type_: Type,
233         /// e.g. `const X: usize = 5;`
234         default: Option<String>,
235     },
236     AssocType {
237         generics: Generics,
238         bounds: Vec<GenericBound>,
239         /// e.g. `type X = usize;`
240         default: Option<Type>,
241     },
242 }
243
244 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
245 pub struct Module {
246     pub is_crate: bool,
247     pub items: Vec<Id>,
248 }
249
250 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
251 pub struct Union {
252     pub generics: Generics,
253     pub fields_stripped: bool,
254     pub fields: Vec<Id>,
255     pub impls: Vec<Id>,
256 }
257
258 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
259 pub struct Struct {
260     pub struct_type: StructType,
261     pub generics: Generics,
262     pub fields_stripped: bool,
263     pub fields: Vec<Id>,
264     pub impls: Vec<Id>,
265 }
266
267 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
268 pub struct Enum {
269     pub generics: Generics,
270     pub variants_stripped: bool,
271     pub variants: Vec<Id>,
272     pub impls: Vec<Id>,
273 }
274
275 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
276 #[serde(rename_all = "snake_case")]
277 #[serde(tag = "variant_kind", content = "variant_inner")]
278 pub enum Variant {
279     Plain,
280     Tuple(Vec<Type>),
281     Struct(Vec<Id>),
282 }
283
284 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
285 #[serde(rename_all = "snake_case")]
286 pub enum StructType {
287     Plain,
288     Tuple,
289     Unit,
290 }
291
292 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
293 pub struct Header {
294     #[serde(rename = "const")]
295     pub const_: bool,
296     #[serde(rename = "unsafe")]
297     pub unsafe_: bool,
298     #[serde(rename = "async")]
299     pub async_: bool,
300     pub abi: Abi,
301 }
302
303 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
304 pub enum Abi {
305     // We only have a concrete listing here for stable ABI's because their are so many
306     // See rustc_ast_passes::feature_gate::PostExpansionVisitor::check_abi for the list
307     Rust,
308     C { unwind: bool },
309     Cdecl { unwind: bool },
310     Stdcall { unwind: bool },
311     Fastcall { unwind: bool },
312     Aapcs { unwind: bool },
313     Win64 { unwind: bool },
314     SysV64 { unwind: bool },
315     System { unwind: bool },
316     Other(String),
317 }
318
319 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
320 pub struct Function {
321     pub decl: FnDecl,
322     pub generics: Generics,
323     pub header: Header,
324 }
325
326 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
327 pub struct Method {
328     pub decl: FnDecl,
329     pub generics: Generics,
330     pub header: Header,
331     pub has_body: bool,
332 }
333
334 #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
335 pub struct Generics {
336     pub params: Vec<GenericParamDef>,
337     pub where_predicates: Vec<WherePredicate>,
338 }
339
340 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
341 pub struct GenericParamDef {
342     pub name: String,
343     pub kind: GenericParamDefKind,
344 }
345
346 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
347 #[serde(rename_all = "snake_case")]
348 pub enum GenericParamDefKind {
349     Lifetime {
350         outlives: Vec<String>,
351     },
352     Type {
353         bounds: Vec<GenericBound>,
354         default: Option<Type>,
355         /// This is normally `false`, which means that this generic parameter is
356         /// declared in the Rust source text.
357         ///
358         /// If it is `true`, this generic parameter has been introduced by the
359         /// compiler behind the scenes.
360         ///
361         /// # Example
362         ///
363         /// Consider
364         ///
365         /// ```ignore (pseudo-rust)
366         /// pub fn f(_: impl Trait) {}
367         /// ```
368         ///
369         /// The compiler will transform this behind the scenes to
370         ///
371         /// ```ignore (pseudo-rust)
372         /// pub fn f<impl Trait: Trait>(_: impl Trait) {}
373         /// ```
374         ///
375         /// In this example, the generic parameter named `impl Trait` (and which
376         /// is bound by `Trait`) is synthetic, because it was not originally in
377         /// the Rust source text.
378         synthetic: bool,
379     },
380     Const {
381         #[serde(rename = "type")]
382         type_: Type,
383         default: Option<String>,
384     },
385 }
386
387 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
388 #[serde(rename_all = "snake_case")]
389 pub enum WherePredicate {
390     BoundPredicate {
391         #[serde(rename = "type")]
392         type_: Type,
393         bounds: Vec<GenericBound>,
394     },
395     RegionPredicate {
396         lifetime: String,
397         bounds: Vec<GenericBound>,
398     },
399     EqPredicate {
400         lhs: Type,
401         rhs: Term,
402     },
403 }
404
405 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
406 #[serde(rename_all = "snake_case")]
407 pub enum GenericBound {
408     TraitBound {
409         #[serde(rename = "trait")]
410         trait_: Type,
411         /// Used for HRTBs
412         generic_params: Vec<GenericParamDef>,
413         modifier: TraitBoundModifier,
414     },
415     Outlives(String),
416 }
417
418 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
419 #[serde(rename_all = "snake_case")]
420 pub enum TraitBoundModifier {
421     None,
422     Maybe,
423     MaybeConst,
424 }
425
426 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
427 #[serde(rename_all = "snake_case")]
428 pub enum Term {
429     Type(Type),
430     Constant(Constant),
431 }
432
433 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
434 #[serde(rename_all = "snake_case")]
435 #[serde(tag = "kind", content = "inner")]
436 pub enum Type {
437     /// Structs, enums, and traits
438     ResolvedPath {
439         name: String,
440         id: Id,
441         args: Option<Box<GenericArgs>>,
442         param_names: Vec<GenericBound>,
443     },
444     /// Parameterized types
445     Generic(String),
446     /// Fixed-size numeric types (plus int/usize/float), char, arrays, slices, and tuples
447     Primitive(String),
448     /// `extern "ABI" fn`
449     FunctionPointer(Box<FunctionPointer>),
450     /// `(String, u32, Box<usize>)`
451     Tuple(Vec<Type>),
452     /// `[u32]`
453     Slice(Box<Type>),
454     /// [u32; 15]
455     Array {
456         #[serde(rename = "type")]
457         type_: Box<Type>,
458         len: String,
459     },
460     /// `impl TraitA + TraitB + ...`
461     ImplTrait(Vec<GenericBound>),
462     /// `_`
463     Infer,
464     /// `*mut u32`, `*u8`, etc.
465     RawPointer {
466         mutable: bool,
467         #[serde(rename = "type")]
468         type_: Box<Type>,
469     },
470     /// `&'a mut String`, `&str`, etc.
471     BorrowedRef {
472         lifetime: Option<String>,
473         mutable: bool,
474         #[serde(rename = "type")]
475         type_: Box<Type>,
476     },
477     /// `<Type as Trait>::Name` or associated types like `T::Item` where `T: Iterator`
478     QualifiedPath {
479         name: String,
480         args: Box<GenericArgs>,
481         self_type: Box<Type>,
482         #[serde(rename = "trait")]
483         trait_: Box<Type>,
484     },
485 }
486
487 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
488 pub struct FunctionPointer {
489     pub decl: FnDecl,
490     pub generic_params: Vec<GenericParamDef>,
491     pub header: Header,
492 }
493
494 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
495 pub struct FnDecl {
496     pub inputs: Vec<(String, Type)>,
497     pub output: Option<Type>,
498     pub c_variadic: bool,
499 }
500
501 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
502 pub struct Trait {
503     pub is_auto: bool,
504     pub is_unsafe: bool,
505     pub items: Vec<Id>,
506     pub generics: Generics,
507     pub bounds: Vec<GenericBound>,
508     pub implementations: Vec<Id>,
509 }
510
511 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
512 pub struct TraitAlias {
513     pub generics: Generics,
514     pub params: Vec<GenericBound>,
515 }
516
517 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
518 pub struct Impl {
519     pub is_unsafe: bool,
520     pub generics: Generics,
521     pub provided_trait_methods: Vec<String>,
522     #[serde(rename = "trait")]
523     pub trait_: Option<Type>,
524     #[serde(rename = "for")]
525     pub for_: Type,
526     pub items: Vec<Id>,
527     pub negative: bool,
528     pub synthetic: bool,
529     pub blanket_impl: Option<Type>,
530 }
531
532 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
533 #[serde(rename_all = "snake_case")]
534 pub struct Import {
535     /// The full path being imported.
536     pub source: String,
537     /// May be different from the last segment of `source` when renaming imports:
538     /// `use source as name;`
539     pub name: String,
540     /// The ID of the item being imported.
541     pub id: Option<Id>, // FIXME is this actually ever None?
542     /// Whether this import uses a glob: `use source::*;`
543     pub glob: bool,
544 }
545
546 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
547 pub struct ProcMacro {
548     pub kind: MacroKind,
549     pub helpers: Vec<String>,
550 }
551
552 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
553 #[serde(rename_all = "snake_case")]
554 pub enum MacroKind {
555     /// A bang macro `foo!()`.
556     Bang,
557     /// An attribute macro `#[foo]`.
558     Attr,
559     /// A derive macro `#[derive(Foo)]`
560     Derive,
561 }
562
563 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
564 pub struct Typedef {
565     #[serde(rename = "type")]
566     pub type_: Type,
567     pub generics: Generics,
568 }
569
570 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
571 pub struct OpaqueTy {
572     pub bounds: Vec<GenericBound>,
573     pub generics: Generics,
574 }
575
576 #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
577 pub struct Static {
578     #[serde(rename = "type")]
579     pub type_: Type,
580     pub mutable: bool,
581     pub expr: String,
582 }
583
584 #[cfg(test)]
585 mod tests;