Skip to content

Commit f69eb8e

Browse files
committed
issue a future-compat lint for constants of invalid type
This is a [breaking-change]: according to RFC rust-lang#1445, constants used as patterns must be of a type that *derives* `Eq`. If you encounter a problem, you are most likely using a constant in an expression where the type of the constant is some struct that does not currently implement `Eq`. Something like the following: ```rust struct SomeType { ... } const SOME_CONST: SomeType = ...; match foo { SOME_CONST => ... } ``` The easiest and most future compatible fix is to annotate the type in question with `#[derive(Eq)]` (note that merely *implementing* `Eq` is not enough, it must be *derived*): ```rust struct SomeType { ... } const SOME_CONST: SomeType = ...; match foo { SOME_CONST => ... } ``` Another good option is to rewrite the match arm to use an `if` condition (this is also particularly good for floating point types, which implement `PartialEq` but not `Eq`): ```rust match foo { c if c == SOME_CONST => ... } ``` Finally, a third alternative is to tag the type with `#[structural_match]`; but this is not recommended, as the attribute is never expected to be stabilized. Please see RFC rust-lang#1445 for more details.
1 parent 05baf64 commit f69eb8e

File tree

5 files changed

+64
-9
lines changed

5 files changed

+64
-9
lines changed

src/librustc/lint/builtin.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,19 @@ declare_lint! {
136136
"type parameter default erroneously allowed in invalid location"
137137
}
138138

