Skip to content

Commit 508ae47

Browse files
committed
add note on the interaction of promotion and const validity checks
1 parent 49b6d56 commit 508ae47

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

text/0000-infallible-promotion.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,13 +113,27 @@ assert!(C.1 == false);
113113
```
114114
See [this prior RFC](https://github.com/rust-lang/rfcs/blob/master/text/1211-mir.md#overflow-checking) for further details.
115115

116+
However, also note that operators being infallible is more subtle than it might seem.
117+
In particular, it requires that all constants of integer type (and even all integer-typed fields of all constants) be proper integers, not pointers cast to integers.
118+
The following code shows a problematic example:
119+
```rust
120+
const FOO: usize = &42 as *const i32 as usize;
121+
let x: &usize = &(FOO * 3);
122+
```
123+
`FOO*3` cannot be evaluated during CTFE, so to ensure that multiplication is infallible, we need to ensure that all constants used in promotion are proper integers.
124+
This is currently ensured by the "validity check" that is performed on the final value of each constant: the check recursively traverses the type of the constant and ensures that the data matches that type.
125+
116126
Operations that might fail include:
117127
- `/`/`%`
118128
- `panic!` (including the assertion that follows `Checked*` arithmetic to ensure that no overflow happened)
119129
- array/slice indexing
120130
- any unsafe operation
121131
- `const fn` calls (as they might do any of the above)
122132

133+
Notably absent from *both* of the above list is dereferencing a reference.
134+
This operation is, in principle, infallible---but due to the concern mentioned above about validity of consts, it is only infallible if the validity check in constants traverses through references.
135+
Currently, the check stops when hitting a reference to a static, so currently, dereferencing a reference can *not* be considered an infallible operation for the purpose of promotion.
136+
123137
# Reference-level explanation
124138
[reference-level-explanation]: #reference-level-explanation
125139

0 commit comments

Comments
 (0)