Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Normalize <X as Y>::T for rustdoc #77467

Merged
merged 4 commits into from
Nov 26, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
325 changes: 185 additions & 140 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,157 @@ impl Clean<Item> for ty::AssocItem {
}
}

fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &DocContext<'_>) -> Type {
use rustc_hir::GenericParamCount;
let hir::Ty { hir_id, span, ref kind } = *hir_ty;
let qpath = match kind {
hir::TyKind::Path(qpath) => qpath,
_ => unreachable!(),
};

match qpath {
hir::QPath::Resolved(None, ref path) => {
if let Res::Def(DefKind::TyParam, did) = path.res {
if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
return new_ty;
}
if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
return ImplTrait(bounds);
}
}

let mut alias = None;
if let Res::Def(DefKind::TyAlias, def_id) = path.res {
// Substitute private type aliases
if let Some(def_id) = def_id.as_local() {
let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
}
}
};

if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
let provided_params = &path.segments.last().expect("segments were empty");
let mut ty_substs = FxHashMap::default();
let mut lt_substs = FxHashMap::default();
let mut ct_substs = FxHashMap::default();
let generic_args = provided_params.generic_args();
{
let mut indices: GenericParamCount = Default::default();
for param in generics.params.iter() {
match param.kind {
hir::GenericParamKind::Lifetime { .. } => {
let mut j = 0;
let lifetime = generic_args.args.iter().find_map(|arg| match arg {
hir::GenericArg::Lifetime(lt) => {
if indices.lifetimes == j {
return Some(lt);
}
j += 1;
None
}
_ => None,
});
if let Some(lt) = lifetime.cloned() {
let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
let cleaned = if !lt.is_elided() {
lt.clean(cx)
} else {
self::types::Lifetime::elided()
};
lt_substs.insert(lt_def_id.to_def_id(), cleaned);
}
indices.lifetimes += 1;
}
hir::GenericParamKind::Type { ref default, .. } => {
let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
let mut j = 0;
let type_ = generic_args.args.iter().find_map(|arg| match arg {
hir::GenericArg::Type(ty) => {
if indices.types == j {
return Some(ty);
}
j += 1;
None
}
_ => None,
});
if let Some(ty) = type_ {
ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
} else if let Some(default) = *default {
ty_substs
.insert(ty_param_def_id.to_def_id(), default.clean(cx));
}
indices.types += 1;
}
hir::GenericParamKind::Const { .. } => {
let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
let mut j = 0;
let const_ = generic_args.args.iter().find_map(|arg| match arg {
hir::GenericArg::Const(ct) => {
if indices.consts == j {
return Some(ct);
}
j += 1;
None
}
_ => None,
});
if let Some(ct) = const_ {
ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
}
// FIXME(const_generics:defaults)
indices.consts += 1;
}
}
}
}
return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
}
resolve_type(cx, path.clean(cx), hir_id)
}
hir::QPath::Resolved(Some(ref qself), ref p) => {
// Try to normalize `<X as Y>::T` to a type
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
if let Some(normalized_value) = normalize(cx.tcx, ty) {
return normalized_value.clean(cx);
}

let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
let trait_segments = &segments[..segments.len() - 1];
let trait_path = self::Path {
global: p.is_global(),
res: Res::Def(
DefKind::Trait,
cx.tcx.associated_item(p.res.def_id()).container.id(),
),
segments: trait_segments.clean(cx),
};
Type::QPath {
name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path, hir_id),
}
}
hir::QPath::TypeRelative(ref qself, ref segment) => {
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
let res = if let ty::Projection(proj) = ty.kind() {
Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
} else {
Res::Err
};
let trait_path = hir::Path { span, res, segments: &[] };
Type::QPath {
name: segment.ident.name.clean(cx),
self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path.clean(cx), hir_id),
}
}
hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
}
}

impl Clean<Type> for hir::Ty<'_> {
fn clean(&self, cx: &DocContext<'_>) -> Type {
use rustc_hir::*;
Expand Down Expand Up @@ -1318,145 +1469,7 @@ impl Clean<Type> for hir::Ty<'_> {
unreachable!()
}
}
TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
if let Res::Def(DefKind::TyParam, did) = path.res {
if let Some(new_ty) = cx.ty_substs.borrow().get(&did).cloned() {
return new_ty;
}
if let Some(bounds) = cx.impl_trait_bounds.borrow_mut().remove(&did.into()) {
return ImplTrait(bounds);
}
}

let mut alias = None;
if let Res::Def(DefKind::TyAlias, def_id) = path.res {
// Substitute private type aliases
if let Some(def_id) = def_id.as_local() {
let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
if !cx.renderinfo.borrow().access_levels.is_exported(def_id.to_def_id()) {
alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
}
}
};

