Skip to content

Commit 02ed23c

Browse files
committed
Use an exhaustive match in Node::ident() and add docs
This should cause a compiler error in the future if more variants are added without `Node::ident()` being updated.
1 parent 0fa3b4f commit 02ed23c

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

compiler/rustc_hir/src/hir.rs

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3182,6 +3182,20 @@ pub enum Node<'hir> {
31823182
}
31833183

31843184
impl<'hir> Node<'hir> {
3185+
/// Get the identifier of this `Node`, if applicable.
3186+
///
3187+
/// # Edge cases
3188+
///
3189+
/// Calling `.ident()` on a [`Node::Ctor`] will return `None`
3190+
/// because `Ctor`s do not have identifiers themselves.
3191+
/// Instead, call `.ident()` on the parent struct/variant, like so:
3192+
///
3193+
/// ```ignore (illustrative)
3194+
/// ctor
3195+
/// .ctor_hir_id()
3196+
/// .and_then(|ctor_id| tcx.hir().find(tcx.hir().get_parent_node(ctor_id)))
3197+
/// .and_then(|parent| parent.ident())
3198+
/// ```
31853199
pub fn ident(&self) -> Option<Ident> {
31863200
match self {
31873201
Node::TraitItem(TraitItem { ident, .. })
@@ -3190,8 +3204,25 @@ impl<'hir> Node<'hir> {
31903204
| Node::Field(FieldDef { ident, .. })
31913205
| Node::Variant(Variant { ident, .. })
31923206
| Node::MacroDef(MacroDef { ident, .. })
3193-
| Node::Item(Item { ident, .. }) => Some(*ident),
3194-
_ => None,
3207+
| Node::Item(Item { ident, .. })
3208+
| Node::PathSegment(PathSegment { ident, .. }) => Some(*ident),
3209+
Node::Lifetime(lt) => Some(lt.name.ident()),
3210+
Node::GenericParam(p) => Some(p.name.ident()),
3211+
Node::Param(..)
3212+
| Node::AnonConst(..)
3213+
| Node::Expr(..)
3214+
| Node::Stmt(..)
3215+
| Node::Block(..)
3216+
| Node::Ctor(..)
3217+
| Node::Pat(..)
3218+
| Node::Binding(..)
3219+
| Node::Arm(..)
3220+
| Node::Local(..)
3221+
| Node::Visibility(..)
3222+
| Node::Crate(..)
3223+
| Node::Ty(..)
3224+
| Node::TraitRef(..)
3225+
| Node::Infer(..) => None,
31953226
}
31963227
}
31973228

0 commit comments

Comments
 (0)