139+
declare_lint! {
140+
pub ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
141+
Warn,
142+
"floating-point constants cannot be used in patterns"
143+
}
144+
145+
declare_lint! {
146+
pub ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
147+
Deny,
148+
"constants of struct or enum type can only be used in a pattern if \
149+
the struct or enum has `#[derive(Eq)]`"
150+
}
151+
139152
declare_lint! {
140153
pub MATCH_OF_UNIT_VARIANT_VIA_PAREN_DOTDOT,
141154
Deny,
@@ -193,6 +206,8 @@ impl LintPass for HardwiredLints {
193206
PRIVATE_IN_PUBLIC,
194207
INACCESSIBLE_EXTERN_CRATE,
195208
INVALID_TYPE_PARAM_DEFAULT,
209+
ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
210+
ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
196211
MATCH_OF_UNIT_VARIANT_VIA_PAREN_DOTDOT,
197212
CONST_ERR,
198213
RAW_POINTER_DERIVE,

src/librustc/middle/check_match.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
478478
Some(Def::Const(did)) => {
479479
let substs = Some(self.tcx.node_id_item_substs(pat.id).substs);
480480
if let Some((const_expr, _)) = lookup_const_by_id(self.tcx, did, substs) {
481-
match const_expr_to_pat(self.tcx, const_expr, pat.span) {
481+
match const_expr_to_pat(self.tcx, const_expr, pat.id, pat.span) {
482482
Ok(new_pat) => {
483483
if let Some(ref mut map) = self.renaming_map {
484484
// Record any renamings we do here
@@ -487,7 +487,6 @@ impl<'a, 'tcx> Folder for StaticInliner<'a, 'tcx> {
487487
new_pat
488488
}
489489
Err(def_id) => {
490-
// TODO back-compat
491490
self.failed = true;
492491
self.tcx.sess.span_err(
493492
pat.span,

src/librustc/middle/const_eval.rs

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use self::EvalHint::*;
1616

1717
use front::map as ast_map;
1818
use front::map::blocks::FnLikeNode;
19+
use lint;
1920
use middle::cstore::{self, CrateStore, InlinedItem};
2021
use middle::{infer, subst, traits};
2122
use middle::def::Def;
@@ -323,13 +324,41 @@ impl ConstVal {
323324
}
324325
}
325326

326-
pub fn const_expr_to_pat(tcx: &ty::TyCtxt, expr: &Expr, span: Span)
327+
pub fn const_expr_to_pat(tcx: &ty::TyCtxt, expr: &Expr, pat_id: ast::NodeId, span: Span)
327328
-> Result<P<hir::Pat>, DefId> {
329+
let pat_ty = tcx.expr_ty(expr);
330+
debug!("expr={:?} pat_ty={:?} pat_id={}", expr, pat_ty, pat_id);
331+
match pat_ty.sty {
332+
ty::TyFloat(_) => {
333+
tcx.sess.add_lint(
334+
lint::builtin::ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
335+
pat_id,
336+
span,
337+
format!("floating point constants cannot be used in patterns"));
338+
}
339+
ty::TyEnum(adt_def, _) |
340+
ty::TyStruct(adt_def, _) => {
341+
if !tcx.has_attr(adt_def.did, "structural_match") {
342+
tcx.sess.add_lint(
343+
lint::builtin::ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
344+
pat_id,
345+
span,
346+
format!("to use a constant of type `{}` \
347+
in a pattern, \
348+
`{}` must be annotated with `#[derive(Eq)]`",
349+
tcx.item_path_str(adt_def.did),
350+
tcx.item_path_str(adt_def.did)));
351+
}
352+
}
353+
_ => { }
354+
}
355+
328356
let pat = match expr.node {
329357
hir::ExprTup(ref exprs) =>
330358
PatKind::Tup(try!(exprs.iter()
331-
.map(|expr| const_expr_to_pat(tcx, &expr, span))
332-
.collect())),
359+
.map(|expr| const_expr_to_pat(tcx, &expr,
360+
pat_id, span))
361+
.collect())),
333362

334363
hir::ExprCall(ref callee, ref args) => {
335364
let def = *tcx.def_map.borrow().get(&callee.id).unwrap();
@@ -347,7 +376,8 @@ pub fn const_expr_to_pat(tcx: &ty::TyCtxt, expr: &Expr, span: Span)
347376
_ => unreachable!()
348377
};
349378
let pats = try!(args.iter()
350-
.map(|expr| const_expr_to_pat(tcx, &**expr, span))
379+
.map(|expr| const_expr_to_pat(tcx, &**expr,
380+
pat_id, span))
351381
.collect());
352382
PatKind::TupleStruct(path, Some(pats))
353383
}
@@ -359,7 +389,8 @@ pub fn const_expr_to_pat(tcx: &ty::TyCtxt, expr: &Expr, span: Span)
359389
span: codemap::DUMMY_SP,
360390
node: hir::FieldPat {
361391
name: field.name.node,
362-
pat: try!(const_expr_to_pat(tcx, &field.expr, span)),
392+
pat: try!(const_expr_to_pat(tcx, &field.expr,
393+
pat_id, span)),
363394
is_shorthand: false,
364395
},
365396
}))
@@ -369,7 +400,8 @@ pub fn const_expr_to_pat(tcx: &ty::TyCtxt, expr: &Expr, span: Span)
369400

370401
hir::ExprVec(ref exprs) => {
371402
let pats = try!(exprs.iter()
372-
.map(|expr| const_expr_to_pat(tcx, &expr, span))
403+
.map(|expr| const_expr_to_pat(tcx, &expr,
404+
pat_id, span))
373405
.collect());
374406
PatKind::Vec(pats, None, hir::HirVec::new())
375407
}
@@ -383,7 +415,7 @@ pub fn const_expr_to_pat(tcx: &ty::TyCtxt, expr: &Expr, span: Span)
383415
Some(Def::AssociatedConst(def_id)) => {
384416
let substs = Some(tcx.node_id_item_substs(expr.id).substs);
385417
let (expr, _ty) = lookup_const_by_id(tcx, def_id, substs).unwrap();
386-
return const_expr_to_pat(tcx, expr, span);
418+
return const_expr_to_pat(tcx, expr, pat_id, span);
387419
},
388420
_ => unreachable!(),
389421
}

src/librustc_lint/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,14 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
179179
id: LintId::of(OVERLAPPING_INHERENT_IMPLS),
180180
reference: "issue #22889 <https://github.com/rust-lang/rust/issues/22889>",
181181
},
182+
FutureIncompatibleInfo {
183+
id: LintId::of(ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN),
184+
reference: "RFC 1445 <https://github.com/rust-lang/rfcs/pull/1445>",
185+
},
186+
FutureIncompatibleInfo {
187+
id: LintId::of(ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN),
188+
reference: "RFC 1445 <https://github.com/rust-lang/rfcs/pull/1445>",
189+
},
182190
]);
183191

184192
// We have one lint pass defined specially

src/librustc_mir/hair/cx/pattern.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ impl<'patcx, 'cx, 'tcx> PatCx<'patcx, 'cx, 'tcx> {
9292
Some((const_expr, _const_ty)) => {
9393
match const_eval::const_expr_to_pat(self.cx.tcx,
9494
const_expr,
95+
pat.id,
9596
pat.span) {
9697
Ok(pat) =>
9798
return self.to_pattern(&pat),

0 commit comments

Comments
 (0)