Pretty-print attributes on tuple structs and add tests
This adds support to the pretty printer to print attributes added to tuple struct elements. Furthermore, it adds a test that makes sure we will print attributes on all variant data types.
Fix ICE in memory categorization of tuple patterns
Fixes https://github.com/rust-lang/rust/issues/34334
It seems to be ok for `pat_ty` to return `Err` even if type checking is done, because it uses `infcx.node_ty` which is supposed to return `Err` for all kinds of erroneous types so its callers could quickly bail out with `?`.
r? @arielb1
Specialize .zip() for efficient slice and slice iteration
The idea is to introduce a private trait TrustedRandomAccess and specialize .zip() for random access iterators into a counted loop.
The implementation in the PR is internal and has no visible effect in the API
Why a counted loop? To have each slice iterator compile to just a pointer, and both pointers are indexed with the same loop counter value in the generated code. When this succeeds, copying loops are readily recognized and replaced with memcpy and addition loops autovectorize well.
The TrustedRandomAccess approach works very well on the surface. Microbenchmarks optimize well, following the ideas above, and that is a dramatic improvement of .zip()'s codegen.
```rust
// old zip before this PR: bad, byte-for-byte loop
// with specialized zip: memcpy
pub fn copy_zip(xs: &[u8], ys: &mut [u8]) {
for (a, b) in ys.iter_mut().zip(xs) {
*a = *b;
}
}
// old zip before this PR: single addition per iteration
// with specialized zip: vectorized
pub fn add_zip(xs: &[f32], ys: &mut [f32]) {
for (a, b) in ys.iter_mut().zip(xs) { *a += *b; }
}
// old zip before this PR: single addition per iteration
// with specialized zip: vectorized (!!)
pub fn add_zip3(xs: &[f32], ys: &[f32], zs: &mut [f32]) {
for ((a, b), c) in zs.iter_mut().zip(xs).zip(ys) { *a += *b * *c; }
}
```
Yet in more complex situations, the .zip() loop can still fall back to its old behavior where phantom null checks throw in fake premature end of the loop conditionals. Remember that a NULL inside
Option<(&T, &T)> makes it a `None` value and a premature (in this case)
end of the loop.
So even if we have 1) an explicit `Some` in the code and 2) the types of the pointers are `&T` or `&mut T` which are nonnull, we can still get a phantom null check at that point.
One example that illustrates the difference is `copy_zip` with slice versus Vec arguments. The involved iterator types are exactly the same, but the Vec version doesn't compile down to memcpy. Investigating into this, the function argument metadata emitted to llvm plays the biggest role. As eddyb summarized, we need nonnull for the loop to autovectorize and noalias for it to replace with memcpy.
There was an experiment to use `assume` to add a non-null assumption on each of the two elements in the specialized zip iterator, but this only helped in some of the test cases and regressed others. Instead I think the nonnull/noalias metadata issue is something we need to solve separately anyway.
These have conditionally implemented TrustedRandomAccess
- Enumerate
- Zip
These have not implemented it
- Map is sideeffectful. The forward case would be workable, but the double ended case is complicated.
- Chain, exact length semantics unclear
- Filter, FilterMap, FlatMap and many others don't offer random access and/or exact length
This adds support to the pretty printer to print attributes
added to tuple struct elements. Furthermore, it adds a test
that makes sure we will print attributes on all variant data
types.
Revert using ? for try! in the libsyntax pretty printer
The use of ...?instead of try!(...) in libsyntax makes extracting libsyntax into syntex quite painful since it's not stable yet. This makes backports take a much longer time and causes a lot of problems for the syntex dependencies. Even if it was, it'd take a few release cycles until syntex would be able to use it. Since it's not stable and that this feature is just syntax sugar, it would be most helpful if we could remove it.
cc #34311
[MIR] Cache drops for early scope exits
Previously we would rebuild all drops on every early exit from a scope, which for code like:
```rust
match x {
A => return 1,
B => return 2,
...
C => return 27
}
```
would produce 27 exactly same chains of drops for each return, basically a `O(n*m)` explosion. [This](https://cloud.githubusercontent.com/assets/679122/16125192/3355e32c-33fb-11e6-8564-c37cab2477a0.png) is such a case for a match on 80-variant enum with 3 droppable variables in scope.
For [`::core::iter::Iterator::partial_cmp`](6edea2cfda/src/libcore/iter/iterator.rs (L1909)) the CFG looked like [this](https://cloud.githubusercontent.com/assets/679122/16122708/ce0024d8-33f0-11e6-93c2-e1c44b910db2.png) (after initial SimplifyCfg). With this patch the CFG looks like [this](https://cloud.githubusercontent.com/assets/679122/16122806/294fb16e-33f1-11e6-95f6-16c5438231af.png) instead.
Some numbers (overall very small wins, however neither of the crates have many cases which abuse this corner case):
| | old time | old rss | new time | new rss |
|-------------------------|----------|---------|----------|----------|
| core dump | 0.879 | 224MB | 0.871 | 223MB |
| core MIR passes | 0.759 | 224MB | 0.718 | 223MB |
| core MIR codegen passes | 1.762 | 230MB | 1.442 | 228MB |
| core trans | 3.263 | 279MB | 3.116 | 278MB |
| core llvm passes | 5.611 | 263MB | 5.565 | 263MB |
| std dump | 0.487 | 190MB | 0.475 | 192MB |
| std MIR passes | 0.311 | 190MB | 0.288 | 192MB |
| std MIR codegen passes | 0.753 | 195MB | 0.720 | 197MB |
| std trans | 2.589 | 287MB | 2.523 | 287MB |
| std llvm passes | 7.268 | 245MB | 7.447 | 246MB |
Previously we would rebuild all drops on every early exit from a scope, which for code like:
```rust
match x {
a => return 1,
b => return 2,
...
z => return 27
}
```
would produce 27 exactly same chains of drops for each return, a O(n*m) explosion in drops.
The use of ...?instead of try!(...) in libsyntax makes
extracting libsyntax into syntex quite painful since it's
not stable yet. This makes backports take a much longer time
and causes a lot of problems for the syntex dependencies. Even
if it was, it'd take a few release cycles until syntex would
be able to use it. Since it's not stable and that this feature
is just syntax sugar, it would be most helpful if we could remove
it.
cc #34311
Add an abs_path member to FileMap, use it when writing debug info.
Fixes#34179.
When items are inlined from extern crates, the filename in the debug info
is taken from the FileMap that's serialized in the rlib metadata.
Currently this is just FileMap.name, which is whatever path is passed to rustc.
Since libcore and libstd are built by invoking rustc with relative paths,
they wind up with relative paths in the rlib, and when linked into a binary
the debug info uses relative paths for the names, but since the compilation
directory for the final binary, tools trying to read source filenames
will wind up with bad paths. We noticed this in Firefox with source
filenames from libcore/libstd having bad paths.
This change stores an absolute path in FileMap.abs_path, and uses that
if available for writing debug info. This is not going to magically make
debuggers able to find the source, but it will at least provide sensible
paths.
When items are inlined from extern crates, the filename in the debug info
is taken from the FileMap that's serialized in the rlib metadata.
Currently this is just FileMap.name, which is whatever path is passed to rustc.
Since libcore and libstd are built by invoking rustc with relative paths,
they wind up with relative paths in the rlib, and when linked into a binary
the debug info uses relative paths for the names, but since the compilation
directory for the final binary, tools trying to read source filenames
will wind up with bad paths. We noticed this in Firefox with source
filenames from libcore/libstd having bad paths.
This change stores an absolute path in FileMap.abs_path, and uses that
if available for writing debug info. This is not going to magically make
debuggers able to find the source, but it will at least provide sensible
paths.
Revert a change in the scope of macros imported from crates to fix a regression
Fixes#34212.
The regression was caused by #34032, which changed the scope of macros imported from extern crates to match the scope of macros imported from modules.
r? @nrc
Support nested `cfg_attr` attributes
Support arbitrarily deeply nested `cfg_attr` attributes (e.g. `#[cfg_attr(foo, cfg_attr(bar, baz))]`).
This makes configuration idempotent.
Currently, the nighties do not support any `cfg_attr` nesting. Stable and beta support just one level of `cfg_attr` nesting (expect for attributes on macro-expanded nodes, where no nesting is supported).
This is a [breaking-change]. For example, the following would break:
```rust
macro_rules! m { () => {
#[cfg_attr(all(), cfg_attr(all(), cfg(foo)))]
fn f() {}
} }
m!();
fn main() { f() } //~ ERROR unresolved name `f`
```
r? @nrc
Show types of all args when missing args
When there're missing arguments in a function call, present a list of
all the expected types:
```rust
fn main() {
t("");
}
fn t(a: &str, x: String) {}
```
```bash
% rustc file.rs
file.rs:3:5: 2:8 error: this function takes 2 parameters but 0
parameters were supplied [E0061]
file.rs:3 t();
^~~
file.rs:3:5: 2:8 help: run `rustc --explain E0061` to see a detailed explanation
file.rs:3:5: 2:8 note: the following parameter types were expected: &str, std::string::String
error: aborting due to previous error
```
Fixes#33649
When there're missing arguments in a function call, present a list of
all the expected types:
```rust
fn main() {
t("");
}
fn t(a: &str, x: String) {}
```
```bash
% rustc file.rs
file.rs:3:5: 2:8 error: this function takes 2 parameters but 0
parameters were supplied [E0061]
file.rs:3 t();
^~~
file.rs:3:5: 2:8 help: run `rustc --explain E0061` to see a detailed explanation
file.rs:3:5: 2:8 note: the following parameter types were expected: &str, std::string::String
error: aborting due to previous error
```
Fixes#33649
prefer `if let` to match with `None => ()` arm in some places
Casual grepping revealed some places in the codebase (some of which
antedated `if let`'s December 2014 stabilization in c200ae5a) where we
were using a match with a `None => ()` arm where (in the present
author's opinion) an `if let` conditional would be more readable. (Other
places where matching to the unit value did seem to better express the
intent were left alone.)
It's likely that we don't care about making such trivial,
non-functional, sheerly æsthetic changes.
But if we do, this is a patch.
Casual grepping revealed some places in the codebase (some of which
antedated `if let`'s December 2014 stabilization in c200ae5a) where we
were using a match with a `None => ()` arm where (in the present
author's opinion) an `if let` conditional would be more readable. (Other
places where matching to the unit value did seem to better express the
intent were left alone.)
It's likely that we don't care about making such trivial,
non-functional, sheerly æsthetic changes.
But if we do, this is a patch.
derive Hash (and not Copy) for ranges
Fixes#34170.
Also, `RangeInclusive` was `Copy` by mistake -- fix that, which is a [breaking-change] to that unstable type.
Improve IP reserved address docs
- Add links to all RFCs to make it clear these are not Rust RFCs.
- Correct RFC numbers to match the numbers in [RFC 6890](https://tools.ietf.org/html/rfc6890)
- Clean up formatting to show addresses and ranges in parentheses like (255.255.255.255)
r? @steveklabnik
rustdoc: Fix redirect pages for renamed reexports
We need to use the name of the target not the name of the current item
when creating the link.
An example in `std` is [`std::sys::ext`](https://doc.rust-lang.org/nightly/std/sys/ext/index.html).
rustdoc: Don't inline #[doc(hidden)] pub use
Currently if a `#[doc(hidden)] pub use` item is inlined the `hidden`
attribute is ignored so the item can appear in the docs. By never inlining
such imports, they can be stripped.
An example in `std` is [`__OsLocalKeyInner`](https://doc.rust-lang.org/nightly/std/thread/struct.__OsLocalKeyInner.html) which clearly should not be documented.
- Add links to all RFCs to make it clear these are not Rust RFCs.
- Correct RFC numbers to match the numbers in [RFC 6890](https://tools.ietf.org/html/rfc6890)
- Clean up formatting to show addresses and ranges in parentheses like (255.255.255.255)
It turns out that the subsequent lines of the error message comment
should be aligned like this.
The "turns the corresponding compiler warning" language may not be
strictly the most accurate—a lint check isn't the same as a compiler
warning; it emits a compiler warning if it's set to the `warn` level—
but it may be worth glossing over such distinctions in favor of simple,
familar phrasings for the sake of pedagogy; thanks to Guillaume Gomez
for the wording suggestion.
Let's also fix up the introductory clauses of the sentences about how to
fix the error to put a little more emphasis on the fact that the
`forbid` setting was probably there for a reason.
Add explanations for E0503 and E0508.
(cannot use `..` because it was mutably borrowed, cannot move out of type `..`, a non-copy fixed-size array)
Part of #32777.
add a test case for issue #32031
I propose a test case to finish the fix for issue #32031. Please review this commit thoroughly, as I have never written a codegen test before.
r? @eddyb
rustdoc: Don't generate empty files for stripped items
We need to traverse stripped modules to generate redirect pages, but we shouldn't generate
anything else for them.
This now renders the file contents to a Vec before writing it to a file in one go. I think
that's probably a better strategy anyway.
Fixes: #34025
Currently if a `#[doc(hidden)] pub use` item is inlined the `hidden`
attribute is ignored so the item can appear in the docs. By never inlining
such imports, they can be stripped.
Remove linking and intrinsics code made dead by only supporting LLVM 3.7 and up
This is mostly based on Alex's throwaway comment:
> probably reject those that LLVM just doesn't support...
So I'm more than happy to adjust the PR based on how you thought this should look. Also happy to split it into two PRs, one for linking and one for intrinsics.
r? @alexcrichton
/cc @nagisa @brson
Treat `#[test]` like `#[cfg(test)]` in non-test builds
This PR treats `#[test]` like `#[cfg(test)]` in non-test builds. In particular, like `#[cfg(test)]`,
- `#[test]` nodes are stripped during `cfg` processing, and
- `#[test]` is disallowed on non-optional expressions.
Closes#33946.
r? @nrc
Visit statement and expression attributes in the AST visitor
Currently, these attributes are not visited, so they are not gated feature checked in the post expansion visitor. This only affects crates using `#![feature(stmt_expr_attributes)]`.
r? @nrc
docs: Improve char::to_{lower,upper}case examples
Collect the results to a String to make it clear that it will not always
return only one char and add examples showing that.
r? @steveklabnik
docs: simplify wording
It took me more then a moment to decipher "with no non-`'static`" thing :)
"`'static` type" should say the same thing more clearly.
r? @steveklabnik
Remove a gotcha from book/error-handling.md
The book's "Error handling with `Box<Error>`" section talks about `Box<Error>`. In the actual example `Box<Error + Send + Sync>` is used instead so that the corresponding From impls could be used to convert a plain string to an error type. Rust 1.7 added support for conversion from `&str`/`String` to
`Box<Error>`, so this gotcha and later references to it can now be removed.
r? @steveklabnik
Reflect supporting only LLVM 3.7+ in the LLVM wrappers
Based on 12abddb06b, it appears we can drop support for these older LLVM versions. Hopefully, this will make it slightly easier to support the changes needed for LLVM 3.9.
r? @nagisa
/cc @brson
Fix wrong statement in compare_exchange doc
The documentation for `core::sync::atomic::AtomicSomething::compare_exchange` contains a wrong, or imprecise, statement about the return value. It goes:
The return value is a result indicating whether the new value was written and containing
the previous value. On success this value is guaranteed to be equal to `new`.
In the second sentence, `this value` is gramatically understood as referring to `return value` from the first sentence. Due to how CAS works, the returned value is always what was in the atomic variable _before_ the operation occurred, not what was written into it during the operation. Hence, the fixed doc should say:
The return value is a result indicating whether the new value was written and containing
the previous value. On success this value is guaranteed to be equal to `current`.
This version is confirmed by the runnable examples in variants of `AtomicSomething`, e.g.
assert_eq!(some_bool.compare_exchange(true, false, Ordering::Acquire, Ordering::Relaxed),
Ok(true));
where the returned value is `Ok(current)`. This PR fixes all occurrences of this bug I could find.
An alternative solution would be to modify the second sentence so that it refers to the value _written_ into the Atomic rather than what was there before, in which case it would be correct. Example alternative formulation:
On success the value written into the `bool`/`usize`/`whatever` is guaranteed to be equal to `new`.
r? @steveklabnik
MIR cleanups and predecessor cache
This PR cleans up a few things in MIR and adds a predecessor cache to allow graph algorithms to be run easily.
r? @nikomatsakis
Rewrote "How Safe and Unsafe Interact" Nomicon chapter.
The previous version of the chapter covered a lot of ground, but was a little meandering and hard to follow at times. This draft is intended to be clearer and more direct, while still providing the same information as the previous version.
r? @steveklabnik
Use it instead of a `panic` for inexhaustive matches and correct the
comment. I think we trust our match-generation algorithm enough to
generate these blocks, and not generating an `unreachable` means that
LLVM won't optimize `match void() {}` to an `unreachable`.
Fix issue #34101
Fix issue #34101: do not track subcontent of type with dtor nor gather flags for untracked content.
(Includes a regression test, which needed to go into `compile-fail/`
due to weaknesses when combining `#[deny(warnings)]` with
`tcx.sess.span_warn(..)`)
Refactor away the prelude injection fold
Instead, just inject `#[prelude_import] use [core|std]::prelude::v1::*;` at the crate root while injecting `extern crate [core|std];` and process `#[no_implicit_prelude]` attributes in `resolve`.
r? @nrc
Support `#[macro_use]` on macro-expanded crates
This PR loads macros from `#[macro_use]` crates during expansion so that
- macro-expanded `#[macro_use]` crates work (fixes#33936, fixes#28071), and
- macros imported from crates have the same scope as macros imported from modules.
This is a [breaking-change]. For example, this will break:
```rust
macro_rules! m {
() => { #[macro_use(foo)] extern crate core; } //~ ERROR imported macro not found
}
m!();
```
Also, this will break:
```rust
macro_rules! try { () => {} }
// #[macro_use] mod bar { macro_rules! try { ... } } //< ... just like this would ...
fn main() { try!(); } //< ... making this an error
```
r? @nrc
trans: don't misuse C_nil for ZSTs other than ().
`C_nil` is actually `C_null` for `()` so `TempRef::new_operand` was treating all ZSTs as `()`.
This should allow running Servo with `RUSTFLAGS=-Zorbit`, assuming there are no other bugs.
The root of the problem is that a string literal pattern is essentially of
the form `&LITERAL`, in a single block, while match checking wants to
split that.
To fix that, I added a type field to the patterns in match checking,
which allows us to distinguish between a full and split pattern.
That file is ugly and needs to be cleaned. However, `trans::_match` calls
it, so I think we should delay the cleanup until we kill that.
Fixes#30240
[MIR] Make scopes debuginfo-specific (visibility scopes).
Fixes#32949 by having MIR (visibility) scopes mimic the lexical structure.
Unlike #33235, this PR also removes all scopes without variable bindings.
Printing of scopes also changed, e.g. for:
```rust
fn foo(x: i32, y: i32) { let a = 0; let b = 0; let c = 0; }
```
Before my changes:
```rust
fn foo(arg0: i32, arg1: i32) -> () {
let var0: i32; // "x" in scope 1 at <anon>:1:8: 1:9
let var1: i32; // "y" in scope 1 at <anon>:1:16: 1:17
let var2: i32; // "a" in scope 3 at <anon>:1:30: 1:31
let var3: i32; // "b" in scope 6 at <anon>:1:41: 1:42
let var4: i32; // "c" in scope 9 at <anon>:1:52: 1:53
...
scope tree:
0 1 2 3 {
4 5
6 {
7 8
9 10 11
}
}
}
```
After my changes:
```rust
fn foo(arg0: i32, arg1: i32) -> () {
scope 1 {
let var0: i32; // "x" in scope 1 at <anon>:1:8: 1:9
let var1: i32; // "y" in scope 1 at <anon>:1:16: 1:17
scope 2 {
let var2: i32; // "a" in scope 2 at <anon>:1:30: 1:31
scope 3 {
let var3: i32; // "b" in scope 3 at <anon>:1:41: 1:42
scope 4 {
let var4: i32; // "c" in scope 4 at <anon>:1:52: 1:53
}
}
}
}
...
}
rustc: Try to contain prepends to PATH
This commit attempts to bring our prepends to PATH on Windows when loading
plugins because we've been seeing quite a few issues with failing to spawn a
process on Windows, the leading theory of which is that PATH is too large as a
result of this. Currently this is mostly a stab in the dark as it's not
confirmed to actually fix the problem, but it's probably not a bad change to
have anyway!
cc #33844Closes#17360
rustdoc: Fix generating redirect pages for statics and consts
These were missing from the cache for some reason meaning the redirect pages failed to render.
Remove the old FOLLOW checking (aka `check_matcher_old`).
It was supposed to be removed at the next release cycle but is still in the tree since like 6 months.
Potential breaking change, since some cases (such as #25658) will change from a warning to an error. But the warning stating that it will be a hard error in the next release has been there for 6 months now.
I think it's safe to break this code. ^_^
trans: always use a memcpy for ABI argument/return casts.
When storing incoming arguments or values returned by call/invoke, always do a `memcpy` from a temporary of the cast type, if there is an ABI cast.
While Clang has gotten smarter ([store](https://godbolt.org/g/EphFuK) vs [memcpy](https://godbolt.org/g/5dikH9)), a `memcpy` will always work.
This is what @dotdash has wanted to do all along, and it fixes#32049.