diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index b9f4a8cd165d8..c352b35f9782a 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -444,6 +444,9 @@ language_item_table! { DefaultTrait1, sym::default_trait1, default_trait1_trait, Target::Trait, GenericRequirement::None; ContractCheckEnsures, sym::contract_check_ensures, contract_check_ensures_fn, Target::Fn, GenericRequirement::None; + + // Used to fallback `{float}` to `f32` when `f32: From<{float}>` + From, sym::From, from_trait, Target::Trait, GenericRequirement::Exact(1); } /// The requirement imposed on the generics of a lang item diff --git a/compiler/rustc_hir_typeck/messages.ftl b/compiler/rustc_hir_typeck/messages.ftl index 9e1b70f5767b4..264dc0a3e1451 100644 --- a/compiler/rustc_hir_typeck/messages.ftl +++ b/compiler/rustc_hir_typeck/messages.ftl @@ -92,6 +92,10 @@ hir_typeck_field_multiply_specified_in_initializer = .label = used more than once .previous_use_label = first use of `{$ident}` +hir_typeck_float_literal_f32_fallback = + falling back to `f32` as the trait bound `f32: From` is not satisfied + .suggestion = explicitly specify the type as `f32` + hir_typeck_fn_item_to_variadic_function = can't pass a function item to a variadic function .suggestion = use a function pointer instead .help = a function item is zero-sized and needs to be cast into a function pointer to be used in FFI diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index d1bc54ed73ead..04f60f049d3e4 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -342,7 +342,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match infer { ty::TyVar(_) => self.next_ty_var(DUMMY_SP), ty::IntVar(_) => self.next_int_var(), - ty::FloatVar(_) => self.next_float_var(), + ty::FloatVar(_) => self.next_float_var(DUMMY_SP), ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => { bug!("unexpected fresh ty outside of the trait solver") } diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index dfaa374592bc2..065f959d0133c 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -979,3 +979,11 @@ pub(crate) enum SupertraitItemShadowee { traits: DiagSymbolList, }, } + +#[derive(LintDiagnostic)] +#[diag(hir_typeck_float_literal_f32_fallback)] +pub(crate) struct FloatLiteralF32Fallback { + pub literal: String, + #[suggestion(code = "{literal}_f32", applicability = "machine-applicable")] + pub span: Option, +} diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 759b5d9550c05..7378f2e59c898 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -6,12 +6,15 @@ use rustc_data_structures::graph::iterate::DepthFirstSearch; use rustc_data_structures::graph::vec_graph::VecGraph; use rustc_data_structures::graph::{self}; use rustc_data_structures::unord::{UnordBag, UnordMap, UnordSet}; -use rustc_hir as hir; -use rustc_hir::HirId; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{InferKind, Visitor}; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable}; +use rustc_hir::{self as hir, CRATE_HIR_ID, HirId}; +use rustc_lint::builtin::FLOAT_LITERAL_F32_FALLBACK; +use rustc_middle::ty::{ + self, ClauseKind, FloatVid, PredicatePolarity, TraitPredicate, Ty, TyCtxt, TypeSuperVisitable, + TypeVisitable, +}; use rustc_session::lint; use rustc_span::def_id::LocalDefId; use rustc_span::{DUMMY_SP, Span}; @@ -92,6 +95,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { let diverging_fallback = self .calculate_diverging_fallback(&unresolved_variables, self.diverging_fallback_behavior); + let fallback_to_f32 = self.calculate_fallback_to_f32(&unresolved_variables); // We do fallback in two passes, to try to generate // better error messages. @@ -99,7 +103,8 @@ impl<'tcx> FnCtxt<'_, 'tcx> { let mut fallback_occurred = false; for ty in unresolved_variables { debug!("unsolved_variable = {:?}", ty); - fallback_occurred |= self.fallback_if_possible(ty, &diverging_fallback); + fallback_occurred |= + self.fallback_if_possible(ty, &diverging_fallback, &fallback_to_f32); } fallback_occurred @@ -109,7 +114,8 @@ impl<'tcx> FnCtxt<'_, 'tcx> { // // - Unconstrained ints are replaced with `i32`. // - // - Unconstrained floats are replaced with `f64`. + // - Unconstrained floats are replaced with `f64`, except when there is a trait predicate + // `f32: From<{float}>`, in which case `f32` is used as the fallback instead. // // - Non-numerics may get replaced with `()` or `!`, depending on // how they were categorized by `calculate_diverging_fallback` @@ -124,6 +130,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { &self, ty: Ty<'tcx>, diverging_fallback: &UnordMap, Ty<'tcx>>, + fallback_to_f32: &UnordSet, ) -> bool { // Careful: we do NOT shallow-resolve `ty`. We know that `ty` // is an unsolved variable, and we determine its fallback @@ -146,6 +153,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { let fallback = match ty.kind() { _ if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e), ty::Infer(ty::IntVar(_)) => self.tcx.types.i32, + ty::Infer(ty::FloatVar(vid)) if fallback_to_f32.contains(vid) => self.tcx.types.f32, ty::Infer(ty::FloatVar(_)) => self.tcx.types.f64, _ => match diverging_fallback.get(&ty) { Some(&fallback_ty) => fallback_ty, @@ -160,6 +168,78 @@ impl<'tcx> FnCtxt<'_, 'tcx> { true } + /// Existing code relies on `f32: From` (usually written as `T: Into`) resolving `T` to + /// `f32` when the type of `T` is inferred from an unsuffixed float literal. Using the default + /// fallback of `f64`, this would break when adding `impl From for f32`, as there are now + /// two float type which could be `T`, meaning that the fallback of `f64` would be used and + /// compilation error would occur as `f32` does not implement `From`. To avoid breaking + /// existing code, we instead fallback `T` to `f32` when there is a trait predicate + /// `f32: From`. This means code like the following will continue to compile: + /// + /// ```rust + /// fn foo>(_: T) {} + /// + /// foo(1.0); + /// ``` + fn calculate_fallback_to_f32(&self, unresolved_variables: &[Ty<'tcx>]) -> UnordSet { + let Some(from_trait) = self.tcx.lang_items().from_trait() else { + return UnordSet::new(); + }; + let pending_obligations = self.fulfillment_cx.borrow_mut().pending_obligations(); + debug!("calculate_fallback_to_f32: pending_obligations={:?}", pending_obligations); + let roots: UnordSet = pending_obligations + .into_iter() + .filter_map(|obligation| { + // The predicates we are looking for look like + // `TraitPredicate(>, polarity:Positive)`. + // They will have no bound variables. + obligation.predicate.kind().no_bound_vars() + }) + .filter_map(|predicate| match predicate { + ty::PredicateKind::Clause(ClauseKind::Trait(TraitPredicate { + polarity: PredicatePolarity::Positive, + trait_ref, + })) if trait_ref.def_id == from_trait + && self.shallow_resolve(trait_ref.self_ty()).kind() + == &ty::Float(ty::FloatTy::F32) => + { + self.root_float_vid(trait_ref.args.type_at(1)) + } + _ => None, + }) + .collect(); + debug!("calculate_fallback_to_f32: roots={:?}", roots); + if roots.is_empty() { + // Most functions have no `f32: From<{float}>` predicates, so short-circuit and return + // an empty set when this is the case. + return UnordSet::new(); + } + // Calculate all the unresolved variables that need to fallback to `f32` here. This ensures + // we don't need to find root variables in `fallback_if_possible`: see the comment at the + // top of that function for details. + let fallback_to_f32 = unresolved_variables + .iter() + .flat_map(|ty| ty.float_vid()) + .filter(|vid| roots.contains(&self.root_float_var(*vid))) + .inspect(|vid| { + let span = self.float_var_origin(*vid); + // Show the entire literal in the suggestion to make it clearer. + let literal = self.tcx.sess.source_map().span_to_snippet(span).ok(); + self.tcx.emit_node_span_lint( + FLOAT_LITERAL_F32_FALLBACK, + CRATE_HIR_ID, + span, + errors::FloatLiteralF32Fallback { + span: literal.as_ref().map(|_| span), + literal: literal.unwrap_or_default(), + }, + ); + }) + .collect(); + debug!("calculate_fallback_to_f32: fallback_to_f32={:?}", fallback_to_f32); + fallback_to_f32 + } + /// The "diverging fallback" system is rather complicated. This is /// a result of our need to balance 'do the right thing' with /// backwards compatibility. @@ -565,6 +645,11 @@ impl<'tcx> FnCtxt<'_, 'tcx> { Some(self.root_var(self.shallow_resolve(ty).ty_vid()?)) } + /// If `ty` is an unresolved float type variable, returns its root vid. + fn root_float_vid(&self, ty: Ty<'tcx>) -> Option { + Some(self.root_float_var(self.shallow_resolve(ty).float_vid()?)) + } + /// Given a set of diverging vids and coercions, walk the HIR to gather a /// set of suggestions which can be applied to preserve fallback to unit. fn try_to_suggest_annotations( diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index da0e8e362d663..715767a5f3fc1 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -1669,7 +1669,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Float(_) => Some(ty), _ => None, }); - opt_ty.unwrap_or_else(|| self.next_float_var()) + opt_ty.unwrap_or_else(|| self.next_float_var(lit.span)) } ast::LitKind::Bool(_) => tcx.types.bool, ast::LitKind::CStr(_, _) => Ty::new_imm_ref( diff --git a/compiler/rustc_infer/src/infer/canonical/mod.rs b/compiler/rustc_infer/src/infer/canonical/mod.rs index 3be07dbe208f9..5f479ff5216d0 100644 --- a/compiler/rustc_infer/src/infer/canonical/mod.rs +++ b/compiler/rustc_infer/src/infer/canonical/mod.rs @@ -116,7 +116,7 @@ impl<'tcx> InferCtxt<'tcx> { CanonicalTyVarKind::Int => self.next_int_var(), - CanonicalTyVarKind::Float => self.next_float_var(), + CanonicalTyVarKind::Float => self.next_float_var(span), }; ty.into() } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 529e996ad1e7d..346aa8cc8edb7 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -21,6 +21,7 @@ use rustc_data_structures::unify as ut; use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_index::IndexVec; use rustc_macros::extension; pub use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::bug; @@ -110,6 +111,10 @@ pub struct InferCtxtInner<'tcx> { /// Map from floating variable to the kind of float it represents. float_unification_storage: ut::UnificationTableStorage, + /// Map from floating variable to the origin span it came from. This is only used for the FCW + /// for the fallback to `f32`, so can be removed once the `f32` fallback is removed. + float_origin_span_storage: IndexVec, + /// Tracks the set of region variables and the constraints between them. /// /// This is initially `Some(_)` but when @@ -166,6 +171,7 @@ impl<'tcx> InferCtxtInner<'tcx> { const_unification_storage: Default::default(), int_unification_storage: Default::default(), float_unification_storage: Default::default(), + float_origin_span_storage: Default::default(), region_constraint_storage: Some(Default::default()), region_obligations: vec![], opaque_type_storage: Default::default(), @@ -634,6 +640,13 @@ impl<'tcx> InferCtxt<'tcx> { self.inner.borrow_mut().type_variables().var_origin(vid) } + /// Returns the origin of the float type variable identified by `vid`. + /// + /// No attempt is made to resolve `vid` to its root variable. + pub fn float_var_origin(&self, vid: FloatVid) -> Span { + self.inner.borrow_mut().float_origin_span_storage[vid] + } + /// Returns the origin of the const variable identified by `vid` // FIXME: We should store origins separately from the unification table // so this doesn't need to be optional. @@ -819,9 +832,11 @@ impl<'tcx> InferCtxt<'tcx> { Ty::new_int_var(self.tcx, next_int_var_id) } - pub fn next_float_var(&self) -> Ty<'tcx> { - let next_float_var_id = - self.inner.borrow_mut().float_unification_table().new_key(ty::FloatVarValue::Unknown); + pub fn next_float_var(&self, span: Span) -> Ty<'tcx> { + let mut inner = self.inner.borrow_mut(); + let next_float_var_id = inner.float_unification_table().new_key(ty::FloatVarValue::Unknown); + let span_index = inner.float_origin_span_storage.push(span); + debug_assert_eq!(next_float_var_id, span_index); Ty::new_float_var(self.tcx, next_float_var_id) } @@ -1063,6 +1078,10 @@ impl<'tcx> InferCtxt<'tcx> { self.inner.borrow_mut().type_variables().root_var(var) } + pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid { + self.inner.borrow_mut().float_unification_table().find(var) + } + pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid { self.inner.borrow_mut().const_unification_table().find(var).vid } diff --git a/compiler/rustc_infer/src/infer/snapshot/fudge.rs b/compiler/rustc_infer/src/infer/snapshot/fudge.rs index 39c8c40ea7d8b..b231b1b139802 100644 --- a/compiler/rustc_infer/src/infer/snapshot/fudge.rs +++ b/compiler/rustc_infer/src/infer/snapshot/fudge.rs @@ -5,6 +5,7 @@ use rustc_middle::ty::{ self, ConstVid, FloatVid, IntVid, RegionVid, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, }; +use rustc_span::Span; use rustc_type_ir::TypeVisitableExt; use tracing::instrument; use ut::UnifyKey; @@ -12,7 +13,9 @@ use ut::UnifyKey; use super::VariableLengths; use crate::infer::type_variable::TypeVariableOrigin; use crate::infer::unify_key::{ConstVariableValue, ConstVidKey}; -use crate::infer::{ConstVariableOrigin, InferCtxt, RegionVariableOrigin, UnificationTable}; +use crate::infer::{ + ConstVariableOrigin, InferCtxt, InferCtxtInner, RegionVariableOrigin, UnificationTable, +}; fn vars_since_snapshot<'tcx, T>( table: &UnificationTable<'_, 'tcx, T>, @@ -25,6 +28,14 @@ where T::from_index(snapshot_var_len as u32)..T::from_index(table.len() as u32) } +fn float_vars_since_snapshot( + inner: &mut InferCtxtInner<'_>, + snapshot_var_len: usize, +) -> (Range, Vec) { + let range = vars_since_snapshot(&inner.float_unification_table(), snapshot_var_len); + (range.clone(), range.map(|index| inner.float_origin_span_storage[index]).collect()) +} + fn const_vars_since_snapshot<'tcx>( table: &mut UnificationTable<'_, 'tcx, ConstVidKey<'tcx>>, snapshot_var_len: usize, @@ -129,7 +140,7 @@ struct SnapshotVarData { region_vars: (Range, Vec), type_vars: (Range, Vec), int_vars: Range, - float_vars: Range, + float_vars: (Range, Vec), const_vars: (Range, Vec), } @@ -142,8 +153,7 @@ impl SnapshotVarData { let type_vars = inner.type_variables().vars_since_snapshot(vars_pre_snapshot.type_var_len); let int_vars = vars_since_snapshot(&inner.int_unification_table(), vars_pre_snapshot.int_var_len); - let float_vars = - vars_since_snapshot(&inner.float_unification_table(), vars_pre_snapshot.float_var_len); + let float_vars = float_vars_since_snapshot(&mut inner, vars_pre_snapshot.float_var_len); let const_vars = const_vars_since_snapshot( &mut inner.const_unification_table(), @@ -157,7 +167,7 @@ impl SnapshotVarData { region_vars.0.is_empty() && type_vars.0.is_empty() && int_vars.is_empty() - && float_vars.is_empty() + && float_vars.0.is_empty() && const_vars.0.is_empty() } } @@ -202,8 +212,10 @@ impl<'a, 'tcx> TypeFolder> for InferenceFudger<'a, 'tcx> { } } ty::FloatVar(vid) => { - if self.snapshot_vars.float_vars.contains(&vid) { - self.infcx.next_float_var() + if self.snapshot_vars.float_vars.0.contains(&vid) { + let idx = vid.as_usize() - self.snapshot_vars.float_vars.0.start.as_usize(); + let span = self.snapshot_vars.float_vars.1[idx]; + self.infcx.next_float_var(span) } else { ty } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index b25d2a30681c0..fbc20bf83afa1 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -5137,3 +5137,52 @@ declare_lint! { reference: "issue #138762 ", }; } + +declare_lint! { + /// The `float_literal_f32_fallback` lint detects situations where the type of an unsuffixed + /// float literal falls back to `f32` instead of `f64` to avoid a compilation error. This occurs + /// when there is a trait bound `f32: From` (or equivalent, such as `T: Into`) and the + /// literal is inferred to have the same type as `T`. + /// + /// ### Example + /// + /// ```rust + /// fn foo(x: impl Into) -> f32 { + /// x.into() + /// } + /// + /// fn main() { + /// dbg!(foo(2.5)); + /// } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// Rust allows traits that are only implemented for a single floating point type to guide type + /// inferrence for floating point literals. This used to apply in the case of `f32: From` + /// (where `T` was inferred to be the same type as a floating point literal), as the only + /// floating point type impl was `f32: From`. However, as Rust is in the process of adding + /// support for `f16`, there are now two implementations for floating point types: + /// `f32: From` and `f32: From`. This means that the trait bound `f32: From` can no + /// longer guide inferrence for the type of the floating point literal. The default fallback for + /// unsuffixed floating point literals is `f64`. As `f32` does not implement `From`, + /// falling back to `f64` would cause a compilation error; therefore, the float type fallback + /// has been tempoarily adjusted to fallback to `f32` in this scenario. + /// + /// The lint will automatically provide a machine-applicable suggestion to add a `_f32` suffix + /// to the literal, which will fix the problem. + /// + /// This is a [future-incompatible] lint to transition this to a hard error in the future. See + /// [issue #FIXME] for more details. + /// + /// [issue #FIXME]: https://github.com/rust-lang/rust/issues/FIXME + pub FLOAT_LITERAL_F32_FALLBACK, + Warn, + "detects unsuffixed floating point literals whose type fallback to `f32`", + @future_incompatible = FutureIncompatibleInfo { + reason: FutureIncompatibilityReason::FutureReleaseErrorDontReportInDeps, + reference: "issue #FIXME ", + }; +} diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 301ae60457434..0954358184805 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1125,6 +1125,14 @@ impl<'tcx> Ty<'tcx> { } } + #[inline] + pub fn float_vid(self) -> Option { + match self.kind() { + &Infer(FloatVar(vid)) => Some(vid), + _ => None, + } + } + #[inline] pub fn is_ty_or_numeric_infer(self) -> bool { matches!(self.kind(), Infer(_)) diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index e1b10e1074d27..267e832a00e3f 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -573,6 +573,7 @@ pub trait Into: Sized { /// [`from`]: From::from /// [book]: ../../book/ch09-00-error-handling.html #[rustc_diagnostic_item = "From"] +#[cfg_attr(not(bootstrap), lang = "From")] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_on_unimplemented(on( all(_Self = "&str", T = "alloc::string::String"), diff --git a/library/core/src/convert/num.rs b/library/core/src/convert/num.rs index d5cb10a5d1c8b..d8faa6cebe8d8 100644 --- a/library/core/src/convert/num.rs +++ b/library/core/src/convert/num.rs @@ -185,8 +185,7 @@ impl_from!(u32 => f128, #[stable(feature = "lossless_float_conv", since = "1.6.0 // impl_from!(u64 => f128, #[stable(feature = "lossless_float_conv", since = "1.6.0")]); // float -> float -// FIXME(f16_f128): adding additional `From<{float}>` impls to `f32` breaks inference. See -// +impl_from!(f16 => f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")]); impl_from!(f16 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]); impl_from!(f16 => f128, #[stable(feature = "lossless_float_conv", since = "1.6.0")]); impl_from!(f32 => f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")]); diff --git a/tests/ui/float/f32-into-f32.fixed b/tests/ui/float/f32-into-f32.fixed new file mode 100644 index 0000000000000..9aa90fafa6423 --- /dev/null +++ b/tests/ui/float/f32-into-f32.fixed @@ -0,0 +1,21 @@ +//@ run-pass +//@ run-rustfix + +fn foo(_: impl Into) {} + +fn main() { + foo(1.0_f32); + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(-(2.5_f32)); + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(1e5_f32); + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(4f32); // no warning + let x = -4.0_f32; + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(x); +} diff --git a/tests/ui/float/f32-into-f32.rs b/tests/ui/float/f32-into-f32.rs new file mode 100644 index 0000000000000..990ea65fbbad6 --- /dev/null +++ b/tests/ui/float/f32-into-f32.rs @@ -0,0 +1,21 @@ +//@ run-pass +//@ run-rustfix + +fn foo(_: impl Into) {} + +fn main() { + foo(1.0); + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(-(2.5)); + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(1e5); + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(4f32); // no warning + let x = -4.0; + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted + foo(x); +} diff --git a/tests/ui/float/f32-into-f32.stderr b/tests/ui/float/f32-into-f32.stderr new file mode 100644 index 0000000000000..c5f3f83863606 --- /dev/null +++ b/tests/ui/float/f32-into-f32.stderr @@ -0,0 +1,39 @@ +warning: falling back to `f32` as the trait bound `f32: From` is not satisfied + --> $DIR/f32-into-f32.rs:7:9 + | +LL | foo(1.0); + | ^^^ help: explicitly specify the type as `f32`: `1.0_f32` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #FIXME + = note: `#[warn(float_literal_f32_fallback)]` on by default + +warning: falling back to `f32` as the trait bound `f32: From` is not satisfied + --> $DIR/f32-into-f32.rs:10:11 + | +LL | foo(-(2.5)); + | ^^^ help: explicitly specify the type as `f32`: `2.5_f32` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #FIXME + +warning: falling back to `f32` as the trait bound `f32: From` is not satisfied + --> $DIR/f32-into-f32.rs:13:9 + | +LL | foo(1e5); + | ^^^ help: explicitly specify the type as `f32`: `1e5_f32` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #FIXME + +warning: falling back to `f32` as the trait bound `f32: From` is not satisfied + --> $DIR/f32-into-f32.rs:17:14 + | +LL | let x = -4.0; + | ^^^ help: explicitly specify the type as `f32`: `4.0_f32` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #FIXME + +warning: 4 warnings emitted + diff --git a/tests/ui/float/trait-f16-or-f32.rs b/tests/ui/float/trait-f16-or-f32.rs new file mode 100644 index 0000000000000..72f0a4fbde477 --- /dev/null +++ b/tests/ui/float/trait-f16-or-f32.rs @@ -0,0 +1,13 @@ +//@ check-fail + +#![feature(f16)] + +trait Trait {} +impl Trait for f16 {} +impl Trait for f32 {} + +fn foo(_: impl Trait) {} + +fn main() { + foo(1.0); //~ ERROR the trait bound `f64: Trait` is not satisfied +} diff --git a/tests/ui/float/trait-f16-or-f32.stderr b/tests/ui/float/trait-f16-or-f32.stderr new file mode 100644 index 0000000000000..8af81231bd949 --- /dev/null +++ b/tests/ui/float/trait-f16-or-f32.stderr @@ -0,0 +1,20 @@ +error[E0277]: the trait bound `f64: Trait` is not satisfied + --> $DIR/trait-f16-or-f32.rs:12:9 + | +LL | foo(1.0); + | --- ^^^ the trait `Trait` is not implemented for `f64` + | | + | required by a bound introduced by this call + | + = help: the following other types implement trait `Trait`: + f16 + f32 +note: required by a bound in `foo` + --> $DIR/trait-f16-or-f32.rs:9:16 + | +LL | fn foo(_: impl Trait) {} + | ^^^^^ required by this bound in `foo` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/inference/untyped-primitives.rs b/tests/ui/inference/untyped-primitives.rs index 8515ca79903fc..d04ccb4ff7bbd 100644 --- a/tests/ui/inference/untyped-primitives.rs +++ b/tests/ui/inference/untyped-primitives.rs @@ -5,5 +5,7 @@ fn main() { let x = f32::from(3.14); + //~^ WARN falling back to `f32` + //~| WARN this was previously accepted let y = f64::from(3.14); } diff --git a/tests/ui/inference/untyped-primitives.stderr b/tests/ui/inference/untyped-primitives.stderr new file mode 100644 index 0000000000000..48d62963221cb --- /dev/null +++ b/tests/ui/inference/untyped-primitives.stderr @@ -0,0 +1,12 @@ +warning: falling back to `f32` as the trait bound `f32: From` is not satisfied + --> $DIR/untyped-primitives.rs:7:23 + | +LL | let x = f32::from(3.14); + | ^^^^ help: explicitly specify the type as `f32`: `3.14_f32` + | + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #FIXME + = note: `#[warn(float_literal_f32_fallback)]` on by default + +warning: 1 warning emitted +