From 698f8c2f01ea549d77d7dc3338a12e04c11057b9 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Wed, 17 Apr 2024 14:02:58 +0200 Subject: Adding upstream version 1.64.0+dfsg1. Signed-off-by: Daniel Baumann --- src/librustdoc/json/conversions.rs | 798 +++++++++++++++++++++++++++++++++++++ src/librustdoc/json/mod.rs | 327 +++++++++++++++ 2 files changed, 1125 insertions(+) create mode 100644 src/librustdoc/json/conversions.rs create mode 100644 src/librustdoc/json/mod.rs (limited to 'src/librustdoc/json') diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs new file mode 100644 index 000000000..716a4c9ea --- /dev/null +++ b/src/librustdoc/json/conversions.rs @@ -0,0 +1,798 @@ +//! These from impls are used to create the JSON types which get serialized. They're very close to +//! the `clean` types but with some fields removed or stringified to simplify the output and not +//! expose unstable compiler internals. + +#![allow(rustc::default_hash_types)] + +use std::convert::From; +use std::fmt; + +use rustc_ast::ast; +use rustc_hir::{def::CtorKind, def_id::DefId}; +use rustc_middle::ty::{self, TyCtxt}; +use rustc_span::{Pos, Symbol}; +use rustc_target::spec::abi::Abi as RustcAbi; + +use rustdoc_json_types::*; + +use crate::clean::utils::print_const_expr; +use crate::clean::{self, ItemId}; +use crate::formats::item_type::ItemType; +use crate::json::JsonRenderer; + +impl JsonRenderer<'_> { + pub(super) fn convert_item(&self, item: clean::Item) -> Option { + let deprecation = item.deprecation(self.tcx); + let links = self + .cache + .intra_doc_links + .get(&item.item_id) + .into_iter() + .flatten() + .map(|clean::ItemLink { link, did, .. }| { + (link.clone(), from_item_id((*did).into(), self.tcx)) + }) + .collect(); + let docs = item.attrs.collapsed_doc_value(); + let attrs = item + .attrs + .other_attrs + .iter() + .map(rustc_ast_pretty::pprust::attribute_to_string) + .collect(); + let span = item.span(self.tcx); + let clean::Item { name, attrs: _, kind: _, visibility, item_id, cfg: _ } = item; + let inner = match *item.kind { + clean::KeywordItem => return None, + clean::StrippedItem(ref inner) => { + match &**inner { + // We document non-empty stripped modules as with `Module::is_stripped` set to + // `true`, to prevent contained items from being orphaned for downstream users, + // as JSON does no inlining. + clean::ModuleItem(m) if !m.items.is_empty() => from_clean_item(item, self.tcx), + _ => return None, + } + } + _ => from_clean_item(item, self.tcx), + }; + Some(Item { + id: from_item_id_with_name(item_id, self.tcx, name), + crate_id: item_id.krate().as_u32(), + name: name.map(|sym| sym.to_string()), + span: self.convert_span(span), + visibility: self.convert_visibility(visibility), + docs, + attrs, + deprecation: deprecation.map(from_deprecation), + inner, + links, + }) + } + + fn convert_span(&self, span: clean::Span) -> Option { + match span.filename(self.sess()) { + rustc_span::FileName::Real(name) => { + if let Some(local_path) = name.into_local_path() { + let hi = span.hi(self.sess()); + let lo = span.lo(self.sess()); + Some(Span { + filename: local_path, + begin: (lo.line, lo.col.to_usize()), + end: (hi.line, hi.col.to_usize()), + }) + } else { + None + } + } + _ => None, + } + } + + fn convert_visibility(&self, v: clean::Visibility) -> Visibility { + use clean::Visibility::*; + match v { + Public => Visibility::Public, + Inherited => Visibility::Default, + Restricted(did) if did.is_crate_root() => Visibility::Crate, + Restricted(did) => Visibility::Restricted { + parent: from_item_id(did.into(), self.tcx), + path: self.tcx.def_path(did).to_string_no_crate_verbose(), + }, + } + } +} + +pub(crate) trait FromWithTcx { + fn from_tcx(f: T, tcx: TyCtxt<'_>) -> Self; +} + +pub(crate) trait IntoWithTcx { + fn into_tcx(self, tcx: TyCtxt<'_>) -> T; +} + +impl IntoWithTcx for T +where + U: FromWithTcx, +{ + fn into_tcx(self, tcx: TyCtxt<'_>) -> U { + U::from_tcx(self, tcx) + } +} + +pub(crate) fn from_deprecation(deprecation: rustc_attr::Deprecation) -> Deprecation { + #[rustfmt::skip] + let rustc_attr::Deprecation { since, note, is_since_rustc_version: _, suggestion: _ } = deprecation; + Deprecation { since: since.map(|s| s.to_string()), note: note.map(|s| s.to_string()) } +} + +impl FromWithTcx for GenericArgs { + fn from_tcx(args: clean::GenericArgs, tcx: TyCtxt<'_>) -> Self { + use clean::GenericArgs::*; + match args { + AngleBracketed { args, bindings } => GenericArgs::AngleBracketed { + args: args.into_vec().into_iter().map(|a| a.into_tcx(tcx)).collect(), + bindings: bindings.into_iter().map(|a| a.into_tcx(tcx)).collect(), + }, + Parenthesized { inputs, output } => GenericArgs::Parenthesized { + inputs: inputs.into_vec().into_iter().map(|a| a.into_tcx(tcx)).collect(), + output: output.map(|a| (*a).into_tcx(tcx)), + }, + } + } +} + +impl FromWithTcx for GenericArg { + fn from_tcx(arg: clean::GenericArg, tcx: TyCtxt<'_>) -> Self { + use clean::GenericArg::*; + match arg { + Lifetime(l) => GenericArg::Lifetime(l.0.to_string()), + Type(t) => GenericArg::Type(t.into_tcx(tcx)), + Const(box c) => GenericArg::Const(c.into_tcx(tcx)), + Infer => GenericArg::Infer, + } + } +} + +impl FromWithTcx for Constant { + fn from_tcx(constant: clean::Constant, tcx: TyCtxt<'_>) -> Self { + let expr = constant.expr(tcx); + let value = constant.value(tcx); + let is_literal = constant.is_literal(tcx); + Constant { type_: constant.type_.into_tcx(tcx), expr, value, is_literal } + } +} + +impl FromWithTcx for TypeBinding { + fn from_tcx(binding: clean::TypeBinding, tcx: TyCtxt<'_>) -> Self { + TypeBinding { + name: binding.assoc.name.to_string(), + args: binding.assoc.args.into_tcx(tcx), + binding: binding.kind.into_tcx(tcx), + } + } +} + +impl FromWithTcx for TypeBindingKind { + fn from_tcx(kind: clean::TypeBindingKind, tcx: TyCtxt<'_>) -> Self { + use clean::TypeBindingKind::*; + match kind { + Equality { term } => TypeBindingKind::Equality(term.into_tcx(tcx)), + Constraint { bounds } => { + TypeBindingKind::Constraint(bounds.into_iter().map(|a| a.into_tcx(tcx)).collect()) + } + } + } +} + +/// It generates an ID as follows: +/// +/// `CRATE_ID:ITEM_ID[:NAME_ID]` (if there is no name, NAME_ID is not generated). +pub(crate) fn from_item_id(item_id: ItemId, tcx: TyCtxt<'_>) -> Id { + from_item_id_with_name(item_id, tcx, None) +} + +// FIXME: this function (and appending the name at the end of the ID) should be removed when +// reexports are not inlined anymore for json format. It should be done in #93518. +pub(crate) fn from_item_id_with_name(item_id: ItemId, tcx: TyCtxt<'_>, name: Option) -> Id { + struct DisplayDefId<'a>(DefId, TyCtxt<'a>, Option); + + impl<'a> fmt::Display for DisplayDefId<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self.2 { + Some(name) => format!(":{}", name.as_u32()), + None => self + .1 + .opt_item_name(self.0) + .map(|n| format!(":{}", n.as_u32())) + .unwrap_or_default(), + }; + write!(f, "{}:{}{}", self.0.krate.as_u32(), u32::from(self.0.index), name) + } + } + + match item_id { + ItemId::DefId(did) => Id(format!("{}", DisplayDefId(did, tcx, name))), + ItemId::Blanket { for_, impl_id } => { + Id(format!("b:{}-{}", DisplayDefId(impl_id, tcx, None), DisplayDefId(for_, tcx, name))) + } + ItemId::Auto { for_, trait_ } => { + Id(format!("a:{}-{}", DisplayDefId(trait_, tcx, None), DisplayDefId(for_, tcx, name))) + } + ItemId::Primitive(ty, krate) => Id(format!("p:{}:{}", krate.as_u32(), ty.as_sym())), + } +} + +fn from_clean_item(item: clean::Item, tcx: TyCtxt<'_>) -> ItemEnum { + use clean::ItemKind::*; + let name = item.name; + let is_crate = item.is_crate(); + let header = item.fn_header(tcx); + + match *item.kind { + ModuleItem(m) => { + ItemEnum::Module(Module { is_crate, items: ids(m.items, tcx), is_stripped: false }) + } + ImportItem(i) => ItemEnum::Import(i.into_tcx(tcx)), + StructItem(s) => ItemEnum::Struct(s.into_tcx(tcx)), + UnionItem(u) => ItemEnum::Union(u.into_tcx(tcx)), + StructFieldItem(f) => ItemEnum::StructField(f.into_tcx(tcx)), + EnumItem(e) => ItemEnum::Enum(e.into_tcx(tcx)), + VariantItem(v) => ItemEnum::Variant(v.into_tcx(tcx)), + FunctionItem(f) => ItemEnum::Function(from_function(f, header.unwrap(), tcx)), + ForeignFunctionItem(f) => ItemEnum::Function(from_function(f, header.unwrap(), tcx)), + TraitItem(t) => ItemEnum::Trait(t.into_tcx(tcx)), + TraitAliasItem(t) => ItemEnum::TraitAlias(t.into_tcx(tcx)), + MethodItem(m, _) => ItemEnum::Method(from_function_method(m, true, header.unwrap(), tcx)), + TyMethodItem(m) => ItemEnum::Method(from_function_method(m, false, header.unwrap(), tcx)), + ImplItem(i) => ItemEnum::Impl(i.into_tcx(tcx)), + StaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)), + ForeignStaticItem(s) => ItemEnum::Static(s.into_tcx(tcx)), + ForeignTypeItem => ItemEnum::ForeignType, + TypedefItem(t) => ItemEnum::Typedef(t.into_tcx(tcx)), + OpaqueTyItem(t) => ItemEnum::OpaqueTy(t.into_tcx(tcx)), + ConstantItem(c) => ItemEnum::Constant(c.into_tcx(tcx)), + MacroItem(m) => ItemEnum::Macro(m.source), + ProcMacroItem(m) => ItemEnum::ProcMacro(m.into_tcx(tcx)), + PrimitiveItem(p) => ItemEnum::PrimitiveType(p.as_sym().to_string()), + TyAssocConstItem(ty) => ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: None }, + AssocConstItem(ty, default) => { + ItemEnum::AssocConst { type_: ty.into_tcx(tcx), default: Some(default.expr(tcx)) } + } + TyAssocTypeItem(g, b) => ItemEnum::AssocType { + generics: (*g).into_tcx(tcx), + bounds: b.into_iter().map(|x| x.into_tcx(tcx)).collect(), + default: None, + }, + AssocTypeItem(t, b) => ItemEnum::AssocType { + generics: t.generics.into_tcx(tcx), + bounds: b.into_iter().map(|x| x.into_tcx(tcx)).collect(), + default: Some(t.item_type.unwrap_or(t.type_).into_tcx(tcx)), + }, + // `convert_item` early returns `None` for stripped items and keywords. + KeywordItem => unreachable!(), + StrippedItem(inner) => { + match *inner { + ModuleItem(m) => ItemEnum::Module(Module { + is_crate, + items: ids(m.items, tcx), + is_stripped: true, + }), + // `convert_item` early returns `None` for stripped items we're not including + _ => unreachable!(), + } + } + ExternCrateItem { ref src } => ItemEnum::ExternCrate { + name: name.as_ref().unwrap().to_string(), + rename: src.map(|x| x.to_string()), + }, + } +} + +impl FromWithTcx for Struct { + fn from_tcx(struct_: clean::Struct, tcx: TyCtxt<'_>) -> Self { + let fields_stripped = struct_.has_stripped_entries(); + let clean::Struct { struct_type, generics, fields } = struct_; + Struct { + struct_type: from_ctor_kind(struct_type), + generics: generics.into_tcx(tcx), + fields_stripped, + fields: ids(fields, tcx), + impls: Vec::new(), // Added in JsonRenderer::item + } + } +} + +impl FromWithTcx for Union { + fn from_tcx(union_: clean::Union, tcx: TyCtxt<'_>) -> Self { + let fields_stripped = union_.has_stripped_entries(); + let clean::Union { generics, fields } = union_; + Union { + generics: generics.into_tcx(tcx), + fields_stripped, + fields: ids(fields, tcx), + impls: Vec::new(), // Added in JsonRenderer::item + } + } +} + +pub(crate) fn from_ctor_kind(struct_type: CtorKind) -> StructType { + match struct_type { + CtorKind::Fictive => StructType::Plain, + CtorKind::Fn => StructType::Tuple, + CtorKind::Const => StructType::Unit, + } +} + +pub(crate) fn from_fn_header(header: &rustc_hir::FnHeader) -> Header { + Header { + async_: header.is_async(), + const_: header.is_const(), + unsafe_: header.is_unsafe(), + abi: convert_abi(header.abi), + } +} + +fn convert_abi(a: RustcAbi) -> Abi { + match a { + RustcAbi::Rust => Abi::Rust, + RustcAbi::C { unwind } => Abi::C { unwind }, + RustcAbi::Cdecl { unwind } => Abi::Cdecl { unwind }, + RustcAbi::Stdcall { unwind } => Abi::Stdcall { unwind }, + RustcAbi::Fastcall { unwind } => Abi::Fastcall { unwind }, + RustcAbi::Aapcs { unwind } => Abi::Aapcs { unwind }, + RustcAbi::Win64 { unwind } => Abi::Win64 { unwind }, + RustcAbi::SysV64 { unwind } => Abi::SysV64 { unwind }, + RustcAbi::System { unwind } => Abi::System { unwind }, + _ => Abi::Other(a.to_string()), + } +} + +impl FromWithTcx for Generics { + fn from_tcx(generics: clean::Generics, tcx: TyCtxt<'_>) -> Self { + Generics { + params: generics.params.into_iter().map(|x| x.into_tcx(tcx)).collect(), + where_predicates: generics + .where_predicates + .into_iter() + .map(|x| x.into_tcx(tcx)) + .collect(), + } + } +} + +impl FromWithTcx for GenericParamDef { + fn from_tcx(generic_param: clean::GenericParamDef, tcx: TyCtxt<'_>) -> Self { + GenericParamDef { + name: generic_param.name.to_string(), + kind: generic_param.kind.into_tcx(tcx), + } + } +} + +impl FromWithTcx for GenericParamDefKind { + fn from_tcx(kind: clean::GenericParamDefKind, tcx: TyCtxt<'_>) -> Self { + use clean::GenericParamDefKind::*; + match kind { + Lifetime { outlives } => GenericParamDefKind::Lifetime { + outlives: outlives.into_iter().map(|lt| lt.0.to_string()).collect(), + }, + Type { did: _, bounds, default, synthetic } => GenericParamDefKind::Type { + bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(), + default: default.map(|x| (*x).into_tcx(tcx)), + synthetic, + }, + Const { did: _, ty, default } => GenericParamDefKind::Const { + type_: (*ty).into_tcx(tcx), + default: default.map(|x| *x), + }, + } + } +} + +impl FromWithTcx for WherePredicate { + fn from_tcx(predicate: clean::WherePredicate, tcx: TyCtxt<'_>) -> Self { + use clean::WherePredicate::*; + match predicate { + BoundPredicate { ty, bounds, bound_params } => WherePredicate::BoundPredicate { + type_: ty.into_tcx(tcx), + bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(), + generic_params: bound_params + .into_iter() + .map(|x| GenericParamDef { + name: x.0.to_string(), + kind: GenericParamDefKind::Lifetime { outlives: vec![] }, + }) + .collect(), + }, + RegionPredicate { lifetime, bounds } => WherePredicate::RegionPredicate { + lifetime: lifetime.0.to_string(), + bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(), + }, + EqPredicate { lhs, rhs } => { + WherePredicate::EqPredicate { lhs: lhs.into_tcx(tcx), rhs: rhs.into_tcx(tcx) } + } + } + } +} + +impl FromWithTcx for GenericBound { + fn from_tcx(bound: clean::GenericBound, tcx: TyCtxt<'_>) -> Self { + use clean::GenericBound::*; + match bound { + TraitBound(clean::PolyTrait { trait_, generic_params }, modifier) => { + // FIXME: should `trait_` be a clean::Path equivalent in JSON? + let trait_ = clean::Type::Path { path: trait_ }.into_tcx(tcx); + GenericBound::TraitBound { + trait_, + generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(), + modifier: from_trait_bound_modifier(modifier), + } + } + Outlives(lifetime) => GenericBound::Outlives(lifetime.0.to_string()), + } + } +} + +pub(crate) fn from_trait_bound_modifier( + modifier: rustc_hir::TraitBoundModifier, +) -> TraitBoundModifier { + use rustc_hir::TraitBoundModifier::*; + match modifier { + None => TraitBoundModifier::None, + Maybe => TraitBoundModifier::Maybe, + MaybeConst => TraitBoundModifier::MaybeConst, + } +} + +impl FromWithTcx for Type { + fn from_tcx(ty: clean::Type, tcx: TyCtxt<'_>) -> Self { + use clean::Type::{ + Array, BareFunction, BorrowedRef, DynTrait, Generic, ImplTrait, Infer, Primitive, + QPath, RawPointer, Slice, Tuple, + }; + + match ty { + clean::Type::Path { path } => Type::ResolvedPath { + name: path.whole_name(), + id: from_item_id(path.def_id().into(), tcx), + args: path.segments.last().map(|args| Box::new(args.clone().args.into_tcx(tcx))), + param_names: Vec::new(), + }, + DynTrait(mut bounds, lt) => { + let first_trait = bounds.remove(0).trait_; + + Type::ResolvedPath { + name: first_trait.whole_name(), + id: from_item_id(first_trait.def_id().into(), tcx), + args: first_trait + .segments + .last() + .map(|args| Box::new(args.clone().args.into_tcx(tcx))), + param_names: bounds + .into_iter() + .map(|t| { + clean::GenericBound::TraitBound(t, rustc_hir::TraitBoundModifier::None) + }) + .chain(lt.map(clean::GenericBound::Outlives)) + .map(|bound| bound.into_tcx(tcx)) + .collect(), + } + } + Generic(s) => Type::Generic(s.to_string()), + Primitive(p) => Type::Primitive(p.as_sym().to_string()), + BareFunction(f) => Type::FunctionPointer(Box::new((*f).into_tcx(tcx))), + Tuple(t) => Type::Tuple(t.into_iter().map(|x| x.into_tcx(tcx)).collect()), + Slice(t) => Type::Slice(Box::new((*t).into_tcx(tcx))), + Array(t, s) => Type::Array { type_: Box::new((*t).into_tcx(tcx)), len: s }, + ImplTrait(g) => Type::ImplTrait(g.into_iter().map(|x| x.into_tcx(tcx)).collect()), + Infer => Type::Infer, + RawPointer(mutability, type_) => Type::RawPointer { + mutable: mutability == ast::Mutability::Mut, + type_: Box::new((*type_).into_tcx(tcx)), + }, + BorrowedRef { lifetime, mutability, type_ } => Type::BorrowedRef { + lifetime: lifetime.map(|l| l.0.to_string()), + mutable: mutability == ast::Mutability::Mut, + type_: Box::new((*type_).into_tcx(tcx)), + }, + QPath { assoc, self_type, trait_, .. } => { + // FIXME: should `trait_` be a clean::Path equivalent in JSON? + let trait_ = clean::Type::Path { path: trait_ }.into_tcx(tcx); + Type::QualifiedPath { + name: assoc.name.to_string(), + args: Box::new(assoc.args.clone().into_tcx(tcx)), + self_type: Box::new((*self_type).into_tcx(tcx)), + trait_: Box::new(trait_), + } + } + } + } +} + +impl FromWithTcx for Term { + fn from_tcx(term: clean::Term, tcx: TyCtxt<'_>) -> Term { + match term { + clean::Term::Type(ty) => Term::Type(FromWithTcx::from_tcx(ty, tcx)), + clean::Term::Constant(c) => Term::Constant(FromWithTcx::from_tcx(c, tcx)), + } + } +} + +impl FromWithTcx for FunctionPointer { + fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self { + let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl; + FunctionPointer { + header: Header { + unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe), + const_: false, + async_: false, + abi: convert_abi(abi), + }, + generic_params: generic_params.into_iter().map(|x| x.into_tcx(tcx)).collect(), + decl: decl.into_tcx(tcx), + } + } +} + +impl FromWithTcx for FnDecl { + fn from_tcx(decl: clean::FnDecl, tcx: TyCtxt<'_>) -> Self { + let clean::FnDecl { inputs, output, c_variadic } = decl; + FnDecl { + inputs: inputs + .values + .into_iter() + .map(|arg| (arg.name.to_string(), arg.type_.into_tcx(tcx))) + .collect(), + output: match output { + clean::FnRetTy::Return(t) => Some(t.into_tcx(tcx)), + clean::FnRetTy::DefaultReturn => None, + }, + c_variadic, + } + } +} + +impl FromWithTcx for Trait { + fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self { + let is_auto = trait_.is_auto(tcx); + let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe; + let clean::Trait { items, generics, bounds, .. } = trait_; + Trait { + is_auto, + is_unsafe, + items: ids(items, tcx), + generics: generics.into_tcx(tcx), + bounds: bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(), + implementations: Vec::new(), // Added in JsonRenderer::item + } + } +} + +impl FromWithTcx> for Impl { + fn from_tcx(impl_: Box, tcx: TyCtxt<'_>) -> Self { + let provided_trait_methods = impl_.provided_trait_methods(tcx); + let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = *impl_; + // FIXME: should `trait_` be a clean::Path equivalent in JSON? + let trait_ = trait_.map(|path| clean::Type::Path { path }.into_tcx(tcx)); + // FIXME: use something like ImplKind in JSON? + let (synthetic, blanket_impl) = match kind { + clean::ImplKind::Normal | clean::ImplKind::FakeVaradic => (false, None), + clean::ImplKind::Auto => (true, None), + clean::ImplKind::Blanket(ty) => (false, Some(*ty)), + }; + let negative_polarity = match polarity { + ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false, + ty::ImplPolarity::Negative => true, + }; + Impl { + is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe, + generics: generics.into_tcx(tcx), + provided_trait_methods: provided_trait_methods + .into_iter() + .map(|x| x.to_string()) + .collect(), + trait_, + for_: for_.into_tcx(tcx), + items: ids(items, tcx), + negative: negative_polarity, + synthetic, + blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)), + } + } +} + +pub(crate) fn from_function( + function: Box, + header: rustc_hir::FnHeader, + tcx: TyCtxt<'_>, +) -> Function { + let clean::Function { decl, generics } = *function; + Function { + decl: decl.into_tcx(tcx), + generics: generics.into_tcx(tcx), + header: from_fn_header(&header), + } +} + +pub(crate) fn from_function_method( + function: Box, + has_body: bool, + header: rustc_hir::FnHeader, + tcx: TyCtxt<'_>, +) -> Method { + let clean::Function { decl, generics } = *function; + Method { + decl: decl.into_tcx(tcx), + generics: generics.into_tcx(tcx), + header: from_fn_header(&header), + has_body, + } +} + +impl FromWithTcx for Enum { + fn from_tcx(enum_: clean::Enum, tcx: TyCtxt<'_>) -> Self { + let variants_stripped = enum_.has_stripped_entries(); + let clean::Enum { variants, generics } = enum_; + Enum { + generics: generics.into_tcx(tcx), + variants_stripped, + variants: ids(variants, tcx), + impls: Vec::new(), // Added in JsonRenderer::item + } + } +} + +impl FromWithTcx for Struct { + fn from_tcx(struct_: clean::VariantStruct, tcx: TyCtxt<'_>) -> Self { + let fields_stripped = struct_.has_stripped_entries(); + let clean::VariantStruct { struct_type, fields } = struct_; + Struct { + struct_type: from_ctor_kind(struct_type), + generics: Generics { params: vec![], where_predicates: vec![] }, + fields_stripped, + fields: ids(fields, tcx), + impls: Vec::new(), + } + } +} + +impl FromWithTcx for Variant { + fn from_tcx(variant: clean::Variant, tcx: TyCtxt<'_>) -> Self { + use clean::Variant::*; + match variant { + CLike => Variant::Plain, + Tuple(fields) => Variant::Tuple( + fields + .into_iter() + .map(|f| { + if let clean::StructFieldItem(ty) = *f.kind { + ty.into_tcx(tcx) + } else { + unreachable!() + } + }) + .collect(), + ), + Struct(s) => Variant::Struct(ids(s.fields, tcx)), + } + } +} + +impl FromWithTcx for Import { + fn from_tcx(import: clean::Import, tcx: TyCtxt<'_>) -> Self { + use clean::ImportKind::*; + match import.kind { + Simple(s) => Import { + source: import.source.path.whole_name(), + name: s.to_string(), + id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)), + glob: false, + }, + Glob => Import { + source: import.source.path.whole_name(), + name: import + .source + .path + .last_opt() + .unwrap_or_else(|| Symbol::intern("*")) + .to_string(), + id: import.source.did.map(ItemId::from).map(|i| from_item_id(i, tcx)), + glob: true, + }, + } + } +} + +impl FromWithTcx for ProcMacro { + fn from_tcx(mac: clean::ProcMacro, _tcx: TyCtxt<'_>) -> Self { + ProcMacro { + kind: from_macro_kind(mac.kind), + helpers: mac.helpers.iter().map(|x| x.to_string()).collect(), + } + } +} + +pub(crate) fn from_macro_kind(kind: rustc_span::hygiene::MacroKind) -> MacroKind { + use rustc_span::hygiene::MacroKind::*; + match kind { + Bang => MacroKind::Bang, + Attr => MacroKind::Attr, + Derive => MacroKind::Derive, + } +} + +impl FromWithTcx> for Typedef { + fn from_tcx(typedef: Box, tcx: TyCtxt<'_>) -> Self { + let clean::Typedef { type_, generics, item_type: _ } = *typedef; + Typedef { type_: type_.into_tcx(tcx), generics: generics.into_tcx(tcx) } + } +} + +impl FromWithTcx for OpaqueTy { + fn from_tcx(opaque: clean::OpaqueTy, tcx: TyCtxt<'_>) -> Self { + OpaqueTy { + bounds: opaque.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(), + generics: opaque.generics.into_tcx(tcx), + } + } +} + +impl FromWithTcx for Static { + fn from_tcx(stat: clean::Static, tcx: TyCtxt<'_>) -> Self { + Static { + type_: stat.type_.into_tcx(tcx), + mutable: stat.mutability == ast::Mutability::Mut, + expr: stat.expr.map(|e| print_const_expr(tcx, e)).unwrap_or_default(), + } + } +} + +impl FromWithTcx for TraitAlias { + fn from_tcx(alias: clean::TraitAlias, tcx: TyCtxt<'_>) -> Self { + TraitAlias { + generics: alias.generics.into_tcx(tcx), + params: alias.bounds.into_iter().map(|x| x.into_tcx(tcx)).collect(), + } + } +} + +impl FromWithTcx for ItemKind { + fn from_tcx(kind: ItemType, _tcx: TyCtxt<'_>) -> Self { + use ItemType::*; + match kind { + Module => ItemKind::Module, + ExternCrate => ItemKind::ExternCrate, + Import => ItemKind::Import, + Struct => ItemKind::Struct, + Union => ItemKind::Union, + Enum => ItemKind::Enum, + Function => ItemKind::Function, + Typedef => ItemKind::Typedef, + OpaqueTy => ItemKind::OpaqueTy, + Static => ItemKind::Static, + Constant => ItemKind::Constant, + Trait => ItemKind::Trait, + Impl => ItemKind::Impl, + TyMethod | Method => ItemKind::Method, + StructField => ItemKind::StructField, + Variant => ItemKind::Variant, + Macro => ItemKind::Macro, + Primitive => ItemKind::Primitive, + AssocConst => ItemKind::AssocConst, + AssocType => ItemKind::AssocType, + ForeignType => ItemKind::ForeignType, + Keyword => ItemKind::Keyword, + TraitAlias => ItemKind::TraitAlias, + ProcAttribute => ItemKind::ProcAttribute, + ProcDerive => ItemKind::ProcDerive, + } + } +} + +fn ids(items: impl IntoIterator, tcx: TyCtxt<'_>) -> Vec { + items + .into_iter() + .filter(|x| !x.is_stripped() && !x.is_keyword()) + .map(|i| from_item_id_with_name(i.item_id, tcx, i.name)) + .collect() +} diff --git a/src/librustdoc/json/mod.rs b/src/librustdoc/json/mod.rs new file mode 100644 index 000000000..6364d00d0 --- /dev/null +++ b/src/librustdoc/json/mod.rs @@ -0,0 +1,327 @@ +//! Rustdoc's JSON backend +//! +//! This module contains the logic for rendering a crate as JSON rather than the normal static HTML +//! output. See [the RFC](https://github.com/rust-lang/rfcs/pull/2963) and the [`types`] module +//! docs for usage and details. + +mod conversions; + +use std::cell::RefCell; +use std::fs::{create_dir_all, File}; +use std::io::{BufWriter, Write}; +use std::path::PathBuf; +use std::rc::Rc; + +use rustc_data_structures::fx::FxHashMap; +use rustc_hir::def_id::DefId; +use rustc_middle::ty::TyCtxt; +use rustc_session::Session; +use rustc_span::def_id::LOCAL_CRATE; + +use rustdoc_json_types as types; + +use crate::clean::types::{ExternalCrate, ExternalLocation}; +use crate::clean::ItemKind; +use crate::config::RenderOptions; +use crate::docfs::PathError; +use crate::error::Error; +use crate::formats::cache::Cache; +use crate::formats::FormatRenderer; +use crate::json::conversions::{from_item_id, from_item_id_with_name, IntoWithTcx}; +use crate::{clean, try_err}; + +#[derive(Clone)] +pub(crate) struct JsonRenderer<'tcx> { + tcx: TyCtxt<'tcx>, + /// A mapping of IDs that contains all local items for this crate which gets output as a top + /// level field of the JSON blob. + index: Rc>>, + /// The directory where the blob will be written to. + out_path: PathBuf, + cache: Rc, +} + +impl<'tcx> JsonRenderer<'tcx> { + fn sess(&self) -> &'tcx Session { + self.tcx.sess + } + + fn get_trait_implementors(&mut self, id: DefId) -> Vec { + Rc::clone(&self.cache) + .implementors + .get(&id) + .map(|implementors| { + implementors + .iter() + .map(|i| { + let item = &i.impl_item; + self.item(item.clone()).unwrap(); + from_item_id_with_name(item.item_id, self.tcx, item.name) + }) + .collect() + }) + .unwrap_or_default() + } + + fn get_impls(&mut self, id: DefId) -> Vec { + Rc::clone(&self.cache) + .impls + .get(&id) + .map(|impls| { + impls + .iter() + .filter_map(|i| { + let item = &i.impl_item; + + // HACK(hkmatsumoto): For impls of primitive types, we index them + // regardless of whether they're local. This is because users can + // document primitive items in an arbitrary crate by using + // `doc(primitive)`. + let mut is_primitive_impl = false; + if let clean::types::ItemKind::ImplItem(ref impl_) = *item.kind { + if impl_.trait_.is_none() { + if let clean::types::Type::Primitive(_) = impl_.for_ { + is_primitive_impl = true; + } + } + } + + if item.item_id.is_local() || is_primitive_impl { + self.item(item.clone()).unwrap(); + Some(from_item_id_with_name(item.item_id, self.tcx, item.name)) + } else { + None + } + }) + .collect() + }) + .unwrap_or_default() + } + + fn get_trait_items(&mut self) -> Vec<(types::Id, types::Item)> { + Rc::clone(&self.cache) + .traits + .iter() + .filter_map(|(&id, trait_item)| { + // only need to synthesize items for external traits + if !id.is_local() { + let trait_item = &trait_item.trait_; + trait_item.items.clone().into_iter().for_each(|i| self.item(i).unwrap()); + let item_id = from_item_id(id.into(), self.tcx); + Some(( + item_id.clone(), + types::Item { + id: item_id, + crate_id: id.krate.as_u32(), + name: self + .cache + .paths + .get(&id) + .unwrap_or_else(|| { + self.cache + .external_paths + .get(&id) + .expect("Trait should either be in local or external paths") + }) + .0 + .last() + .map(|s| s.to_string()), + visibility: types::Visibility::Public, + inner: types::ItemEnum::Trait(trait_item.clone().into_tcx(self.tcx)), + span: None, + docs: Default::default(), + links: Default::default(), + attrs: Default::default(), + deprecation: Default::default(), + }, + )) + } else { + None + } + }) + .collect() + } +} + +impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { + fn descr() -> &'static str { + "json" + } + + const RUN_ON_MODULE: bool = false; + + fn init( + krate: clean::Crate, + options: RenderOptions, + cache: Cache, + tcx: TyCtxt<'tcx>, + ) -> Result<(Self, clean::Crate), Error> { + debug!("Initializing json renderer"); + Ok(( + JsonRenderer { + tcx, + index: Rc::new(RefCell::new(FxHashMap::default())), + out_path: options.output, + cache: Rc::new(cache), + }, + krate, + )) + } + + fn make_child_renderer(&self) -> Self { + self.clone() + } + + /// Inserts an item into the index. This should be used rather than directly calling insert on + /// the hashmap because certain items (traits and types) need to have their mappings for trait + /// implementations filled out before they're inserted. + fn item(&mut self, item: clean::Item) -> Result<(), Error> { + trace!("rendering {} {:?}", item.type_(), item.name); + + // Flatten items that recursively store other items. We include orphaned items from + // stripped modules and etc that are otherwise reachable. + if let ItemKind::StrippedItem(inner) = &*item.kind { + inner.inner_items().for_each(|i| self.item(i.clone()).unwrap()); + } + + // Flatten items that recursively store other items + item.kind.inner_items().for_each(|i| self.item(i.clone()).unwrap()); + + let name = item.name; + let item_id = item.item_id; + if let Some(mut new_item) = self.convert_item(item) { + let can_be_ignored = match new_item.inner { + types::ItemEnum::Trait(ref mut t) => { + t.implementations = self.get_trait_implementors(item_id.expect_def_id()); + false + } + types::ItemEnum::Struct(ref mut s) => { + s.impls = self.get_impls(item_id.expect_def_id()); + false + } + types::ItemEnum::Enum(ref mut e) => { + e.impls = self.get_impls(item_id.expect_def_id()); + false + } + types::ItemEnum::Union(ref mut u) => { + u.impls = self.get_impls(item_id.expect_def_id()); + false + } + + types::ItemEnum::Method(_) + | types::ItemEnum::AssocConst { .. } + | types::ItemEnum::AssocType { .. } + | types::ItemEnum::PrimitiveType(_) => true, + types::ItemEnum::Module(_) + | types::ItemEnum::ExternCrate { .. } + | types::ItemEnum::Import(_) + | types::ItemEnum::StructField(_) + | types::ItemEnum::Variant(_) + | types::ItemEnum::Function(_) + | types::ItemEnum::TraitAlias(_) + | types::ItemEnum::Impl(_) + | types::ItemEnum::Typedef(_) + | types::ItemEnum::OpaqueTy(_) + | types::ItemEnum::Constant(_) + | types::ItemEnum::Static(_) + | types::ItemEnum::ForeignType + | types::ItemEnum::Macro(_) + | types::ItemEnum::ProcMacro(_) => false, + }; + let removed = self + .index + .borrow_mut() + .insert(from_item_id_with_name(item_id, self.tcx, name), new_item.clone()); + + // FIXME(adotinthevoid): Currently, the index is duplicated. This is a sanity check + // to make sure the items are unique. The main place this happens is when an item, is + // reexported in more than one place. See `rustdoc-json/reexport/in_root_and_mod` + if let Some(old_item) = removed { + // In case of generic implementations (like `impl Trait for T {}`), all the + // inner items will be duplicated so we can ignore if they are slightly different. + if !can_be_ignored { + assert_eq!(old_item, new_item); + } + } + } + + Ok(()) + } + + fn mod_item_in(&mut self, _item: &clean::Item) -> Result<(), Error> { + unreachable!("RUN_ON_MODULE = false should never call mod_item_in") + } + + fn after_krate(&mut self) -> Result<(), Error> { + debug!("Done with crate"); + + for primitive in Rc::clone(&self.cache).primitive_locations.values() { + self.get_impls(*primitive); + } + + let e = ExternalCrate { crate_num: LOCAL_CRATE }; + + let mut index = (*self.index).clone().into_inner(); + index.extend(self.get_trait_items()); + // This needs to be the default HashMap for compatibility with the public interface for + // rustdoc-json-types + #[allow(rustc::default_hash_types)] + let output = types::Crate { + root: types::Id(format!("0:0:{}", e.name(self.tcx).as_u32())), + crate_version: self.cache.crate_version.clone(), + includes_private: self.cache.document_private, + index: index.into_iter().collect(), + paths: self + .cache + .paths + .clone() + .into_iter() + .chain(self.cache.external_paths.clone().into_iter()) + .map(|(k, (path, kind))| { + ( + from_item_id(k.into(), self.tcx), + types::ItemSummary { + crate_id: k.krate.as_u32(), + path: path.iter().map(|s| s.to_string()).collect(), + kind: kind.into_tcx(self.tcx), + }, + ) + }) + .collect(), + external_crates: self + .cache + .extern_locations + .iter() + .map(|(crate_num, external_location)| { + let e = ExternalCrate { crate_num: *crate_num }; + ( + crate_num.as_u32(), + types::ExternalCrate { + name: e.name(self.tcx).to_string(), + html_root_url: match external_location { + ExternalLocation::Remote(s) => Some(s.clone()), + _ => None, + }, + }, + ) + }) + .collect(), + format_version: types::FORMAT_VERSION, + }; + let out_dir = self.out_path.clone(); + try_err!(create_dir_all(&out_dir), out_dir); + + let mut p = out_dir; + p.push(output.index.get(&output.root).unwrap().name.clone().unwrap()); + p.set_extension("json"); + let mut file = BufWriter::new(try_err!(File::create(&p), p)); + serde_json::ser::to_writer(&mut file, &output).unwrap(); + try_err!(file.flush(), p); + + Ok(()) + } + + fn cache(&self) -> &Cache { + &self.cache + } +} -- cgit v1.2.3