Skip to content

Commit 84ad2be

Browse files
committed
Merge branch 'pr-462'
Conflicts: README.md
2 parents d4cf288 + a36707b commit 84ad2be

File tree

4 files changed

+89
-5
lines changed

4 files changed

+89
-5
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ A collection of lints to catch common mistakes and improve your Rust code.
66
[Jump to usage instructions](#usage)
77

88
##Lints
9-
There are 76 lints included in this crate:
9+
There are 77 lints included in this crate:
1010

1111
name | default | meaning
1212
---------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -52,6 +52,7 @@ name
5252
[no_effect](https://github.com/Manishearth/rust-clippy/wiki#no_effect) | warn | statements with no effect
5353
[non_ascii_literal](https://github.com/Manishearth/rust-clippy/wiki#non_ascii_literal) | allow | using any literal non-ASCII chars in a string literal; suggests using the \\u escape instead
5454
[nonsensical_open_options](https://github.com/Manishearth/rust-clippy/wiki#nonsensical_open_options) | warn | nonsensical combination of options for opening a file
55+
[ok_expect](https://github.com/Manishearth/rust-clippy/wiki#ok_expect) | warn | using `ok().expect()`, which gives worse error messages than calling `expect` directly on the Result
5556
[option_unwrap_used](https://github.com/Manishearth/rust-clippy/wiki#option_unwrap_used) | allow | using `Option.unwrap()`, which should at least get a better message using `expect()`
5657
[precedence](https://github.com/Manishearth/rust-clippy/wiki#precedence) | warn | catches operations where precedence may be unclear. See the wiki for a list of cases caught
5758
[ptr_arg](https://github.com/Manishearth/rust-clippy/wiki#ptr_arg) | warn | fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ pub fn plugin_registrar(reg: &mut Registry) {
155155
matches::MATCH_BOOL,
156156
matches::MATCH_REF_PATS,
157157
matches::SINGLE_MATCH,
158+
methods::OK_EXPECT,
158159
methods::SHOULD_IMPLEMENT_TRAIT,
159160
methods::STR_TO_STRING,
160161
methods::STRING_TO_STRING,

src/methods.rs

Lines changed: 61 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
use rustc_front::hir::*;
22
use rustc::lint::*;
33
use rustc::middle::ty;
4-
use rustc::middle::subst::Subst;
4+
use rustc::middle::subst::{Subst, TypeSpace};
55
use std::iter;
66
use std::borrow::Cow;
77

8-
use utils::{snippet, span_lint, match_path, match_type, walk_ptrs_ty_depth};
8+
use utils::{snippet, span_lint, match_path, match_type, walk_ptrs_ty_depth,
9+
walk_ptrs_ty};
910
use utils::{OPTION_PATH, RESULT_PATH, STRING_PATH};
1011

1112
use self::SelfKind::*;
1213
use self::OutType::*;
1314

14-
#[derive(Copy,Clone)]
15+
#[derive(Clone)]
1516
pub struct MethodsPass;
1617

1718
declare_lint!(pub OPTION_UNWRAP_USED, Allow,
@@ -30,16 +31,21 @@ declare_lint!(pub WRONG_SELF_CONVENTION, Warn,
3031
declare_lint!(pub WRONG_PUB_SELF_CONVENTION, Allow,
3132
"defining a public method named with an established prefix (like \"into_\") that takes \
3233
`self` with the wrong convention");
34+
declare_lint!(pub OK_EXPECT, Warn,
35+
"using `ok().expect()`, which gives worse error messages than \
36+
calling `expect` directly on the Result");
37+
3338

3439
impl LintPass for MethodsPass {
3540
fn get_lints(&self) -> LintArray {
3641
lint_array!(OPTION_UNWRAP_USED, RESULT_UNWRAP_USED, STR_TO_STRING, STRING_TO_STRING,
37-
SHOULD_IMPLEMENT_TRAIT, WRONG_SELF_CONVENTION)
42+
SHOULD_IMPLEMENT_TRAIT, WRONG_SELF_CONVENTION, OK_EXPECT)
3843
}
3944
}
4045

4146
impl LateLintPass for MethodsPass {
4247
fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
48+
4349
if let ExprMethodCall(ref name, _, ref args) = expr.node {
4450
let (obj_ty, ptr_depth) = walk_ptrs_ty_depth(cx.tcx.expr_ty(&args[0]));
4551
if name.node.as_str() == "unwrap" {
@@ -70,6 +76,22 @@ impl LateLintPass for MethodsPass {
7076
`clone()` to make a copy");
7177
}
7278
}
79+
else if name.node.as_str() == "expect" {
80+
if let ExprMethodCall(ref inner_name, _, ref inner_args) = args[0].node {
81+
if inner_name.node.as_str() == "ok"
82+
&& match_type(cx, cx.tcx.expr_ty(&inner_args[0]), &RESULT_PATH) {
83+
let result_type = cx.tcx.expr_ty(&inner_args[0]);
84+
if let Some(error_type) = get_error_type(cx, result_type) {
85+
if has_debug_impl(error_type, cx) {
86+
span_lint(cx, OK_EXPECT, expr.span,
87+
"called `ok().expect()` on a Result \
88+
value. You can call `expect` directly
89+
on the `Result`");
90+
}
91+
}
92+
}
93+
}
94+
}
7395
}
7496
}
7597

@@ -115,6 +137,41 @@ impl LateLintPass for MethodsPass {
115137
}
116138
}
117139

140+
// Given a `Result<T, E>` type, return its error type (`E`)
141+
fn get_error_type<'a>(cx: &LateContext, ty: ty::Ty<'a>) -> Option<ty::Ty<'a>> {
142+
if !match_type(cx, ty, &RESULT_PATH) {
143+
return None;
144+
}
145+
if let ty::TyEnum(_, substs) = ty.sty {
146+
if let Some(err_ty) = substs.types.opt_get(TypeSpace, 1) {
147+
return Some(err_ty);
148+
}
149+
}
150+
None
151+
}
152+
153+
// This checks whether a given type is known to implement Debug. It's
154+
// conservative, i.e. it should not return false positives, but will return
155+
// false negatives.
156+
fn has_debug_impl<'a, 'b>(ty: ty::Ty<'a>, cx: &LateContext<'b, 'a>) -> bool {
157+
let no_ref_ty = walk_ptrs_ty(ty);
158+
let debug = match cx.tcx.lang_items.debug_trait() {
159+
Some(debug) => debug,
160+
None => return false
161+
};
162+
let debug_def = cx.tcx.lookup_trait_def(debug);
163+
let mut debug_impl_exists = false;
164+
debug_def.for_each_relevant_impl(cx.tcx, no_ref_ty, |d| {
165+
let self_ty = &cx.tcx.impl_trait_ref(d).and_then(|im| im.substs.self_ty());
166+
if let Some(self_ty) = *self_ty {
167+
if !self_ty.flags.get().contains(ty::TypeFlags::HAS_PARAMS) {
168+
debug_impl_exists = true;
169+
}
170+
}
171+
});
172+
debug_impl_exists
173+
}
174+
118175
const CONVENTIONS: [(&'static str, &'static [SelfKind]); 5] = [
119176
("into_", &[ValueSelf]),
120177
("to_", &[RefSelf]),

tests/compile-fail/methods.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ impl Mul<T> for T {
3535
}
3636

3737
fn main() {
38+
use std::io;
39+
3840
let opt = Some(0);
3941
let _ = opt.unwrap(); //~ERROR used unwrap() on an Option
4042

@@ -46,4 +48,27 @@ fn main() {
4648
let v = &"str";
4749
let string = v.to_string(); //~ERROR `(*v).to_owned()` is faster
4850
let _again = string.to_string(); //~ERROR `String.to_string()` is a no-op
51+
52+
res.ok().expect("disaster!"); //~ERROR called `ok().expect()`
53+
// the following should not warn, since `expect` isn't implemented unless
54+
// the error type implements `Debug`
55+
let res2: Result<i32, MyError> = Ok(0);
56+
res2.ok().expect("oh noes!");
57+
// we currently don't warn if the error type has a type parameter
58+
// (but it would be nice if we did)
59+
let res3: Result<u32, MyErrorWithParam<u8>>= Ok(0);
60+
res3.ok().expect("whoof");
61+
let res4: Result<u32, io::Error> = Ok(0);
62+
res4.ok().expect("argh"); //~ERROR called `ok().expect()`
63+
let res5: io::Result<u32> = Ok(0);
64+
res5.ok().expect("oops"); //~ERROR called `ok().expect()`
65+
let res6: Result<u32, &str> = Ok(0);
66+
res6.ok().expect("meh"); //~ERROR called `ok().expect()`
67+
}
68+
69+
struct MyError(()); // doesn't implement Debug
70+
71+
#[derive(Debug)]
72+
struct MyErrorWithParam<T> {
73+
x: T
4974
}

0 commit comments

Comments
 (0)