Skip to content

librustdoc: flatten nested ifs #138090

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

Merged
merged 1 commit into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 6 additions & 4 deletions src/librustdoc/clean/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -563,11 +563,13 @@ pub(crate) fn build_impl(
// Return if the trait itself or any types of the generic parameters are doc(hidden).
let mut stack: Vec<&Type> = vec![&for_];

if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
if !document_hidden && tcx.is_doc_hidden(did) {
return;
}
if let Some(did) = trait_.as_ref().map(|t| t.def_id())
&& !document_hidden
&& tcx.is_doc_hidden(did)
{
return;
}

if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
stack.extend(generics);
}
Expand Down
112 changes: 51 additions & 61 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -828,30 +828,26 @@ fn clean_ty_generics<'tcx>(
.iter()
.flat_map(|(pred, _)| {
let mut projection = None;
let param_idx = (|| {
let param_idx = {
let bound_p = pred.kind();
match bound_p.skip_binder() {
ty::ClauseKind::Trait(pred) => {
if let ty::Param(param) = pred.self_ty().kind() {
return Some(param.index);
}
ty::ClauseKind::Trait(pred) if let ty::Param(param) = pred.self_ty().kind() => {
Some(param.index)
}
ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg)) => {
if let ty::Param(param) = ty.kind() {
return Some(param.index);
}
ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg))
if let ty::Param(param) = ty.kind() =>
{
Some(param.index)
}
ty::ClauseKind::Projection(p) => {
if let ty::Param(param) = p.projection_term.self_ty().kind() {
projection = Some(bound_p.rebind(p));
return Some(param.index);
}
ty::ClauseKind::Projection(p)
if let ty::Param(param) = p.projection_term.self_ty().kind() =>
{
projection = Some(bound_p.rebind(p));
Some(param.index)
}
_ => (),
_ => None,
}

None
})();
};

if let Some(param_idx) = param_idx
&& let Some(bounds) = impl_trait.get_mut(&param_idx)
Expand Down Expand Up @@ -1378,12 +1374,12 @@ pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocCo
tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder();
if self_arg_ty == self_ty {
item.decl.inputs.values[0].type_ = SelfTy;
} else if let ty::Ref(_, ty, _) = *self_arg_ty.kind() {
if ty == self_ty {
match item.decl.inputs.values[0].type_ {
BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
_ => unreachable!(),
}
} else if let ty::Ref(_, ty, _) = *self_arg_ty.kind()
&& ty == self_ty
{
match item.decl.inputs.values[0].type_ {
BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
_ => unreachable!(),
}
}
}
Expand Down Expand Up @@ -2331,25 +2327,22 @@ fn clean_middle_opaque_bounds<'tcx>(
let bindings: ThinVec<_> = bounds
.iter()
.filter_map(|(bound, _)| {
if let ty::ClauseKind::Projection(proj) = bound.kind().skip_binder() {
if proj.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder() {
Some(AssocItemConstraint {
assoc: projection_to_path_segment(
// FIXME: This needs to be made resilient for `AliasTerm`s that
// are associated consts.
bound.kind().rebind(proj.projection_term.expect_ty(cx.tcx)),
cx,
),
kind: AssocItemConstraintKind::Equality {
term: clean_middle_term(bound.kind().rebind(proj.term), cx),
},
})
} else {
None
}
} else {
None
if let ty::ClauseKind::Projection(proj) = bound.kind().skip_binder()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That could even be a clippy lint. :3

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is. Not sure why it didn't fire. (I did run clippy on librustdoc, and didn't see a warning on this)
https://rust-lang.github.io/rust-clippy/master/index.html#collapsible_if
(Also, clippy-fix-PR coming soon)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, thanks!

&& proj.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder()
{
return Some(AssocItemConstraint {
assoc: projection_to_path_segment(
// FIXME: This needs to be made resilient for `AliasTerm`s that
// are associated consts.
bound.kind().rebind(proj.projection_term.expect_ty(cx.tcx)),
cx,
),
kind: AssocItemConstraintKind::Equality {
term: clean_middle_term(bound.kind().rebind(proj.term), cx),
},
});
}
None
})
.collect();

Expand Down Expand Up @@ -2743,23 +2736,20 @@ fn add_without_unwanted_attributes<'hir>(
}
let mut attr = attr.clone();
match attr {
hir::Attribute::Unparsed(ref mut normal) => {
if let [ident] = &*normal.path.segments {
let ident = ident.name;
if ident == sym::doc {
filter_doc_attr(&mut normal.args, is_inline);
attrs.push((Cow::Owned(attr), import_parent));
} else if is_inline || ident != sym::cfg {
// If it's not a `cfg()` attribute, we keep it.
attrs.push((Cow::Owned(attr), import_parent));
}
}
}
hir::Attribute::Parsed(..) => {
if is_inline {
hir::Attribute::Unparsed(ref mut normal) if let [ident] = &*normal.path.segments => {
let ident = ident.name;
if ident == sym::doc {
filter_doc_attr(&mut normal.args, is_inline);
attrs.push((Cow::Owned(attr), import_parent));
} else if is_inline || ident != sym::cfg {
// If it's not a `cfg()` attribute, we keep it.
attrs.push((Cow::Owned(attr), import_parent));
}
}
hir::Attribute::Parsed(..) if is_inline => {
attrs.push((Cow::Owned(attr), import_parent));
}
_ => {}
}
}
}
Expand Down Expand Up @@ -2961,16 +2951,16 @@ fn clean_extern_crate<'tcx>(
&& !cx.is_json_output();

