Skip to content

Commit c3fe177

Browse files
committed
Add description for LUB Coercion
1 parent 30af091 commit c3fe177

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/type-coercions.md

+44
Original file line numberDiff line numberDiff line change
@@ -184,3 +184,47 @@ unsized coercion to `Foo<U>`.
184184
185185
[`Unsize`]: ../std/marker/trait.Unsize.html
186186
[`CoerceUnsized`]: ../std/ops/trait.CoerceUnsized.html
187+
188+
## LUB Coercion
189+
190+
This is not in the RFC 401, but it's the behavior of current compiler. In LUB
191+
Coercion, we tried to find the least upper bound of given types. It can be
192+
observed in array collection, if-else/match arms.
193+
194+
For example:
195+
196+
```rust
197+
let emm = if true {
198+
A
199+
} else if false {
200+
B
201+
} else {
202+
C
203+
};
204+
205+
let foo = match 42 {
206+
0 => A,
207+
1 => B,
208+
_ => C,
209+
};
210+
211+
let bar = [A, B, C];
212+
```
213+
In this example, both `emm` and `foo` has type
214+
`LubCoerce(typeof(A), typeof(B), typeof(C))` and `bar` has type
215+
`[LubCoerce(typeof(A), typeof(B), typeof(C)); 3]`.
216+
217+
LUB Coercion has some features:
218+
1. Order independent: e.g. `LubCoerce(ty0, ty1, ty2, ty3)` equals to
219+
`LubCoerce(ty1, ty0, ty4, ty3)`.
220+
2. `LubCoerce(ty0, ty1, ty2, ...)` equals to
221+
`LubCoerce(LubCoerce(ty0, ty1), ty2, ...)`
222+
4. `LubCoerce(ty0, ty1) == ty2` means both `ty0` and `ty1` can be coerced to
223+
`ty2`.
224+
225+
Notice the feature No.3, it uses the word "means" rather than "if and only if".
226+
That's because currently if `ty0` and `ty1` can be coerced to `ty2` and `ty2`
227+
equals to neither `ty0` nor `ty1`, there are only two special cases we can get
228+
`LubCoerce(ty0, ty1) == ty2`:
229+
1. `LubCoerce(FnDef, FnDef) == FnPtr`,
230+
2. `LubCoerce(Closure, Closure) == FnPtr`(where Closure is non-capturing).

0 commit comments

Comments
 (0)