Skip to content

Commit 7f559db

Browse files
committed
Fallback {float} to f32 when f32: From<{float}>
1 parent b0e9259 commit 7f559db

File tree

8 files changed

+130
-3
lines changed

8 files changed

+130
-3
lines changed

compiler/rustc_hir/src/lang_items.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,9 @@ language_item_table! {
436436
DefaultTrait1, sym::default_trait1, default_trait1_trait, Target::Trait, GenericRequirement::None;
437437

438438
ContractCheckEnsures, sym::contract_check_ensures, contract_check_ensures_fn, Target::Fn, GenericRequirement::None;
439+
440+
// Used to fallback `{float}` to `f32` when `f32: From<{float}>`
441+
From, sym::From, from_trait, Target::Trait, GenericRequirement::Exact(1);
439442
}
440443

441444
/// The requirement imposed on the generics of a lang item

compiler/rustc_hir_typeck/src/fallback.rs

Lines changed: 74 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ use rustc_hir::HirId;
1111
use rustc_hir::def::{DefKind, Res};
1212
use rustc_hir::def_id::DefId;
1313
use rustc_hir::intravisit::{InferKind, Visitor};
14-
use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable};
14+
use rustc_middle::ty::{
15+
self, ClauseKind, FloatVid, PredicatePolarity, TraitPredicate, Ty, TyCtxt, TypeSuperVisitable,
16+
TypeVisitable,
17+
};
1518
use rustc_session::lint;
1619
use rustc_span::def_id::LocalDefId;
1720
use rustc_span::{DUMMY_SP, Span};
@@ -92,14 +95,16 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
9295

9396
let diverging_fallback = self
9497
.calculate_diverging_fallback(&unresolved_variables, self.diverging_fallback_behavior);
98+
let fallback_to_f32 = self.calculate_fallback_to_f32(&unresolved_variables);
9599

96100
// We do fallback in two passes, to try to generate
97101
// better error messages.
98102
// The first time, we do *not* replace opaque types.
99103
let mut fallback_occurred = false;
100104
for ty in unresolved_variables {
101105
debug!("unsolved_variable = {:?}", ty);
102-
fallback_occurred |= self.fallback_if_possible(ty, &diverging_fallback);
106+
fallback_occurred |=
107+
self.fallback_if_possible(ty, &diverging_fallback, &fallback_to_f32);
103108
}
104109