let krate_owner_def_id = krate.owner_id.def_id;
if please_inline {
if let Some(items) = inline::try_inline(
if please_inline
&& let Some(items) = inline::try_inline(
cx,
Res::Def(DefKind::Mod, crate_def_id),
name,
Some((attrs, Some(krate_owner_def_id))),
&mut Default::default(),
) {
return items;
}
)
{
return items;
}

vec![Item::from_def_id_and_parts(
Expand Down
36 changes: 17 additions & 19 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,11 @@ impl ExternalCrate {
.get_attrs(def_id, sym::doc)
.flat_map(|attr| attr.meta_item_list().unwrap_or_default());
for meta in meta_items {
if meta.has_name(sym::keyword) {
if let Some(v) = meta.value_str() {
keyword = Some(v);
break;
}
if meta.has_name(sym::keyword)
&& let Some(v) = meta.value_str()
{
keyword = Some(v);
break;
}
}
return keyword.map(|p| (def_id, p));
Expand Down Expand Up @@ -1071,16 +1071,14 @@ pub(crate) fn extract_cfg_from_attrs<'a, I: Iterator<Item = &'a hir::Attribute>
// treat #[target_feature(enable = "feat")] attributes as if they were
// #[doc(cfg(target_feature = "feat"))] attributes as well
for attr in hir_attr_lists(attrs, sym::target_feature) {
if attr.has_name(sym::enable) {
if attr.value_str().is_some() {
// Clone `enable = "feat"`, change to `target_feature = "feat"`.
// Unwrap is safe because `value_str` succeeded above.
let mut meta = attr.meta_item().unwrap().clone();
meta.path = ast::Path::from_ident(Ident::with_dummy_span(sym::target_feature));

if let Ok(feat_cfg) = Cfg::parse(&ast::MetaItemInner::MetaItem(meta)) {
cfg &= feat_cfg;
}
if attr.has_name(sym::enable) && attr.value_str().is_some() {
// Clone `enable = "feat"`, change to `target_feature = "feat"`.
// Unwrap is safe because `value_str` succeeded above.
let mut meta = attr.meta_item().unwrap().clone();
meta.path = ast::Path::from_ident(Ident::with_dummy_span(sym::target_feature));

if let Ok(feat_cfg) = Cfg::parse(&ast::MetaItemInner::MetaItem(meta)) {
cfg &= feat_cfg;
}
}
}
Expand Down Expand Up @@ -1160,10 +1158,10 @@ impl Attributes {
continue;
}

if let Some(items) = attr.meta_item_list() {
if items.iter().filter_map(|i| i.meta_item()).any(|it| it.has_name(flag)) {
return true;
}
if let Some(items) = attr.meta_item_list()
&& items.iter().filter_map(|i| i.meta_item()).any(|it| it.has_name(flag))
{
return true;
}
}

Expand Down
16 changes: 8 additions & 8 deletions src/librustdoc/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -645,10 +645,10 @@ impl Options {

let extension_css = matches.opt_str("e").map(|s| PathBuf::from(&s));

if let Some(ref p) = extension_css {
if !p.is_file() {
dcx.fatal("option --extend-css argument must be a file");
}
if let Some(ref p) = extension_css
&& !p.is_file()
{
dcx.fatal("option --extend-css argument must be a file");
}

let mut themes = Vec::new();
Expand Down Expand Up @@ -720,10 +720,10 @@ impl Options {
}

let index_page = matches.opt_str("index-page").map(|s| PathBuf::from(&s));
if let Some(ref index_page) = index_page {
if !index_page.is_file() {
dcx.fatal("option `--index-page` argument must be a file");
}
if let Some(ref index_page) = index_page
&& !index_page.is_file()
{
dcx.fatal("option `--index-page` argument must be a file");
}

let target = parse_target_triple(early_dcx, matches);
Expand Down
5 changes: 2 additions & 3 deletions src/librustdoc/doctest/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,9 @@ impl HirCollector<'_> {
let ast_attrs = self.tcx.hir().attrs(self.tcx.local_def_id_to_hir_id(def_id));
if let Some(ref cfg) =
extract_cfg_from_attrs(ast_attrs.iter(), self.tcx, &FxHashSet::default())
&& !cfg.matches(&self.tcx.sess.psess, Some(self.tcx.features()))
{
if !cfg.matches(&self.tcx.sess.psess, Some(self.tcx.features())) {
return;
}
return;
}

let has_name = !name.is_empty();
Expand Down
4 changes: 3 additions & 1 deletion src/librustdoc/formats/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,9 @@ impl DocFolder for CacheBuilder<'_, '_> {
}
}

if let Some(generics) = i.trait_.as_ref().and_then(|t| t.generics()) {
if let Some(trait_) = &i.trait_
&& let Some(generics) = trait_.generics()
{
for bound in generics {
dids.extend(bound.def_id(self.cache));
}
Expand Down
83 changes: 41 additions & 42 deletions src/librustdoc/html/highlight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1102,53 +1102,52 @@ fn string_without_closing_tag<T: Display>(
});
}

if let Some(href_context) = href_context {
if let Some(href) =
href_context.context.shared.span_correspondence_map.get(&def_span).and_then(|href| {
let context = href_context.context;
// FIXME: later on, it'd be nice to provide two links (if possible) for all items:
// one to the documentation page and one to the source definition.
// FIXME: currently, external items only generate a link to their documentation,
// a link to their definition can be generated using this:
// https://github.com/rust-lang/rust/blob/60f1a2fc4b535ead9c85ce085fdce49b1b097531/src/librustdoc/html/render/context.rs#L315-L338
match href {
LinkFromSrc::Local(span) => {
context.href_from_span_relative(*span, &href_context.current_href)
}
LinkFromSrc::External(def_id) => {
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
.ok()
.map(|(url, _, _)| url)
}
LinkFromSrc::Primitive(prim) => format::href_with_root_path(
PrimitiveType::primitive_locations(context.tcx())[prim],
context,
Some(href_context.root_path),
)
.ok()
.map(|(url, _, _)| url),
LinkFromSrc::Doc(def_id) => {
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
.ok()
.map(|(doc_link, _, _)| doc_link)
}
if let Some(href_context) = href_context
&& let Some(href) = href_context.context.shared.span_correspondence_map.get(&def_span)
&& let Some(href) = {
let context = href_context.context;
// FIXME: later on, it'd be nice to provide two links (if possible) for all items:
// one to the documentation page and one to the source definition.
// FIXME: currently, external items only generate a link to their documentation,
// a link to their definition can be generated using this:
// https://github.com/rust-lang/rust/blob/60f1a2fc4b535ead9c85ce085fdce49b1b097531/src/librustdoc/html/render/context.rs#L315-L338
match href {
LinkFromSrc::Local(span) => {
context.href_from_span_relative(*span, &href_context.current_href)
}
})
{
if !open_tag {
// We're already inside an element which has the same klass, no need to give it
// again.
LinkFromSrc::External(def_id) => {
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
.ok()
.map(|(url, _, _)| url)
}
LinkFromSrc::Primitive(prim) => format::href_with_root_path(
PrimitiveType::primitive_locations(context.tcx())[prim],
context,
Some(href_context.root_path),
)
.ok()
.map(|(url, _, _)| url),
LinkFromSrc::Doc(def_id) => {
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
.ok()
.map(|(doc_link, _, _)| doc_link)
}
}
}
{
if !open_tag {
// We're already inside an element which has the same klass, no need to give it
// again.
write!(out, "<a href=\"{href}\">{text_s}").unwrap();
} else {
let klass_s = klass.as_html();
if klass_s.is_empty() {
write!(out, "<a href=\"{href}\">{text_s}").unwrap();
} else {
let klass_s = klass.as_html();
if klass_s.is_empty() {
write!(out, "<a href=\"{href}\">{text_s}").unwrap();
} else {
write!(out, "<a class=\"{klass_s}\" href=\"{href}\">{text_s}").unwrap();
}
write!(out, "<a class=\"{klass_s}\" href=\"{href}\">{text_s}").unwrap();
}
return Some("</a>");
}
return Some("</a>");
}
if !open_tag {
write!(out, "{}", text_s).unwrap();
Expand Down
Loading
Loading