Make some matches slightly more ergonomic in librustdoc

This commit is contained in:
Yotam Ofek 2025-05-17 13:05:05 +00:00
parent b0e925903a
commit a4765c9fc2
5 changed files with 98 additions and 120 deletions

View file

@ -144,7 +144,7 @@ impl Cfg {
/// Whether the configuration consists of just `Cfg` or `Not`.
fn is_simple(&self) -> bool {
match *self {
match self {
Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) => true,
Cfg::All(..) | Cfg::Any(..) => false,
}
@ -152,7 +152,7 @@ impl Cfg {
/// Whether the configuration consists of just `Cfg`, `Not` or `All`.
fn is_all(&self) -> bool {
match *self {
match self {
Cfg::False | Cfg::True | Cfg::Cfg(..) | Cfg::Not(..) | Cfg::All(..) => true,
Cfg::Any(..) => false,
}
@ -204,7 +204,7 @@ impl Cfg {
}
fn should_append_only_to_description(&self) -> bool {
match *self {
match self {
Cfg::False | Cfg::True => false,
Cfg::Any(..) | Cfg::All(..) | Cfg::Cfg(..) => true,
Cfg::Not(box Cfg::Cfg(..)) => true,
@ -261,17 +261,17 @@ impl ops::Not for Cfg {
impl ops::BitAndAssign for Cfg {
fn bitand_assign(&mut self, other: Cfg) {
match (self, other) {
(&mut Cfg::False, _) | (_, Cfg::True) => {}
(Cfg::False, _) | (_, Cfg::True) => {}
(s, Cfg::False) => *s = Cfg::False,
(s @ &mut Cfg::True, b) => *s = b,
(&mut Cfg::All(ref mut a), Cfg::All(ref mut b)) => {
(s @ Cfg::True, b) => *s = b,
(Cfg::All(a), Cfg::All(ref mut b)) => {
for c in b.drain(..) {
if !a.contains(&c) {
a.push(c);
}
}
}
(&mut Cfg::All(ref mut a), ref mut b) => {
(Cfg::All(a), ref mut b) => {
if !a.contains(b) {
a.push(mem::replace(b, Cfg::True));
}
@ -305,15 +305,15 @@ impl ops::BitOrAssign for Cfg {
fn bitor_assign(&mut self, other: Cfg) {
match (self, other) {
(Cfg::True, _) | (_, Cfg::False) | (_, Cfg::True) => {}
(s @ &mut Cfg::False, b) => *s = b,
(&mut Cfg::Any(ref mut a), Cfg::Any(ref mut b)) => {
(s @ Cfg::False, b) => *s = b,
(Cfg::Any(a), Cfg::Any(ref mut b)) => {
for c in b.drain(..) {
if !a.contains(&c) {
a.push(c);
}
}
}
(&mut Cfg::Any(ref mut a), ref mut b) => {
(Cfg::Any(a), ref mut b) => {
if !a.contains(b) {
a.push(mem::replace(b, Cfg::True));
}
@ -440,40 +440,34 @@ impl Display<'_> {
impl fmt::Display for Display<'_> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self.0 {
Cfg::Not(ref child) => match **child {
Cfg::Any(ref sub_cfgs) => {
let separator =
if sub_cfgs.iter().all(Cfg::is_simple) { " nor " } else { ", nor " };
fmt.write_str("neither ")?;
match self.0 {
Cfg::Not(box Cfg::Any(sub_cfgs)) => {
let separator =
if sub_cfgs.iter().all(Cfg::is_simple) { " nor " } else { ", nor " };
fmt.write_str("neither ")?;
sub_cfgs
.iter()
.map(|sub_cfg| {
fmt::from_fn(|fmt| {
write_with_opt_paren(
fmt,
!sub_cfg.is_all(),
Display(sub_cfg, self.1),
)
})
sub_cfgs
.iter()
.map(|sub_cfg| {
fmt::from_fn(|fmt| {
write_with_opt_paren(fmt, !sub_cfg.is_all(), Display(sub_cfg, self.1))
})
.joined(separator, fmt)
}
ref simple @ Cfg::Cfg(..) => write!(fmt, "non-{}", Display(simple, self.1)),
ref c => write!(fmt, "not ({})", Display(c, self.1)),
},
})
.joined(separator, fmt)
}
Cfg::Not(box simple @ Cfg::Cfg(..)) => write!(fmt, "non-{}", Display(simple, self.1)),
Cfg::Not(box c) => write!(fmt, "not ({})", Display(c, self.1)),
Cfg::Any(ref sub_cfgs) => {
Cfg::Any(sub_cfgs) => {
let separator = if sub_cfgs.iter().all(Cfg::is_simple) { " or " } else { ", or " };
self.display_sub_cfgs(fmt, sub_cfgs, separator)
}
Cfg::All(ref sub_cfgs) => self.display_sub_cfgs(fmt, sub_cfgs, " and "),
Cfg::All(sub_cfgs) => self.display_sub_cfgs(fmt, sub_cfgs, " and "),
Cfg::True => fmt.write_str("everywhere"),
Cfg::False => fmt.write_str("nowhere"),
Cfg::Cfg(name, value) => {
&Cfg::Cfg(name, value) => {
let human_readable = match (name, value) {
(sym::unix, None) => "Unix",
(sym::windows, None) => "Windows",

View file

@ -224,9 +224,9 @@ fn clean_generic_bound<'tcx>(
bound: &hir::GenericBound<'tcx>,
cx: &mut DocContext<'tcx>,
) -> Option<GenericBound> {
Some(match *bound {
Some(match bound {
hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
hir::GenericBound::Trait(ref t) => {
hir::GenericBound::Trait(t) => {
// `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
if let hir::BoundConstness::Maybe(_) = t.modifiers.constness
&& cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap())
@ -352,8 +352,8 @@ fn clean_where_predicate<'tcx>(
if !predicate.kind.in_where_clause() {
return None;
}
Some(match *predicate.kind {
hir::WherePredicateKind::BoundPredicate(ref wbp) => {
Some(match predicate.kind {
hir::WherePredicateKind::BoundPredicate(wbp) => {
let bound_params = wbp
.bound_generic_params
.iter()
@ -366,12 +366,12 @@ fn clean_where_predicate<'tcx>(
}
}
hir::WherePredicateKind::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
hir::WherePredicateKind::RegionPredicate(wrp) => WherePredicate::RegionPredicate {
lifetime: clean_lifetime(wrp.lifetime, cx),
bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
},
hir::WherePredicateKind::EqPredicate(ref wrp) => WherePredicate::EqPredicate {
hir::WherePredicateKind::EqPredicate(wrp) => WherePredicate::EqPredicate {
lhs: clean_ty(wrp.lhs_ty, cx),
rhs: clean_ty(wrp.rhs_ty, cx).into(),
},
@ -2112,7 +2112,7 @@ pub(crate) fn clean_middle_ty<'tcx>(
);
Type::Path { path }
}
ty::Dynamic(obj, ref reg, _) => {
ty::Dynamic(obj, reg, _) => {
// HACK: pick the first `did` as the `did` of the trait object. Someone
// might want to implement "native" support for marker-trait-only
// trait objects.
@ -2129,7 +2129,7 @@ pub(crate) fn clean_middle_ty<'tcx>(
inline::record_extern_fqn(cx, did, ItemType::Trait);
let lifetime = clean_trait_object_lifetime_bound(*reg, container, obj, cx.tcx);
let lifetime = clean_trait_object_lifetime_bound(reg, container, obj, cx.tcx);
let mut bounds = dids
.map(|did| {
@ -2846,7 +2846,7 @@ fn clean_maybe_renamed_item<'tcx>(
));
return ret;
}
ItemKind::Enum(_, ref def, generics) => EnumItem(Enum {
ItemKind::Enum(_, def, generics) => EnumItem(Enum {
variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
generics: clean_generics(generics, cx),
}),
@ -2854,11 +2854,11 @@ fn clean_maybe_renamed_item<'tcx>(
generics: clean_generics(generics, cx),
bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
}),
ItemKind::Union(_, ref variant_data, generics) => UnionItem(Union {
ItemKind::Union(_, variant_data, generics) => UnionItem(Union {
generics: clean_generics(generics, cx),
fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
}),
ItemKind::Struct(_, ref variant_data, generics) => StructItem(Struct {
ItemKind::Struct(_, variant_data, generics) => StructItem(Struct {
ctor_kind: variant_data.ctor_kind(),
generics: clean_generics(generics, cx),
fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),

View file

@ -1337,9 +1337,9 @@ pub(crate) enum WherePredicate {
impl WherePredicate {
pub(crate) fn get_bounds(&self) -> Option<&[GenericBound]> {
match *self {
WherePredicate::BoundPredicate { ref bounds, .. } => Some(bounds),
WherePredicate::RegionPredicate { ref bounds, .. } => Some(bounds),
match self {
WherePredicate::BoundPredicate { bounds, .. } => Some(bounds),
WherePredicate::RegionPredicate { bounds, .. } => Some(bounds),
_ => None,
}
}
@ -1709,13 +1709,13 @@ impl Type {
///
/// [clean]: crate::clean
pub(crate) fn def_id(&self, cache: &Cache) -> Option<DefId> {
let t: PrimitiveType = match *self {
Type::Path { ref path } => return Some(path.def_id()),
DynTrait(ref bounds, _) => return bounds.first().map(|b| b.trait_.def_id()),
Primitive(p) => return cache.primitive_locations.get(&p).cloned(),
let t: PrimitiveType = match self {
Type::Path { path } => return Some(path.def_id()),
DynTrait(bounds, _) => return bounds.first().map(|b| b.trait_.def_id()),
Primitive(p) => return cache.primitive_locations.get(p).cloned(),
BorrowedRef { type_: box Generic(..), .. } => PrimitiveType::Reference,
BorrowedRef { ref type_, .. } => return type_.def_id(cache),
Tuple(ref tys) => {
BorrowedRef { type_, .. } => return type_.def_id(cache),
Tuple(tys) => {
if tys.is_empty() {
PrimitiveType::Unit
} else {
@ -1727,7 +1727,7 @@ impl Type {
Array(..) => PrimitiveType::Array,
Type::Pat(..) => PrimitiveType::Pat,
RawPointer(..) => PrimitiveType::RawPointer,
QPath(box QPathData { ref self_type, .. }) => return self_type.def_id(cache),
QPath(box QPathData { self_type, .. }) => return self_type.def_id(cache),
Generic(_) | SelfTy | Infer | ImplTrait(_) | UnsafeBinder(_) => return None,
};
Primitive(t).def_id(cache)

View file

@ -70,12 +70,12 @@ impl Serialize for ItemType {
impl<'a> From<&'a clean::Item> for ItemType {
fn from(item: &'a clean::Item) -> ItemType {
let kind = match item.kind {
clean::StrippedItem(box ref item) => item,
ref kind => kind,
let kind = match &item.kind {
clean::StrippedItem(box item) => item,
kind => kind,
};
match *kind {
match kind {
clean::ModuleItem(..) => ItemType::Module,
clean::ExternCrateItem { .. } => ItemType::ExternCrate,
clean::ImportItem(..) => ItemType::Import,
@ -103,7 +103,7 @@ impl<'a> From<&'a clean::Item> for ItemType {
clean::ForeignTypeItem => ItemType::ForeignType,
clean::KeywordItem => ItemType::Keyword,
clean::TraitAliasItem(..) => ItemType::TraitAlias,
clean::ProcMacroItem(ref mac) => match mac.kind {
clean::ProcMacroItem(mac) => match mac.kind {
MacroKind::Bang => ItemType::Macro,
MacroKind::Attr => ItemType::ProcAttribute,
MacroKind::Derive => ItemType::ProcDerive,
@ -134,22 +134,15 @@ impl ItemType {
DefKind::Trait => Self::Trait,
DefKind::TyAlias => Self::TypeAlias,
DefKind::TraitAlias => Self::TraitAlias,
DefKind::Macro(kind) => match kind {
MacroKind::Bang => ItemType::Macro,
MacroKind::Attr => ItemType::ProcAttribute,
MacroKind::Derive => ItemType::ProcDerive,
},
DefKind::Macro(MacroKind::Bang) => ItemType::Macro,
DefKind::Macro(MacroKind::Attr) => ItemType::ProcAttribute,
DefKind::Macro(MacroKind::Derive) => ItemType::ProcDerive,
DefKind::ForeignTy => Self::ForeignType,
DefKind::Variant => Self::Variant,
DefKind::Field => Self::StructField,
DefKind::AssocTy => Self::AssocType,
DefKind::AssocFn => {
if let Some(DefKind::Trait) = parent_kind {
Self::TyMethod
} else {
Self::Method
}
}
DefKind::AssocFn if let Some(DefKind::Trait) = parent_kind => Self::TyMethod,
DefKind::AssocFn => Self::Method,
DefKind::Ctor(CtorOf::Struct, _) => Self::Struct,
DefKind::Ctor(CtorOf::Variant, _) => Self::Variant,
DefKind::AssocConst => Self::AssocConst,
@ -170,7 +163,7 @@ impl ItemType {
}
pub(crate) fn as_str(&self) -> &'static str {
match *self {
match self {
ItemType::Module => "mod",
ItemType::ExternCrate => "externcrate",
ItemType::Import => "import",
@ -199,10 +192,10 @@ impl ItemType {
}
}
pub(crate) fn is_method(&self) -> bool {
matches!(*self, ItemType::Method | ItemType::TyMethod)
matches!(self, ItemType::Method | ItemType::TyMethod)
}
pub(crate) fn is_adt(&self) -> bool {
matches!(*self, ItemType::Struct | ItemType::Union | ItemType::Enum)
matches!(self, ItemType::Struct | ItemType::Union | ItemType::Enum)
}
}

View file

@ -856,15 +856,15 @@ fn fmt_type(
) -> fmt::Result {
trace!("fmt_type(t = {t:?})");
match *t {
match t {
clean::Generic(name) => f.write_str(name.as_str()),
clean::SelfTy => f.write_str("Self"),
clean::Type::Path { ref path } => {
clean::Type::Path { path } => {
// Paths like `T::Output` and `Self::Output` should be rendered with all segments.
let did = path.def_id();
resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)
}
clean::DynTrait(ref bounds, ref lt) => {
clean::DynTrait(bounds, lt) => {
f.write_str("dyn ")?;
tybounds(bounds, lt, cx).fmt(f)
}
@ -872,8 +872,8 @@ fn fmt_type(
clean::Primitive(clean::PrimitiveType::Never) => {
primitive_link(f, PrimitiveType::Never, format_args!("!"), cx)
}
clean::Primitive(prim) => primitive_link(f, prim, format_args!("{}", prim.as_sym()), cx),
clean::BareFunction(ref decl) => {
&clean::Primitive(prim) => primitive_link(f, prim, format_args!("{}", prim.as_sym()), cx),
clean::BareFunction(decl) => {
print_higher_ranked_params_with_space(&decl.generic_params, cx, "for").fmt(f)?;
decl.safety.print_with_space().fmt(f)?;
print_abi_with_space(decl.abi).fmt(f)?;
@ -884,11 +884,11 @@ fn fmt_type(
}
decl.decl.print(cx).fmt(f)
}
clean::UnsafeBinder(ref binder) => {
clean::UnsafeBinder(binder) => {
print_higher_ranked_params_with_space(&binder.generic_params, cx, "unsafe").fmt(f)?;
binder.ty.print(cx).fmt(f)
}
clean::Tuple(ref typs) => match &typs[..] {
clean::Tuple(typs) => match &typs[..] {
&[] => primitive_link(f, PrimitiveType::Unit, format_args!("()"), cx),
[one] => {
if let clean::Generic(name) = one {
@ -925,45 +925,36 @@ fn fmt_type(
}
}
},
clean::Slice(ref t) => match **t {
clean::Generic(name) => {
primitive_link(f, PrimitiveType::Slice, format_args!("[{name}]"), cx)
}
_ => {
write!(f, "[")?;
t.print(cx).fmt(f)?;
write!(f, "]")
}
},
clean::Type::Pat(ref t, ref pat) => {
clean::Slice(box clean::Generic(name)) => {
primitive_link(f, PrimitiveType::Slice, format_args!("[{name}]"), cx)
}
clean::Slice(t) => {
write!(f, "[")?;
t.print(cx).fmt(f)?;
write!(f, "]")
}
clean::Type::Pat(t, pat) => {
fmt::Display::fmt(&t.print(cx), f)?;
write!(f, " is {pat}")
}
clean::Array(ref t, ref n) => match **t {
clean::Generic(name) if !f.alternate() => primitive_link(
f,
PrimitiveType::Array,
format_args!("[{name}; {n}]", n = Escape(n)),
cx,
),
_ => {
write!(f, "[")?;
t.print(cx).fmt(f)?;
if f.alternate() {
write!(f, "; {n}")?;
} else {
write!(f, "; ")?;
primitive_link(
f,
PrimitiveType::Array,
format_args!("{n}", n = Escape(n)),
cx,
)?;
}
write!(f, "]")
clean::Array(box clean::Generic(name), n) if !f.alternate() => primitive_link(
f,
PrimitiveType::Array,
format_args!("[{name}; {n}]", n = Escape(n)),
cx,
),
clean::Array(t, n) => {
write!(f, "[")?;
t.print(cx).fmt(f)?;
if f.alternate() {
write!(f, "; {n}")?;
} else {
write!(f, "; ")?;
primitive_link(f, PrimitiveType::Array, format_args!("{n}", n = Escape(n)), cx)?;
}
},
clean::RawPointer(m, ref t) => {
write!(f, "]")
}
clean::RawPointer(m, t) => {
let m = match m {
hir::Mutability::Mut => "mut",
hir::Mutability::Not => "const",
@ -991,7 +982,7 @@ fn fmt_type(
t.print(cx).fmt(f)
}
}
clean::BorrowedRef { lifetime: ref l, mutability, type_: ref ty } => {
clean::BorrowedRef { lifetime: l, mutability, type_: ty } => {
let lt = fmt::from_fn(|f| match l {
Some(l) => write!(f, "{} ", l.print()),
_ => Ok(()),
@ -1028,11 +1019,11 @@ fn fmt_type(
}
Ok(())
}
clean::ImplTrait(ref bounds) => {
clean::ImplTrait(bounds) => {
f.write_str("impl ")?;
print_generic_bounds(bounds, cx).fmt(f)
}
clean::QPath(box clean::QPathData {
&clean::QPath(box clean::QPathData {
ref assoc,
ref self_type,
ref trait_,