105110
fallback_occurred
@@ -109,7 +114,8 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
109114
//
110115
// - Unconstrained ints are replaced with `i32`.
111116
//
112-
// - Unconstrained floats are replaced with `f64`.
117+
// - Unconstrained floats are replaced with `f64`, except when there is a trait predicate
118+
// `f32: From<{float}>`, in which case `f32` is used as the fallback instead.
113119
//
114120
// - Non-numerics may get replaced with `()` or `!`, depending on
115121
// how they were categorized by `calculate_diverging_fallback`
@@ -124,6 +130,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
124130
&self,
125131
ty: Ty<'tcx>,
126132
diverging_fallback: &UnordMap<Ty<'tcx>, Ty<'tcx>>,
133+
fallback_to_f32: &UnordSet<FloatVid>,
127134
) -> bool {
128135
// Careful: we do NOT shallow-resolve `ty`. We know that `ty`
129136
// is an unsolved variable, and we determine its fallback
@@ -146,6 +153,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
146153
let fallback = match ty.kind() {
147154
_ if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e),
148155
ty::Infer(ty::IntVar(_)) => self.tcx.types.i32,
156+
ty::Infer(ty::FloatVar(vid)) if fallback_to_f32.contains(vid) => self.tcx.types.f32,
149157
ty::Infer(ty::FloatVar(_)) => self.tcx.types.f64,
150158
_ => match diverging_fallback.get(&ty) {
151159
Some(&fallback_ty) => fallback_ty,
@@ -160,6 +168,64 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
160168
true
161169
}
162170

171+
/// Existing code relies on `f32: From<T>` (usually written as `T: Into<f32>`) resolving `T` to
172+
/// `f32` when the type of `T` is inferred from an unsuffixed float literal. Using the default
173+
/// fallback of `f64`, this would break when adding `impl From<f16> for f32`, as there are now
174+
/// two float type which could be `T`, meaning that the fallback of `f64` would be used and
175+
/// compilation error would occur as `f32` does not implement `From<f64>`. To avoid breaking
176+
/// existing code, we instead fallback `T` to `f32` when there is a trait predicate
177+
/// `f32: From<T>`. This means code like the following will continue to compile:
178+
///
179+
/// ```rust
180+
/// fn foo<T: Into<f32>>(_: T) {}
181+
///
182+
/// foo(1.0);
183+
/// ```
184+
fn calculate_fallback_to_f32(&self, unresolved_variables: &[Ty<'tcx>]) -> UnordSet<FloatVid> {
185+
let Some(from_trait) = self.tcx.lang_items().from_trait() else {
186+
return UnordSet::new();
187+
};
188+
let pending_obligations = self.fulfillment_cx.borrow_mut().pending_obligations();
189+
debug!("calculate_fallback_to_f32: pending_obligations={:?}", pending_obligations);
190+
let roots: UnordSet<ty::FloatVid> = pending_obligations
191+
.into_iter()
192+
.filter_map(|obligation| {
193+
// The predicates we are looking for look like
194+
// `TraitPredicate(<f32 as std::convert::From<{float}>>, polarity:Positive)`.
195+
// They will have no bound variables.
196+
obligation.predicate.kind().no_bound_vars()
197+
})
198+
.filter_map(|predicate| match predicate {
199+
ty::PredicateKind::Clause(ClauseKind::Trait(TraitPredicate {
200+
polarity: PredicatePolarity::Positive,
201+
trait_ref,
202+
})) if trait_ref.def_id == from_trait
203+
&& self.shallow_resolve(trait_ref.self_ty()).kind()
204+
== &ty::Float(ty::FloatTy::F32) =>
205+
{
206+
self.root_float_vid(trait_ref.args.type_at(1))
207+
}
208+
_ => None,
209+
})
210+
.collect();
211+
debug!("calculate_fallback_to_f32: roots={:?}", roots);
212+
if roots.is_empty() {
213+
// Most functions have no `f32: From<{float}>` predicates, so short-circuit and return
214+
// an empty set when this is the case.
215+
return UnordSet::new();
216+
}
217+
// Calculate all the unresolved variables that need to fallback to `f32` here. This ensures
218+
// we don't need to find root variables in `fallback_if_possible`: see the comment at the
219+
// top of that function for details.
220+
let fallback_to_f32 = unresolved_variables
221+
.iter()
222+
.flat_map(|ty| ty.float_vid())
223+
.filter(|vid| roots.contains(&self.root_float_var(*vid)))
224+
.collect();
225+
debug!("calculate_fallback_to_f32: fallback_to_f32={:?}", fallback_to_f32);
226+
fallback_to_f32
227+
}
228+
163229
/// The "diverging fallback" system is rather complicated. This is
164230
/// a result of our need to balance 'do the right thing' with
165231
/// backwards compatibility.
@@ -565,6 +631,11 @@ impl<'tcx> FnCtxt<'_, 'tcx> {
565631
Some(self.root_var(self.shallow_resolve(ty).ty_vid()?))
566632
}
567633

634+
/// If `ty` is an unresolved float type variable, returns its root vid.
635+
fn root_float_vid(&self, ty: Ty<'tcx>) -> Option<ty::FloatVid> {
636+
Some(self.root_float_var(self.shallow_resolve(ty).float_vid()?))
637+
}
638+
568639
/// Given a set of diverging vids and coercions, walk the HIR to gather a
569640
/// set of suggestions which can be applied to preserve fallback to unit.
570641
fn try_to_suggest_annotations(

compiler/rustc_infer/src/infer/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,6 +1056,10 @@ impl<'tcx> InferCtxt<'tcx> {
10561056
self.inner.borrow_mut().type_variables().root_var(var)
10571057
}
10581058

1059+
pub fn root_float_var(&self, var: ty::FloatVid) -> ty::FloatVid {
1060+
self.inner.borrow_mut().float_unification_table().find(var)
1061+
}
1062+
10591063
pub fn root_const_var(&self, var: ty::ConstVid) -> ty::ConstVid {
10601064
self.inner.borrow_mut().const_unification_table().find(var).vid
10611065
}

compiler/rustc_middle/src/ty/sty.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,14 @@ impl<'tcx> Ty<'tcx> {
11261126
}
11271127
}
11281128

1129+
#[inline]
1130+
pub fn float_vid(self) -> Option<ty::FloatVid> {
1131+
match self.kind() {
1132+
&Infer(FloatVar(vid)) => Some(vid),
1133+
_ => None,
1134+
}
1135+
}
1136+
11291137
#[inline]
11301138
pub fn is_ty_or_numeric_infer(self) -> bool {
11311139
matches!(self.kind(), Infer(_))

library/core/src/convert/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,6 +573,7 @@ pub trait Into<T>: Sized {
573573
/// [`from`]: From::from
574574
/// [book]: ../../book/ch09-00-error-handling.html
575575
#[rustc_diagnostic_item = "From"]
576+
#[cfg_attr(not(bootstrap), lang = "From")]
576577
#[stable(feature = "rust1", since = "1.0.0")]
577578
#[rustc_on_unimplemented(on(
578579
all(_Self = "&str", T = "alloc::string::String"),

tests/ui/float/f32-into-f32.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
//@ run-pass
2+
3+
fn foo(_: impl Into<f32>) {}
4+
5+
fn main() {
6+
foo(1.0);
7+
}

tests/ui/float/trait-f16-or-f32.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
//@ check-fail
2+
3+
#![feature(f16)]
4+
5+
trait Trait {}
6+
impl Trait for f16 {}
7+
impl Trait for f32 {}
8+
9+
fn foo(_: impl Trait) {}
10+
11+
fn main() {
12+
foo(1.0); //~ ERROR the trait bound `f64: Trait` is not satisfied
13+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error[E0277]: the trait bound `f64: Trait` is not satisfied
2+
--> $DIR/trait-f16-or-f32.rs:12:9
3+
|
4+
LL | foo(1.0);
5+
| --- ^^^ the trait `Trait` is not implemented for `f64`
6+
| |
7+
| required by a bound introduced by this call
8+
|
9+
= help: the following other types implement trait `Trait`:
10+
f16
11+
f32
12+
note: required by a bound in `foo`
13+
--> $DIR/trait-f16-or-f32.rs:9:16
14+
|
15+
LL | fn foo(_: impl Trait) {}
16+
| ^^^^^ required by this bound in `foo`
17+
18+
error: aborting due to 1 previous error
19+
20+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)