Skip to content

Commit e2b22b5

Browse files
committed
Use pattern matching instead of checking lengths explicitly
This piece of code checks that there are exaclty two variants, one having exactly one field, the other having exactly zero fields. If any of these conditions is violated, it returns `None`. Otherwise it assigns that one field's ty to `field_ty`. Instead of fiddling with indices and length checks explicitly, use pattern matching to simplify this.
1 parent 1160cf8 commit e2b22b5

File tree

1 file changed

+7
-19
lines changed

1 file changed

+7
-19
lines changed

compiler/rustc_lint/src/types.rs

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,14 @@ use rustc_data_structures::fx::FxHashSet;
55
use rustc_errors::Applicability;
66
use rustc_hir as hir;
77
use rustc_hir::{is_range_literal, ExprKind, Node};
8-
use rustc_index::vec::Idx;
98
use rustc_middle::ty::layout::{IntegerExt, SizeSkeleton};
109
use rustc_middle::ty::subst::SubstsRef;
1110
use rustc_middle::ty::{self, AdtKind, Ty, TyCtxt, TypeFoldable};
1211
use rustc_span::source_map;
1312
use rustc_span::symbol::sym;
1413
use rustc_span::{Span, DUMMY_SP};
1514
use rustc_target::abi::Abi;
16-
use rustc_target::abi::{Integer, LayoutOf, TagEncoding, VariantIdx, Variants};
15+
use rustc_target::abi::{Integer, LayoutOf, TagEncoding, Variants};
1716
use rustc_target::spec::abi::Abi as SpecAbi;
1817

1918
use std::cmp;
@@ -783,25 +782,14 @@ crate fn repr_nullable_ptr<'tcx>(
783782
) -> Option<Ty<'tcx>> {
784783
debug!("is_repr_nullable_ptr(cx, ty = {:?})", ty);
785784
if let ty::Adt(ty_def, substs) = ty.kind() {
786-
if ty_def.variants.len() != 2 {
787-
return None;
788-
}
789-
790-
let get_variant_fields = |index| &ty_def.variants[VariantIdx::new(index)].fields;
791-
let variant_fields = [get_variant_fields(0), get_variant_fields(1)];
792-
let fields = if variant_fields[0].is_empty() {
793-
&variant_fields[1]
794-
} else if variant_fields[1].is_empty() {
795-
&variant_fields[0]
796-
} else {
797-
return None;
785+
let field_ty = match &ty_def.variants.raw[..] {
786+
[var_one, var_two] => match (&var_one.fields[..], &var_two.fields[..]) {
787+
([], [field]) | ([field], []) => field.ty(cx.tcx, substs),
788+
_ => return None,
789+
},
790+
_ => return None,
798791
};
799792

800-
if fields.len() != 1 {
801-
return None;
802-
}
803-
804-
let field_ty = fields[0].ty(cx.tcx, substs);
805793
if !ty_is_known_nonnull(cx, field_ty, ckind) {
806794
return None;
807795
}

0 commit comments

Comments
 (0)