Skip to content

Commit

Permalink
IAT: Rustdoc integration
Browse files Browse the repository at this point in the history
  • Loading branch information
fmease committed May 4, 2023
1 parent 46ec348 commit 61e1eda
Show file tree
Hide file tree
Showing 11 changed files with 183 additions and 40 deletions.
5 changes: 4 additions & 1 deletion src/librustdoc/clean/auto_trait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,10 @@ where
WherePredicate::EqPredicate { lhs, rhs, bound_params } => {
match *lhs {
Type::QPath(box QPathData {
ref assoc, ref self_type, ref trait_, ..
ref assoc,
ref self_type,
trait_: Some(ref trait_),
..
}) => {
let ty = &*self_type;
let mut new_trait = trait_.clone();
Expand Down
7 changes: 6 additions & 1 deletion src/librustdoc/clean/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -706,7 +706,12 @@ fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean:

g.where_predicates.retain(|pred| match pred {
clean::WherePredicate::BoundPredicate {
ty: clean::QPath(box clean::QPathData { self_type: clean::Generic(ref s), trait_, .. }),
ty:
clean::QPath(box clean::QPathData {
self_type: clean::Generic(ref s),
trait_: Some(trait_),
..
}),
bounds,
..
} => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did),
Expand Down
60 changes: 45 additions & 15 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ fn clean_projection<'tcx>(
assoc: projection_to_path_segment(ty, cx),
should_show_cast,
self_type,
trait_,
trait_: Some(trait_),
}))
}