if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
let provided_params = &path.segments.last().expect("segments were empty");
let mut ty_substs = FxHashMap::default();
let mut lt_substs = FxHashMap::default();
let mut ct_substs = FxHashMap::default();
let generic_args = provided_params.generic_args();
{
let mut indices: GenericParamCount = Default::default();
for param in generics.params.iter() {
match param.kind {
hir::GenericParamKind::Lifetime { .. } => {
let mut j = 0;
let lifetime =
generic_args.args.iter().find_map(|arg| match arg {
hir::GenericArg::Lifetime(lt) => {
if indices.lifetimes == j {
return Some(lt);
}
j += 1;
None
}
_ => None,
});
if let Some(lt) = lifetime.cloned() {
let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
let cleaned = if !lt.is_elided() {
lt.clean(cx)
} else {
self::types::Lifetime::elided()
};
lt_substs.insert(lt_def_id.to_def_id(), cleaned);
}
indices.lifetimes += 1;
}
hir::GenericParamKind::Type { ref default, .. } => {
let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
let mut j = 0;
let type_ =
generic_args.args.iter().find_map(|arg| match arg {
hir::GenericArg::Type(ty) => {
if indices.types == j {
return Some(ty);
}
j += 1;
None
}
_ => None,
});
if let Some(ty) = type_ {
ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
} else if let Some(default) = *default {
ty_substs
.insert(ty_param_def_id.to_def_id(), default.clean(cx));
}
indices.types += 1;
}
hir::GenericParamKind::Const { .. } => {
let const_param_def_id =
cx.tcx.hir().local_def_id(param.hir_id);
let mut j = 0;
let const_ =
generic_args.args.iter().find_map(|arg| match arg {
hir::GenericArg::Const(ct) => {
if indices.consts == j {
return Some(ct);
}
j += 1;
None
}
_ => None,
});
if let Some(ct) = const_ {
ct_substs
.insert(const_param_def_id.to_def_id(), ct.clean(cx));
}
// FIXME(const_generics:defaults)
indices.consts += 1;
}
}
}
}
return cx.enter_alias(ty_substs, lt_substs, ct_substs, || ty.clean(cx));
}
resolve_type(cx, path.clean(cx), self.hir_id)
}
TyKind::Path(hir::QPath::Resolved(Some(ref qself), ref p)) => {
let segments = if p.is_global() { &p.segments[1..] } else { &p.segments };
let trait_segments = &segments[..segments.len() - 1];
let trait_path = self::Path {
global: p.is_global(),
res: Res::Def(
DefKind::Trait,
cx.tcx.associated_item(p.res.def_id()).container.id(),
),
segments: trait_segments.clean(cx),
};
Type::QPath {
name: p.segments.last().expect("segments were empty").ident.name.clean(cx),
self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path, self.hir_id),
}
}
TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
let mut res = Res::Err;
let ty = hir_ty_to_ty(cx.tcx, self);
if let ty::Projection(proj) = ty.kind() {
res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
}
let trait_path = hir::Path { span: self.span, res, segments: &[] };
Type::QPath {
name: segment.ident.name.clean(cx),
self_type: box qself.clean(cx),
trait_: box resolve_type(cx, trait_path.clean(cx), self.hir_id),
}
}
TyKind::Path(hir::QPath::LangItem(..)) => {
bug!("clean: requiring documentation of lang item")
}
TyKind::Path(_) => clean_qpath(&self, cx),
TyKind::TraitObject(ref bounds, ref lifetime) => {
match bounds[0].clean(cx).trait_ {
ResolvedPath { path, param_names: None, did, is_generic } => {
Expand Down Expand Up @@ -1484,10 +1497,42 @@ impl Clean<Type> for hir::Ty<'_> {
}
}

/// Returns `None` if the type could not be normalized
fn normalize(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
use crate::rustc_trait_selection::infer::TyCtxtInferExt;
use crate::rustc_trait_selection::traits::query::normalize::AtExt;
use rustc_middle::traits::ObligationCause;
use rustc_middle::ty::ParamEnv;

// Try to normalize `<X as Y>::T` to a type
// FIXME: rustdoc won't be able to perform 'partial' normalization
// until this param env is actually correct
// 'partial': `<Vec<T> as IntoIterator>::IntoIter>` -> `vec::IntoIter<T>`
let param_env = ParamEnv::empty();
let lifted = ty.lift_to_tcx(tcx).unwrap();
let normalized = tcx.infer_ctxt().enter(|infcx| {
infcx
.at(&ObligationCause::dummy(), param_env)
.normalize(lifted)
.map(|resolved| infcx.resolve_vars_if_possible(resolved.value))
});
match normalized {
Ok(normalized_value) => {
debug!("resolved {:?} to {:?}", ty, normalized_value);
Some(normalized_value)
}
Err(err) => {
debug!("failed to resolve {:?}: {:?}", ty, err);
None
}
}
}

impl<'tcx> Clean<Type> for Ty<'tcx> {
fn clean(&self, cx: &DocContext<'_>) -> Type {
debug!("cleaning type: {:?}", self);
match *self.kind() {
let ty = normalize(cx.tcx, self.lift_to_tcx(cx.tcx).unwrap()).unwrap_or(self);
jyn514 marked this conversation as resolved.
Show resolved Hide resolved
match *ty.kind() {
ty::Never => Never,
ty::Bool => Primitive(PrimitiveType::Bool),
ty::Char => Primitive(PrimitiveType::Char),
Expand Down
12 changes: 12 additions & 0 deletions src/test/rustdoc/auxiliary/normalize-assoc-item.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#![crate_name = "inner"]
pub trait MyTrait {
type Y;
}

impl MyTrait for u32 {
type Y = i32;
}

pub fn foo() -> <u32 as MyTrait>::Y {
0
}
Loading