Working towards a libc-less (wasm32) libstd
This is a series of commits I was able to extract from prepare to comiple libstd on a "bare libc-less" target, notably wasm32. The actual wasm32 bits I intend to send in a PR later, this is just some internal refactorings required for libstd to work with a `libc` that's empty and a few other assorted refactorings.
No functional change should be included in this PR for users of libstd, this is intended to just be internal refactorings.
This commit removes usage of the `libc` crate in "portable" modules like
those at the top level and `sys_common`. Instead common types like `*mut
u8` or `u32` are used instead of `*mut c_void` or `c_int` as well as
switching to platform-specific functions like `sys::strlen` instead of
`libc::strlen`.
Refactor internal suggestion API
~~The only functional change is that whitespace, which is suggested to be added, also gets `^^^^` under it. An example is shown in the tests (the only test that changed).~~
Continuation of #41876
r? @nagisa
the changes are probably best viewed [without whitespace](https://github.com/rust-lang/rust/pull/45741/files?w=1)
This commit moves the `f32::cmath` and `f64::cmath` modules into the
`sys` module. Note that these are not publicly exported modules, simply
implementation details. These modules are already platform-specific with
shims on MSVC and this is mostly just a reflection of that reality. This
should also help cut down on `#[cfg]` traffic if platforms are brought on
which don't directly support these functions.
This commit removes the reexport of `EBADF_ERR` as a constant from
libstd's portability facade, instead opting for a platform-specific
function that specifically queries an `io::Error`. Not all platforms may
have a constant for this, so it makes the intent a little more clear
that a code need not be supplied, just an answer to a query.
This commit removes the `rand` crate from the standard library facade as
well as the `__rand` module in the standard library. Neither of these
were used in any meaningful way in the standard library itself. The only
need for randomness in libstd is to initialize the thread-local keys of
a `HashMap`, and that unconditionally used `OsRng` defined in the
standard library anyway.
The cruft of the `rand` crate and the extra `rand` support in the
standard library makes libstd slightly more difficult to port to new
platforms, namely WebAssembly which doesn't have any randomness at all
(without interfacing with JS). The purpose of this commit is to clarify
and streamline randomness in libstd, focusing on how it's only required
in one location, hashmap seeds.
Note that the `rand` crate out of tree has almost always been a drop-in
replacement for the `rand` crate in-tree, so any usage (accidental or
purposeful) of the crate in-tree should switch to the `rand` crate on
crates.io. This then also has the further benefit of avoiding
duplication (mostly) between the two crates!
Add reftest that checks the layout of repr(int) on non-c-like enums
This verifies the first layout specified in https://github.com/rust-lang/rfcs/pull/2195
The second (`repr(C)`) layout isn't included here because it doesn't actually exist today. However if/when that's implemented a second test could be fairly easily derived from this one.
CC @eddyb
incr.comp.: Verify stability of incr. comp. hashes and clean up various other things.
The main contribution of this PR is that it adds the `-Z incremental-verify-ich` functionality. Normally, when the red-green tracking system determines that a certain query result has not changed, it does not re-compute the incr. comp. hash (ICH) for that query result because that hash is already known. `-Z incremental-verify-ich` tells the compiler to re-hash the query result and compare the new hash against the cached hash. This is a rather thorough way of
- testing hashing implementation stability,
- finding missing `[input]` annotations on `DepNodes`, and
- finding missing read-edges,
since both a missed read and a missing `[input]` annotation can lead to something being marked as green instead of red and thus will have a different hash than it should have.
Case in point, implementing this verification logic and activating it for all `src/test/incremental` tests has revealed several such oversights, all of which are fixed in this PR.
r? @nikomatsakis
Detect `=` -> `:` typo in let bindings
When encountering a let binding type error, attempt to parse as
initializer instead. If successful, it is likely just a typo:
```rust
fn main() {
let x: Vec::with_capacity(10);
}
```
```
error: expected type, found `10`
--> file.rs:3:31
|
3 | let x: Vec::with_capacity(10, 20);
| -- ^^
| ||
| |help: did you mean assign here?: `=`
| while parsing the type for `x`
```
Fix#43703.
Saturating casts between integers and floats
Introduces a new flag, `-Z saturating-float-casts`, which makes code generation for int->float and float->int casts safe (`undef`-free), implementing [the saturating semantics laid out by](https://github.com/rust-lang/rust/issues/10184#issuecomment-299229143) @jorendorff for float->int casts and overflowing to infinity for `u128::MAX` -> `f32`.
Constant evaluation in trans was changed to behave like HIR const eval already did, i.e., saturate for u128->f32 and report an error for problematic float->int casts.
Many thanks to @eddyb, whose APFloat port simplified many parts of this patch, and made HIR constant evaluation recognize dangerous float casts as mentioned above.
Also thanks to @ActuallyaDeviloper whose branchless implementation served as inspiration for this implementation.
cc #10184#41799fixes#45134
Disable `mmap` in `libbacktrace` on Apple platforms
Fixes#45731
libbacktrace uses mmap if available to map ranges of the files containing debug information. On macOS `mmap` will succeed even if the mapped range does not exist, and a SIGBUS (with an unusual EXC_BAD_ACCESS code 10) will occur when the program attempts to page in the memory. To combat this we force `libbacktrace` to be built with the simple `read` based fallback on Apple platforms.
Only instantiate inline- and const-fns if they are referenced (again).
It seems that we have regressed on not translating `#[inline]` functions unless they are actually used. This should bring back this optimization. I also added a regression test this time so it doesn't happen again accidentally.
Fixes#40392.
r? @alexcrichton
UPDATE & PSA
---------------------
This patch **makes translation very lazy** -- in general this is a good thing (we don't want the compiler to do unnecessary work) but it has two consequences:
1. Some error messages are only generated when an item is actually translated. Consequently, this patch will lead to more cases where the compiler will only start emitting errors when the erroneous function is actually used. This has always been true to some extend (e.g. when passing generic values to an intrinsic) but since this is something user-facing it's worth mentioning.
2. When writing tests, one has to make sure that the functions in question are actually generated. In other words, it must not be dead code. This can usually be achieved by either
1. making sure the function is exported from the resulting binary or
2. by making sure the function is called from something that is exported (or `main()`).
Note that it depends on the crate type what functions are exported:
1. For rlibs and dylibs everything that is reachable from the outside is exported.
2. For executables, cdylibs, and staticlibs, items are only exported if they are additionally `#[no_mangle]` or have an `#[export_name]`.
The commits in this PR contain many examples of how tests can be updated to comply to the new requirements.
Fixes#45731
libbacktrace uses mmap if available to map ranges of the files containing debug information. On macOS `mmap` will succeed even if the mapped range does not exist, and a SIGBUS (with an unusual EXC_BAD_ACCESS code 10) will occur when the program attempts to page in the memory. To combat this we force `libbacktrace` to be built with the simple `read` based fallback on Apple platforms.
Warn about lack of args glob expansion in Windows shell
Because all shells on Linux/macOS expand globs, and even MinGW on Windows emulates this behavior, it's easy to forget that Windows by itself doesn't support glob expansion. This PR documents this cross-platform difference.
impl FromIterator<()> for ()
This just collapses all unit items from an iterator into one. This is
more useful when combined with higher-level abstractions, like
collecting to a `Result<(), E>` where you only care about errors:
```rust
use std::io::*;
data = vec![1, 2, 3, 4, 5];
let res: Result<()> = data.iter()
.map(|x| writeln!(stdout(), "{}", x))
.collect();
assert!(res.is_ok());
```
Remove `T: Sized` on pointer `as_ref()` and `as_mut()`
`NonZero::is_zero()` was already casting all pointers to thin `*mut u8` to check for null. The same test on unsized fat pointers can also be used with `as_ref()` and `as_mut()` to get fat references.
(This PR formerly changed `is_null()` too, but checking just the data pointer is not obviously correct for trait objects, especially if `*const self` sorts of methods are ever allowed.)
This affects regular code generation as well as constant evaluation in trans,
but not the HIR constant evaluator because that one returns an error for
overflowing casts and NaN-to-int casts. That error is conservatively
correct and we should be careful to not accept more code in constant
expressions.
The changes to code generation are guarded by a new -Z flag, to be able
to evaluate the performance impact. The trans constant evaluation changes
are unconditional because they have no run time impact and don't affect
type checking either.
Pretty print parens around casts on the LHS of `<`/`<<`
When pretty printing a cast expression occuring on the LHS of a `<` or `<<` expression, we should add parens around the cast. Otherwise, the `<`/`<<` gets interpreted as the beginning of the generics for the type on the RHS of the cast.
Consider:
$ cat parens_cast.rs
macro_rules! negative {
($e:expr) => { $e < 0 }
}
fn main() {
negative!(1 as i32);
}
Before this PR, the output of the following is not valid Rust:
$ rustc -Z unstable-options --pretty=expanded parens_cast.rs
#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
macro_rules! negative(( $ e : expr ) => { $ e < 0 });
fn main() { 1 as i32 < 0; }
After this PR, the output of the following is valid Rust:
$ rustc -Z unstable-options --pretty=expanded parens_cast.rs
#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
macro_rules! negative(( $ e : expr ) => { $ e < 0 });
fn main() { (1 as i32) < 0; }
I've gone through several README/wiki style documents but I'm still not sure where to test this though. I'm not even sure if this sort of thing is tested...
rustdoc: add #[allow(unused)] to every doctest
More information in #45750 - this is behavior that was documented but not actually implemented.
I also reordered how outer attributes are applied to doctests. Previously, attributes from `#![doc(test(attr(...)))]` would be applied *after* attributes from within the test itself, meaning if a doctest tried to override lints that would be set crate-wide, it wouldn't work at all. This gives a better scope of how lints can be applied.
Closes#45750
Handle anon lifetime arg being returned with named lifetime return type
When there's a lifetime mismatch between an argument with an anonymous
lifetime being returned in a method with a return type that has a named
lifetime, show specialized lifetime error pointing at argument with a
hint to give it an explicit lifetime matching the return type.
```
error[E0621]: explicit lifetime required in the type of `other`
--> file2.rs:21:21
|
17 | fn bar(&self, other: Foo) -> Foo<'a> {
| ----- consider changing the type of `other` to `Foo<'a>`
...
21 | other
| ^^^^^ lifetime `'a` required
```
Follow up to #44124 and #42669. Fix#44684.