Expand Down Expand Up @@ -1330,7 +1330,13 @@ pub(crate) fn clean_middle_assoc_item<'tcx>(
let mut bounds: Vec<GenericBound> = Vec::new();
generics.where_predicates.retain_mut(|pred| match *pred {
WherePredicate::BoundPredicate {
ty: QPath(box QPathData { ref assoc, ref self_type, ref trait_, .. }),
ty:
QPath(box QPathData {
ref assoc,
ref self_type,
trait_: Some(ref trait_),
..
}),
bounds: ref mut pred_bounds,
..
} => {
Expand Down Expand Up @@ -1492,25 +1498,30 @@ fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type
assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
should_show_cast,
self_type,
trait_,
trait_: Some(trait_),
}))
}
hir::QPath::TypeRelative(qself, segment) => {
let ty = hir_ty_to_ty(cx.tcx, hir_ty);
let res = match ty.kind() {
let self_type = clean_ty(qself, cx);

let (trait_, should_show_cast) = match ty.kind() {
ty::Alias(ty::Projection, proj) => {
Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id)
let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
register_res(cx, trait_.res);
let self_def_id = res.opt_def_id();
let should_show_cast =
compute_should_show_cast(self_def_id, &trait_, &self_type);

(Some(trait_), should_show_cast)
}
ty::Alias(ty::Inherent, _) => (None, false),
// Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
ty::Error(_) => return Type::Infer,
// Otherwise, this is an inherent associated type.
_ => return clean_middle_ty(ty::Binder::dummy(ty), cx, None),
_ => bug!("clean: expected associated type, found `{ty:?}`"),
};
let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
register_res(cx, trait_.res);
let self_def_id = res.opt_def_id();
let self_type = clean_ty(qself, cx);
let should_show_cast = compute_should_show_cast(self_def_id, &trait_, &self_type);

Type::QPath(Box::new(QPathData {
assoc: clean_path_segment(segment, cx),
should_show_cast,
Expand Down Expand Up @@ -1836,9 +1847,28 @@ pub(crate) fn clean_middle_ty<'tcx>(
clean_projection(bound_ty.rebind(*data), cx, parent_def_id)
}

// FIXME(fmease): Clean inherent projections properly. This requires making the trait ref in
// `QPathData` optional or alternatively adding a new `clean::Type` variant.
ty::Alias(ty::Inherent, _data) => Type::Infer,
ty::Alias(ty::Inherent, alias_ty) => {
let alias_ty = bound_ty.rebind(alias_ty);
let self_type = clean_middle_ty(alias_ty.map_bound(|ty| ty.self_ty()), cx, None);

Type::QPath(Box::new(QPathData {
assoc: PathSegment {
name: cx.tcx.associated_item(alias_ty.skip_binder().def_id).name,
args: GenericArgs::AngleBracketed {
args: substs_to_args(
cx,
alias_ty.map_bound(|ty| ty.substs.as_slice()),
true,
)
.into(),
bindings: Default::default(),
},
},
should_show_cast: false,
self_type,
trait_: None,
}))
}

ty::Param(ref p) => {
if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
Expand Down
4 changes: 2 additions & 2 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1660,7 +1660,7 @@ impl Type {

pub(crate) fn projection(&self) -> Option<(&Type, DefId, PathSegment)> {
if let QPath(box QPathData { self_type, trait_, assoc, .. }) = self {
Some((self_type, trait_.def_id(), assoc.clone()))
Some((self_type, trait_.as_ref()?.def_id(), assoc.clone()))
} else {
None
}
Expand Down Expand Up @@ -1704,7 +1704,7 @@ pub(crate) struct QPathData {
pub self_type: Type,
/// FIXME: compute this field on demand.
pub should_show_cast: bool,
pub trait_: Path,
pub trait_: Option<Path>,
}

/// A primitive (aka, builtin) type.
Expand Down
46 changes: 35 additions & 11 deletions src/librustdoc/html/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1116,14 +1116,17 @@ fn fmt_type<'cx>(
ref trait_,
should_show_cast,
}) => {
// FIXME(inherent_associated_types): Once we support non-ADT self-types (#106719),
// we need to surround them with angle brackets in some cases (e.g. `<dyn …>::P`).

if f.alternate() {
if should_show_cast {
if let Some(trait_) = trait_ && should_show_cast {
write!(f, "<{:#} as {:#}>::", self_type.print(cx), trait_.print(cx))?
} else {
write!(f, "{:#}::", self_type.print(cx))?
}
} else {
if should_show_cast {
if let Some(trait_) = trait_ && should_show_cast {
write!(f, "&lt;{} as {}&gt;::", self_type.print(cx), trait_.print(cx))?
} else {
write!(f, "{}::", self_type.print(cx))?
Expand All @@ -1139,15 +1142,36 @@ fn fmt_type<'cx>(
// the ugliness comes from inlining across crates where
// everything comes in as a fully resolved QPath (hard to
// look at).
if !f.alternate() && let Ok((url, _, path)) = href(trait_.def_id(), cx) {
write!(
f,
"<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
title=\"type {path}::{name}\">{name}</a>",
shortty = ItemType::AssocType,
name = assoc.name,
path = join_with_double_colon(&path),
)
if !f.alternate() {
// FIXME(inherent_associated_types): We always link to the very first associated
// type (in respect to source order) that bears the given name (`assoc.name`) and that is
// affiliated with the computed `DefId`. This is obviously incorrect when we have
// multiple impl blocks. Ideally, we would thread the `DefId` of the assoc ty itself
// through here and map it to the corresponding HTML ID that was generated by
// `render::Context::derive_id` when the impl blocks were rendered.
// There is no such mapping unfortunately.
// As a hack, we could badly imitate `derive_id` here by keeping *count* when looking
// for the assoc ty `DefId` in `tcx.associated_items(self_ty_did).in_definition_order()`
// considering privacy, `doc(hidden)`, etc.
// I don't feel like that right now :cold_sweat:.

let parent_href = match trait_ {
Some(trait_) => href(trait_.def_id(), cx).ok(),
None => self_type.def_id(cx.cache()).and_then(|did| href(did, cx).ok()),
};

if let Some((url, _, path)) = parent_href {
write!(
f,
"<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \
title=\"type {path}::{name}\">{name}</a>",
shortty = ItemType::AssocType,
name = assoc.name,
path = join_with_double_colon(&path),
)
} else {
write!(f, "{}", assoc.name)
}
} else {
write!(f, "{}", assoc.name)
}?;
Expand Down
4 changes: 3 additions & 1 deletion src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2202,7 +2202,9 @@ fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> {
}
clean::Type::QPath(box clean::QPathData { self_type, trait_, .. }) => {
work.push_back(self_type);
process_path(trait_.def_id());
if let Some(trait_) = trait_ {
process_path(trait_.def_id());
}
}
_ => {}
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/json/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ impl FromWithTcx<clean::Type> for Type {
name: assoc.name.to_string(),
args: Box::new(assoc.args.into_tcx(tcx)),
self_type: Box::new(self_type.into_tcx(tcx)),
trait_: trait_.into_tcx(tcx),
trait_: trait_.map(|trait_| trait_.into_tcx(tcx)),
},
}
}
Expand Down
8 changes: 5 additions & 3 deletions src/rustdoc-json-types/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// rustdoc format-version.
pub const FORMAT_VERSION: u32 = 24;
pub const FORMAT_VERSION: u32 = 25;

/// A `Crate` is the root of the emitted JSON blob. It contains all type/documentation information
/// about the language items in the local crate, as well as info about external items to allow
Expand Down Expand Up @@ -581,13 +581,15 @@ pub enum Type {
#[serde(rename = "type")]
type_: Box<Type>,
},
/// `<Type as Trait>::Name` or associated types like `T::Item` where `T: Iterator`
/// Associated types like `<Type as Trait>::Name` and `T::Item` where
/// `T: Iterator` or inherent associated types like `Struct::Name`.
QualifiedPath {
name: String,
args: Box<GenericArgs>,
self_type: Box<Type>,
/// `None` iff this is an *inherent* associated type.
#[serde(rename = "trait")]
trait_: Path,
trait_: Option<Path>,
},
}

Expand Down
4 changes: 3 additions & 1 deletion src/tools/jsondoclint/src/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,9 @@ impl<'a> Validator<'a> {
Type::QualifiedPath { name: _, args, self_type, trait_ } => {
self.check_generic_args(&**args);
self.check_type(&**self_type);
self.check_path(trait_, PathKind::Trait);
if let Some(trait_) = trait_ {
self.check_path(trait_, PathKind::Trait);
}
}
}
}
Expand Down
38 changes: 34 additions & 4 deletions tests/rustdoc/inherent-projections.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,44 @@
#![feature(inherent_associated_types)]
#![allow(incomplete_features)]

// FIXME(fmease): Properly render inherent projections.

// @has inherent_projections/fn.create.html
// @has - '//pre[@class="rust item-decl"]' "create() -> _"
// @has 'inherent_projections/fn.create.html'
// @has - '//pre[@class="rust item-decl"]' "create() -> Owner::Metadata"
// @has - '//pre[@class="rust item-decl"]//a[@class="associatedtype"]/@href' 'struct.Owner.html#associatedtype.Metadata'
pub fn create() -> Owner::Metadata {}

pub struct Owner;

impl Owner {
pub type Metadata = ();
}

// Make sure we handle bound vars correctly.
// @has 'inherent_projections/type.User.html' '//pre[@class="rust item-decl"]' "for<'a> fn(_: Carrier<'a>::Focus)"
pub type User = for<'a> fn(Carrier<'a>::Focus);

pub struct Carrier<'a>(&'a ());

impl<'a> Carrier<'a> {
pub type Focus = &'a mut i32;
}

////////////////////////////////////////

// FIXME(inherent_associated_types): Below we link to `Proj` but we should link to `Proj-1`.
// The current test checks for the buggy behavior for demonstration purposes.

// @has 'inherent_projections/type.Test.html'
// @has - '//pre[@class="rust item-decl"]' "Parametrized<i32>"
// @has - '//pre[@class="rust item-decl"]//a[@class="associatedtype"]/@href' 'struct.Parametrized.html#associatedtype.Proj'
// @!has - '//pre[@class="rust item-decl"]//a[@class="associatedtype"]/@href' 'struct.Parametrized.html#associatedtype.Proj-1'
pub type Test = Parametrized<i32>::Proj;

pub struct Parametrized<T>(T);

impl Parametrized<bool> {
pub type Proj = ();
}

impl Parametrized<i32> {
pub type Proj = String;
}
45 changes: 45 additions & 0 deletions tests/rustdoc/intra-doc/inherent-associated-types.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#![feature(inherent_associated_types)]

#![allow(incomplete_features)]
#![deny(rustdoc::broken_intra_doc_links)]

// @has inherent_associated_types/index.html

// @has - '//a/@href' 'enum.Simple.html#associatedtype.Type'
//! [`Simple::Type`]
pub enum Simple {}

impl Simple {
pub type Type = ();
}

////////////////////////////////////////

// @has 'inherent_associated_types/type.Test0.html' '//a/@href' \
// 'struct.Parametrized.html#associatedtype.Proj'
/// [`Parametrized<bool>::Proj`]
pub type Test0 = ();

// FIXME(inherent_associated_types): The intra-doc link below should point to `Proj-1` not `Proj`.
// The current test checks for the buggy behavior for demonstration purposes.
// The same bug happens for inherent associated functions and constants (see #85960, #93398).
//
// Further, at some point we should reject the intra-doc link `Parametrized::Proj`.
// It currently links to `Parametrized<bool>::Proj`.

// @has 'inherent_associated_types/type.Test1.html'
// @has - '//a/@href' 'struct.Parametrized.html#associatedtype.Proj'
// @!has - '//a/@href' 'struct.Parametrized.html#associatedtype.Proj-1'
/// [`Parametrized<i32>::Proj`]
pub type Test1 = ();

pub struct Parametrized<T>(T);

impl Parametrized<bool> {
pub type Proj = ();
}

impl Parametrized<i32> {
pub type Proj = String;
}

0 comments on commit 61e1eda

Please sign in to comment.