]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/demand.rs
Auto merge of #55095 - Manishearth:rollup, r=Manishearth
[rust.git] / src / librustc_typeck / check / demand.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use check::FnCtxt;
12 use rustc::infer::InferOk;
13 use rustc::traits::ObligationCause;
14
15 use syntax::ast;
16 use syntax::util::parser::PREC_POSTFIX;
17 use syntax_pos::Span;
18 use rustc::hir;
19 use rustc::hir::def::Def;
20 use rustc::hir::Node;
21 use rustc::hir::{Item, ItemKind, print};
22 use rustc::ty::{self, Ty, AssociatedItem};
23 use rustc::ty::adjustment::AllowTwoPhase;
24 use errors::{Applicability, DiagnosticBuilder, SourceMapper};
25
26 use super::method::probe;
27
28 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
29     // Requires that the two types unify, and prints an error message if
30     // they don't.
31     pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
32         self.demand_suptype_diag(sp, expected, actual).map(|mut e| e.emit());
33     }
34
35     pub fn demand_suptype_diag(&self,
36                                sp: Span,
37                                expected: Ty<'tcx>,
38                                actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
39         let cause = &self.misc(sp);
40         match self.at(cause, self.param_env).sup(expected, actual) {
41             Ok(InferOk { obligations, value: () }) => {
42                 self.register_predicates(obligations);
43                 None
44             },
45             Err(e) => {
46                 Some(self.report_mismatched_types(&cause, expected, actual, e))
47             }
48         }
49     }
50
51     pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) {
52         if let Some(mut err) = self.demand_eqtype_diag(sp, expected, actual) {
53             err.emit();
54         }
55     }
56
57     pub fn demand_eqtype_diag(&self,
58                              sp: Span,
59                              expected: Ty<'tcx>,
60                              actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
61         self.demand_eqtype_with_origin(&self.misc(sp), expected, actual)
62     }
63
64     pub fn demand_eqtype_with_origin(&self,
65                                      cause: &ObligationCause<'tcx>,
66                                      expected: Ty<'tcx>,
67                                      actual: Ty<'tcx>) -> Option<DiagnosticBuilder<'tcx>> {
68         match self.at(cause, self.param_env).eq(expected, actual) {
69             Ok(InferOk { obligations, value: () }) => {
70                 self.register_predicates(obligations);
71                 None
72             }
73             Err(e) => {
74                 Some(self.report_mismatched_types(cause, expected, actual, e))
75             }
76         }
77     }
78
79     pub fn demand_coerce(&self,
80                          expr: &hir::Expr,
81                          checked_ty: Ty<'tcx>,
82                          expected: Ty<'tcx>,
83                          allow_two_phase: AllowTwoPhase)
84                          -> Ty<'tcx> {
85         let (ty, err) = self.demand_coerce_diag(expr, checked_ty, expected, allow_two_phase);
86         if let Some(mut err) = err {
87             err.emit();
88         }
89         ty
90     }
91
92     // Checks that the type of `expr` can be coerced to `expected`.
93     //
94     // NB: This code relies on `self.diverges` to be accurate. In
95     // particular, assignments to `!` will be permitted if the
96     // diverges flag is currently "always".
97     pub fn demand_coerce_diag(&self,
98                               expr: &hir::Expr,
99                               checked_ty: Ty<'tcx>,
100                               expected: Ty<'tcx>,
101                               allow_two_phase: AllowTwoPhase)
102                               -> (Ty<'tcx>, Option<DiagnosticBuilder<'tcx>>) {
103         let expected = self.resolve_type_vars_with_obligations(expected);
104
105         let e = match self.try_coerce(expr, checked_ty, expected, allow_two_phase) {
106             Ok(ty) => return (ty, None),
107             Err(e) => e
108         };
109
110         let cause = self.misc(expr.span);
111         let expr_ty = self.resolve_type_vars_with_obligations(checked_ty);
112         let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
113
114         // If the expected type is an enum with any variants whose sole
115         // field is of the found type, suggest such variants. See Issue
116         // #42764.
117         if let ty::Adt(expected_adt, substs) = expected.sty {
118             let mut compatible_variants = expected_adt.variants
119                                                   .iter()
120                                                   .filter(|variant| variant.fields.len() == 1)
121                                                   .filter_map(|variant| {
122                 let sole_field = &variant.fields[0];
123                 let sole_field_ty = sole_field.ty(self.tcx, substs);
124                 if self.can_coerce(expr_ty, sole_field_ty) {
125                     let variant_path = self.tcx.item_path_str(variant.did);
126                     Some(variant_path.trim_left_matches("std::prelude::v1::").to_string())
127                 } else {
128                     None
129                 }
130             }).peekable();
131
132             if compatible_variants.peek().is_some() {
133                 let expr_text = print::to_string(print::NO_ANN, |s| s.print_expr(expr));
134                 let suggestions = compatible_variants.map(|v|
135                     format!("{}({})", v, expr_text)).collect::<Vec<_>>();
136                 err.span_suggestions_with_applicability(
137                      expr.span,
138                      "try using a variant of the expected type",
139                      suggestions,
140                      Applicability::MaybeIncorrect,
141                 );
142             }
143         }
144
145         self.suggest_ref_or_into(&mut err, expr, expected, expr_ty);
146
147         (expected, Some(err))
148     }
149
150     pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>)
151                               -> Vec<AssociatedItem> {
152         let mut methods = self.probe_for_return_type(span,
153                                                      probe::Mode::MethodCall,
154                                                      expected,
155                                                      checked_ty,
156                                                      ast::DUMMY_NODE_ID);
157         methods.retain(|m| {
158             self.has_no_input_arg(m) &&
159                 self.tcx.get_attrs(m.def_id).iter()
160                 // This special internal attribute is used to whitelist
161                 // "identity-like" conversion methods to be suggested here.
162                 //
163                 // FIXME (#46459 and #46460): ideally
164                 // `std::convert::Into::into` and `std::borrow:ToOwned` would
165                 // also be `#[rustc_conversion_suggestion]`, if not for
166                 // method-probing false-positives and -negatives (respectively).
167                 //
168                 // FIXME? Other potential candidate methods: `as_ref` and
169                 // `as_mut`?
170                 .find(|a| a.check_name("rustc_conversion_suggestion")).is_some()
171         });
172
173         methods
174     }
175
176     // This function checks if the method isn't static and takes other arguments than `self`.
177     fn has_no_input_arg(&self, method: &AssociatedItem) -> bool {
178         match method.def() {
179             Def::Method(def_id) => {
180                 self.tcx.fn_sig(def_id).inputs().skip_binder().len() == 1
181             }
182             _ => false,
183         }
184     }
185
186     /// Identify some cases where `as_ref()` would be appropriate and suggest it.
187     ///
188     /// Given the following code:
189     /// ```
190     /// struct Foo;
191     /// fn takes_ref(_: &Foo) {}
192     /// let ref opt = Some(Foo);
193     ///
194     /// opt.map(|arg| takes_ref(arg));
195     /// ```
196     /// Suggest using `opt.as_ref().map(|arg| takes_ref(arg));` instead.
197     ///
198     /// It only checks for `Option` and `Result` and won't work with
199     /// ```
200     /// opt.map(|arg| { takes_ref(arg) });
201     /// ```
202     fn can_use_as_ref(&self, expr: &hir::Expr) -> Option<(Span, &'static str, String)> {
203         if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = expr.node {
204             if let hir::def::Def::Local(id) = path.def {
205                 let parent = self.tcx.hir.get_parent_node(id);
206                 if let Some(Node::Expr(hir::Expr {
207                     id,
208                     node: hir::ExprKind::Closure(_, decl, ..),
209                     ..
210                 })) = self.tcx.hir.find(parent) {
211                     let parent = self.tcx.hir.get_parent_node(*id);
212                     if let (Some(Node::Expr(hir::Expr {
213                         node: hir::ExprKind::MethodCall(path, span, expr),
214                         ..
215                     })), 1) = (self.tcx.hir.find(parent), decl.inputs.len()) {
216                         let self_ty = self.tables.borrow().node_id_to_type(expr[0].hir_id);
217                         let self_ty = format!("{:?}", self_ty);
218                         let name = path.ident.as_str();
219                         let is_as_ref_able = (
220                             self_ty.starts_with("&std::option::Option") ||
221                             self_ty.starts_with("&std::result::Result") ||
222                             self_ty.starts_with("std::option::Option") ||
223                             self_ty.starts_with("std::result::Result")
224                         ) && (name == "map" || name == "and_then");
225                         if is_as_ref_able {
226                             return Some((span.shrink_to_lo(),
227                                          "consider using `as_ref` instead",
228                                          "as_ref().".into()));
229                         }
230                     }
231                 }
232             }
233         }
234         None
235     }
236
237     /// This function is used to determine potential "simple" improvements or users' errors and
238     /// provide them useful help. For example:
239     ///
240     /// ```
241     /// fn some_fn(s: &str) {}
242     ///
243     /// let x = "hey!".to_owned();
244     /// some_fn(x); // error
245     /// ```
246     ///
247     /// No need to find every potential function which could make a coercion to transform a
248     /// `String` into a `&str` since a `&` would do the trick!
249     ///
250     /// In addition of this check, it also checks between references mutability state. If the
251     /// expected is mutable but the provided isn't, maybe we could just say "Hey, try with
252     /// `&mut`!".
253     pub fn check_ref(&self,
254                  expr: &hir::Expr,
255                  checked_ty: Ty<'tcx>,
256                  expected: Ty<'tcx>)
257                  -> Option<(Span, &'static str, String)> {
258         let cm = self.sess().source_map();
259         // Use the callsite's span if this is a macro call. #41858
260         let sp = cm.call_span_if_macro(expr.span);
261         if !cm.span_to_filename(sp).is_real() {
262             return None;
263         }
264
265         match (&expected.sty, &checked_ty.sty) {
266             (&ty::Ref(_, exp, _), &ty::Ref(_, check, _)) => match (&exp.sty, &check.sty) {
267                 (&ty::Str, &ty::Array(arr, _)) |
268                 (&ty::Str, &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
269                     if let hir::ExprKind::Lit(_) = expr.node {
270                         if let Ok(src) = cm.span_to_snippet(sp) {
271                             if src.starts_with("b\"") {
272                                 return Some((sp,
273                                              "consider removing the leading `b`",
274                                              src[1..].to_string()));
275                             }
276                         }
277                     }
278                 },
279                 (&ty::Array(arr, _), &ty::Str) |
280                 (&ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
281                     if let hir::ExprKind::Lit(_) = expr.node {
282                         if let Ok(src) = cm.span_to_snippet(sp) {
283                             if src.starts_with("\"") {
284                                 return Some((sp,
285                                              "consider adding a leading `b`",
286                                              format!("b{}", src)));
287                             }
288                         }
289                     }
290                 }
291                 _ => {}
292             },
293             (&ty::Ref(_, _, mutability), _) => {
294                 // Check if it can work when put into a ref. For example:
295                 //
296                 // ```
297                 // fn bar(x: &mut i32) {}
298                 //
299                 // let x = 0u32;
300                 // bar(&x); // error, expected &mut
301                 // ```
302                 let ref_ty = match mutability {
303                     hir::Mutability::MutMutable => self.tcx.mk_mut_ref(
304                                                        self.tcx.mk_region(ty::ReStatic),
305                                                        checked_ty),
306                     hir::Mutability::MutImmutable => self.tcx.mk_imm_ref(
307                                                        self.tcx.mk_region(ty::ReStatic),
308                                                        checked_ty),
309                 };
310                 if self.can_coerce(ref_ty, expected) {
311                     if let Ok(src) = cm.span_to_snippet(sp) {
312                         let needs_parens = match expr.node {
313                             // parenthesize if needed (Issue #46756)
314                             hir::ExprKind::Cast(_, _) |
315                             hir::ExprKind::Binary(_, _, _) => true,
316                             // parenthesize borrows of range literals (Issue #54505)
317                             _ if self.is_range_literal(expr) => true,
318                             _ => false,
319                         };
320                         let sugg_expr = if needs_parens {
321                             format!("({})", src)
322                         } else {
323                             src
324                         };
325
326                         if let Some(sugg) = self.can_use_as_ref(expr) {
327                             return Some(sugg);
328                         }
329                         return Some(match mutability {
330                             hir::Mutability::MutMutable => {
331                                 (sp, "consider mutably borrowing here", format!("&mut {}",
332                                                                                 sugg_expr))
333                             }
334                             hir::Mutability::MutImmutable => {
335                                 (sp, "consider borrowing here", format!("&{}", sugg_expr))
336                             }
337                         });
338                     }
339                 }
340             }
341             (_, &ty::Ref(_, checked, _)) => {
342                 // We have `&T`, check if what was expected was `T`. If so,
343                 // we may want to suggest adding a `*`, or removing
344                 // a `&`.
345                 //
346                 // (But, also check check the `expn_info()` to see if this is
347                 // a macro; if so, it's hard to extract the text and make a good
348                 // suggestion, so don't bother.)
349                 if self.infcx.can_sub(self.param_env, checked, &expected).is_ok() &&
350                    sp.ctxt().outer().expn_info().is_none() {
351                     match expr.node {
352                         // Maybe remove `&`?
353                         hir::ExprKind::AddrOf(_, ref expr) => {
354                             if !cm.span_to_filename(expr.span).is_real() {
355                                 return None;
356                             }
357                             if let Ok(code) = cm.span_to_snippet(expr.span) {
358                                 return Some((sp, "consider removing the borrow", code));
359                             }
360                         }
361
362                         // Maybe add `*`? Only if `T: Copy`.
363                         _ => {
364                             if !self.infcx.type_moves_by_default(self.param_env,
365                                                                 checked,
366                                                                 sp) {
367                                 // do not suggest if the span comes from a macro (#52783)
368                                 if let (Ok(code),
369                                         true) = (cm.span_to_snippet(sp), sp == expr.span) {
370                                     return Some((
371                                         sp,
372                                         "consider dereferencing the borrow",
373                                         format!("*{}", code),
374                                     ));
375                                 }
376                             }
377                         }
378                     }
379                 }
380             }
381             _ => {}
382         }
383         None
384     }
385
386     /// This function checks if the specified expression is a built-in range literal.
387     /// (See: `LoweringContext::lower_expr()` in `src/librustc/hir/lowering.rs`).
388     fn is_range_literal(&self, expr: &hir::Expr) -> bool {
389         use hir::{Path, QPath, ExprKind, TyKind};
390
391         // We support `::std::ops::Range` and `::core::ops::Range` prefixes
392         let is_range_path = |path: &Path| {
393             let mut segs = path.segments.iter()
394                 .map(|seg| seg.ident.as_str());
395
396             if let (Some(root), Some(std_core), Some(ops), Some(range), None) =
397                 (segs.next(), segs.next(), segs.next(), segs.next(), segs.next())
398             {
399                 // "{{root}}" is the equivalent of `::` prefix in Path
400                 root == "{{root}}" && (std_core == "std" || std_core == "core")
401                     && ops == "ops" && range.starts_with("Range")
402             } else {
403                 false
404             }
405         };
406
407         let span_is_range_literal = |span: &Span| {
408             // Check whether a span corresponding to a range expression
409             // is a range literal, rather than an explicit struct or `new()` call.
410             let source_map = self.tcx.sess.source_map();
411             let end_point = source_map.end_point(*span);
412
413             if let Ok(end_string) = source_map.span_to_snippet(end_point) {
414                 !(end_string.ends_with("}") || end_string.ends_with(")"))
415             } else {
416                 false
417             }
418         };
419
420         match expr.node {
421             // All built-in range literals but `..=` and `..` desugar to Structs
422             ExprKind::Struct(QPath::Resolved(None, ref path), _, _) |
423             // `..` desugars to its struct path
424             ExprKind::Path(QPath::Resolved(None, ref path)) => {
425                 return is_range_path(&path) && span_is_range_literal(&expr.span);
426             }
427
428             // `..=` desugars into `::std::ops::RangeInclusive::new(...)`
429             ExprKind::Call(ref func, _) => {
430                 if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
431                     if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
432                         let call_to_new = segment.ident.as_str() == "new";
433
434                         return is_range_path(&path) && span_is_range_literal(&expr.span)
435                             && call_to_new;
436                     }
437                 }
438             }
439
440             _ => {}
441         }
442
443         false
444     }
445
446     pub fn check_for_cast(&self,
447                       err: &mut DiagnosticBuilder<'tcx>,
448                       expr: &hir::Expr,
449                       checked_ty: Ty<'tcx>,
450                       expected_ty: Ty<'tcx>)
451                       -> bool {
452         let parent_id = self.tcx.hir.get_parent_node(expr.id);
453         if let Some(parent) = self.tcx.hir.find(parent_id) {
454             // Shouldn't suggest `.into()` on `const`s.
455             if let Node::Item(Item { node: ItemKind::Const(_, _), .. }) = parent {
456                 // FIXME(estebank): modify once we decide to suggest `as` casts
457                 return false;
458             }
459         };
460
461         let will_truncate = "will truncate the source value";
462         let depending_on_isize = "will truncate or zero-extend depending on the bit width of \
463                                   `isize`";
464         let depending_on_usize = "will truncate or zero-extend depending on the bit width of \
465                                   `usize`";
466         let will_sign_extend = "will sign-extend the source value";
467         let will_zero_extend = "will zero-extend the source value";
468
469         // If casting this expression to a given numeric type would be appropriate in case of a type
470         // mismatch.
471         //
472         // We want to minimize the amount of casting operations that are suggested, as it can be a
473         // lossy operation with potentially bad side effects, so we only suggest when encountering
474         // an expression that indicates that the original type couldn't be directly changed.
475         //
476         // For now, don't suggest casting with `as`.
477         let can_cast = false;
478
479         let needs_paren = expr.precedence().order() < (PREC_POSTFIX as i8);
480
481         if let Ok(src) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
482             let msg = format!("you can cast an `{}` to `{}`", checked_ty, expected_ty);
483             let cast_suggestion = format!("{}{}{} as {}",
484                                           if needs_paren { "(" } else { "" },
485                                           src,
486                                           if needs_paren { ")" } else { "" },
487                                           expected_ty);
488             let into_suggestion = format!(
489                 "{}{}{}.into()",
490                 if needs_paren { "(" } else { "" },
491                 src,
492                 if needs_paren { ")" } else { "" },
493             );
494             let literal_is_ty_suffixed = |expr: &hir::Expr| {
495                 if let hir::ExprKind::Lit(lit) = &expr.node {
496                     lit.node.is_suffixed()
497                 } else {
498                     false
499                 }
500             };
501
502             let into_sugg = into_suggestion.clone();
503             let suggest_to_change_suffix_or_into = |err: &mut DiagnosticBuilder,
504                                                     note: Option<&str>| {
505                 let suggest_msg = if literal_is_ty_suffixed(expr) {
506                     format!(
507                         "change the type of the numeric literal from `{}` to `{}`",
508                         checked_ty,
509                         expected_ty,
510                     )
511                 } else {
512                     match note {
513                         Some(note) => format!("{}, which {}", msg, note),
514                         _ => format!("{} in a lossless way", msg),
515                     }
516                 };
517
518                 let suffix_suggestion = format!(
519                     "{}{}{}{}",
520                     if needs_paren { "(" } else { "" },
521                     src.trim_right_matches(&checked_ty.to_string()),
522                     expected_ty,
523                     if needs_paren { ")" } else { "" },
524                 );
525
526                 err.span_suggestion_with_applicability(
527                     expr.span,
528                     &suggest_msg,
529                     if literal_is_ty_suffixed(expr) {
530                         suffix_suggestion
531                     } else {
532                         into_sugg
533                     },
534                     Applicability::MachineApplicable,
535                 );
536             };
537
538             match (&expected_ty.sty, &checked_ty.sty) {
539                 (&ty::Int(ref exp), &ty::Int(ref found)) => {
540                     match (found.bit_width(), exp.bit_width()) {
541                         (Some(found), Some(exp)) if found > exp => {
542                             if can_cast {
543                                 err.span_suggestion_with_applicability(
544                                     expr.span,
545                                     &format!("{}, which {}", msg, will_truncate),
546                                     cast_suggestion,
547                                     Applicability::MaybeIncorrect // lossy conversion
548                                 );
549                             }
550                         }
551                         (None, _) | (_, None) => {
552                             if can_cast {
553                                 err.span_suggestion_with_applicability(
554                                     expr.span,
555                                     &format!("{}, which {}", msg, depending_on_isize),
556                                     cast_suggestion,
557                                     Applicability::MaybeIncorrect // lossy conversion
558                                 );
559                             }
560                         }
561                         _ => {
562                             suggest_to_change_suffix_or_into(
563                                 err,
564                                 Some(will_sign_extend),
565                             );
566                         }
567                     }
568                     true
569                 }
570                 (&ty::Uint(ref exp), &ty::Uint(ref found)) => {
571                     match (found.bit_width(), exp.bit_width()) {
572                         (Some(found), Some(exp)) if found > exp => {
573                             if can_cast {
574                                 err.span_suggestion_with_applicability(
575                                     expr.span,
576                                     &format!("{}, which {}", msg, will_truncate),
577                                     cast_suggestion,
578                                     Applicability::MaybeIncorrect  // lossy conversion
579                                 );
580                             }
581                         }
582                         (None, _) | (_, None) => {
583                             if can_cast {
584                                 err.span_suggestion_with_applicability(
585                                     expr.span,
586                                     &format!("{}, which {}", msg, depending_on_usize),
587                                     cast_suggestion,
588                                     Applicability::MaybeIncorrect  // lossy conversion
589                                 );
590                             }
591                         }
592                         _ => {
593                            suggest_to_change_suffix_or_into(
594                                err,
595                                Some(will_zero_extend),
596                            );
597                         }
598                     }
599                     true
600                 }
601                 (&ty::Int(ref exp), &ty::Uint(ref found)) => {
602                     if can_cast {
603                         match (found.bit_width(), exp.bit_width()) {
604                             (Some(found), Some(exp)) if found > exp - 1 => {
605                                 err.span_suggestion_with_applicability(
606                                     expr.span,
607                                     &format!("{}, which {}", msg, will_truncate),
608                                     cast_suggestion,
609                                     Applicability::MaybeIncorrect  // lossy conversion
610                                 );
611                             }
612                             (None, None) => {
613                                 err.span_suggestion_with_applicability(
614                                     expr.span,
615                                     &format!("{}, which {}", msg, will_truncate),
616                                     cast_suggestion,
617                                     Applicability::MaybeIncorrect  // lossy conversion
618                                 );
619                             }
620                             (None, _) => {
621                                 err.span_suggestion_with_applicability(
622                                     expr.span,
623                                     &format!("{}, which {}", msg, depending_on_isize),
624                                     cast_suggestion,
625                                     Applicability::MaybeIncorrect  // lossy conversion
626                                 );
627                             }
628                             (_, None) => {
629                                 err.span_suggestion_with_applicability(
630                                     expr.span,
631                                     &format!("{}, which {}", msg, depending_on_usize),
632                                     cast_suggestion,
633                                     Applicability::MaybeIncorrect  // lossy conversion
634                                 );
635                             }
636                             _ => {
637                                 err.span_suggestion_with_applicability(
638                                     expr.span,
639                                     &format!("{}, which {}", msg, will_zero_extend),
640                                     cast_suggestion,
641                                     Applicability::MachineApplicable
642                                 );
643                             }
644                         }
645                     }
646                     true
647                 }
648                 (&ty::Uint(ref exp), &ty::Int(ref found)) => {
649                     if can_cast {
650                         match (found.bit_width(), exp.bit_width()) {
651                             (Some(found), Some(exp)) if found - 1 > exp => {
652                                 err.span_suggestion_with_applicability(
653                                     expr.span,
654                                     &format!("{}, which {}", msg, will_truncate),
655                                     cast_suggestion,
656                                     Applicability::MaybeIncorrect  // lossy conversion
657                                 );
658                             }
659                             (None, None) => {
660                                 err.span_suggestion_with_applicability(
661                                     expr.span,
662                                     &format!("{}, which {}", msg, will_sign_extend),
663                                     cast_suggestion,
664                                     Applicability::MachineApplicable  // lossy conversion
665                                 );
666                             }
667                             (None, _) => {
668                                 err.span_suggestion_with_applicability(
669                                     expr.span,
670                                     &format!("{}, which {}", msg, depending_on_usize),
671                                     cast_suggestion,
672                                     Applicability::MaybeIncorrect  // lossy conversion
673                                 );
674                             }
675                             (_, None) => {
676                                 err.span_suggestion_with_applicability(
677                                     expr.span,
678                                     &format!("{}, which {}", msg, depending_on_isize),
679                                     cast_suggestion,
680                                     Applicability::MaybeIncorrect  // lossy conversion
681                                 );
682                             }
683                             _ => {
684                                 err.span_suggestion_with_applicability(
685                                     expr.span,
686                                     &format!("{}, which {}", msg, will_sign_extend),
687                                     cast_suggestion,
688                                     Applicability::MachineApplicable
689                                 );
690                             }
691                         }
692                     }
693                     true
694                 }
695                 (&ty::Float(ref exp), &ty::Float(ref found)) => {
696                     if found.bit_width() < exp.bit_width() {
697                        suggest_to_change_suffix_or_into(
698                            err,
699                            None,
700                        );
701                     } else if can_cast {
702                         err.span_suggestion_with_applicability(
703                             expr.span,
704                             &format!("{}, producing the closest possible value", msg),
705                             cast_suggestion,
706                             Applicability::MaybeIncorrect  // lossy conversion
707                         );
708                     }
709                     true
710                 }
711                 (&ty::Uint(_), &ty::Float(_)) | (&ty::Int(_), &ty::Float(_)) => {
712                     if can_cast {
713                         err.span_suggestion_with_applicability(
714                             expr.span,
715                             &format!("{}, rounding the float towards zero", msg),
716                             cast_suggestion,
717                             Applicability::MaybeIncorrect  // lossy conversion
718                         );
719                         err.warn("casting here will cause undefined behavior if the rounded value \
720                                   cannot be represented by the target integer type, including \
721                                   `Inf` and `NaN` (this is a bug and will be fixed)");
722                     }
723                     true
724                 }
725                 (&ty::Float(ref exp), &ty::Uint(ref found)) => {
726                     // if `found` is `None` (meaning found is `usize`), don't suggest `.into()`
727                     if exp.bit_width() > found.bit_width().unwrap_or(256) {
728                         err.span_suggestion_with_applicability(
729                             expr.span,
730                             &format!("{}, producing the floating point representation of the \
731                                       integer",
732                                      msg),
733                             into_suggestion,
734                             Applicability::MachineApplicable
735                         );
736                     } else if can_cast {
737                         err.span_suggestion_with_applicability(expr.span,
738                             &format!("{}, producing the floating point representation of the \
739                                       integer, rounded if necessary",
740                                      msg),
741                             cast_suggestion,
742                             Applicability::MaybeIncorrect  // lossy conversion
743                         );
744                     }
745                     true
746                 }
747                 (&ty::Float(ref exp), &ty::Int(ref found)) => {
748                     // if `found` is `None` (meaning found is `isize`), don't suggest `.into()`
749                     if exp.bit_width() > found.bit_width().unwrap_or(256) {
750                         err.span_suggestion_with_applicability(
751                             expr.span,
752                             &format!("{}, producing the floating point representation of the \
753                                       integer",
754                                      msg),
755                             into_suggestion,
756                             Applicability::MachineApplicable
757                         );
758                     } else if can_cast {
759                         err.span_suggestion_with_applicability(
760                             expr.span,
761                             &format!("{}, producing the floating point representation of the \
762                                       integer, rounded if necessary",
763                                      msg),
764                             cast_suggestion,
765                             Applicability::MaybeIncorrect  // lossy conversion
766                         );
767                     }
768                     true
769                 }
770                 _ => false,
771             }
772         } else {
773             false
774         }
775     }
776 }