Explain why a closure is `FnOnce` in closure errors.
Issue: #42065
@nikomatsakis Am I going the right direction with this?
~~I am stuck in a few bits:~~
~~1. How to trace the code to get the upvar instead of the original variable's span?~~
~~2. How to find the node id of the upvar where the move occured?~~
trace_macro: Show both the macro call and its expansion. #42072.
See #42072 for the initial motivation behind this.
The change is not the minimal fix, but I want this behavior almost every time I use `trace_macros`.
add thiscall calling convention support
This support is needed for bindgen to work well on 32-bit Windows, and also enables people to begin experimenting with C++ FFI support on that platform.
Fixes#42044.
This support is needed for bindgen to work well on 32-bit Windows, and
also enables people to begin experimenting with C++ FFI support on that
platform.
Fixes#42044.
Add better error message when == operator is badly used
Part of #40660.
With the following code:
```rust
fn foo<T: PartialEq>(a: &T, b: T) {
a == b;
}
fn main() {
foo(&1, 1);
}
```
It prints:
```
error[E0277]: the trait bound `&T: std::cmp::PartialEq<T>` is not satisfied
--> test.rs:2:5
|
2 | a == b;
| ^^^^^^ can't compare `&T` with `T`
|
= help: the trait `std::cmp::PartialEq<T>` is not implemented for `&T`
= help: consider adding a `where &T: std::cmp::PartialEq<T>` bound
error: aborting due to previous error
```
Make diagnostic note for existing method with unsatisfied trait bounds
multiline for cleaner output.
```
= note: the method `count` exists but the following trait bounds were not satisfied:
`[closure@../../src/test/compile-fail/issue-36053-2.rs:17:39: 17:53] : std::ops::FnMut<(&_,)>`
`std::iter::Filter<std::iter::Fuse<std::iter::Once<&str>> [closure@../../src/test/compile-fail/issue-36053-2.rs:17:39: 17:53]> : std::iter::Iterator`
Before:
```
= note: the method `count` exists but the following trait bounds were not satisfied: `[closure@../../src/test/compile-fail/issue-36053-2.rs:17:39: 17:53] : std::ops::FnMut<(&_,)>`, `std::iter::Filter<std::iter::Fuse<std::iter::Once<&str>>, [closure@../../src/test/compile-fail/issue-36053-2.rs:17:39: 17:53]> : std::iter::Iterator`
```
Point at fields that make the type recursive
On recursive types of infinite size, point at all the fields that make
the type recursive.
```rust
struct Foo {
bar: Bar,
}
struct Bar {
foo: Foo,
}
```
outputs
```
error[E0072]: recursive type `Foo` has infinite size
--> file.rs:1:1
1 | struct Foo {
| ^^^^^^^^^^ recursive type has infinite size
2 | bar: Bar,
| -------- recursive here
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable
error[E0072]: recursive type `Bar` has infinite size
--> file.rs:5:1
|
5 | struct Bar {
| ^^^^^^^^^^ recursive type has infinite size
6 | foo: Foo,
| -------- recursive here
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Bar` representable
```
Suggest `!` for bitwise negation when encountering a `~`
Fix#41679
Here is a program
```rust
fn main() {
let x = ~1;
}
```
It's output:
```
error: `~` can not be used as an unary operator
--> /home/fcc/temp/test.rs:4:13
|
4 | let x = ~1;
| ^^
|
= help: use `!` instead of `~` if you meant to bitwise negation
```
cc @bstrie
On recursive types of infinite size, point at all the fields that make
the type recursive.
```rust
struct Foo {
bar: Bar,
}
struct Bar {
foo: Foo,
}
```
outputs
```
error[E0072]: recursive type `Foo` has infinite size
--> file.rs:1:1
1 | struct Foo {
| _^ starting here...
2 | | bar: Bar,
| | -------- recursive here
3 | | }
| |_^ ...ending here: recursive type has infinite size
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable
error[E0072]: recursive type `Bar` has infinite size
--> file.rs:5:1
|
5 | struct Bar {
| _^ starting here...
6 | | foo: Foo,
| | -------- recursive here
7 | | }
| |_^ ...ending here: recursive type has infinite size
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Bar` representable
```
Consider changing to & for let bindings #40402
This is a fix for #40402
For the example
```
fn main() {
let v = vec![String::from("oh no")];
let e = v[0];
}
```
It gives
```
error[E0507]: cannot move out of indexed content
--> ex1.rs:4:13
|
4 | let e = v[0];
| ^^^^ cannot move out of indexed content
|
= help: consider changing to `&v[0]`
error: aborting due to previous error
```
Another alternative is
```
error[E0507]: cannot move out of indexed content
--> ex1.rs:4:13
|
4 | let e = v[0];
| ^^^^ consider changing to `&v[0]`
error: aborting due to previous error
```
Also refer to #41564 for more details.
r? @nikomatsakis
Clean up callable type mismatch errors
```rust
error[E0593]: closure takes 1 argument but 2 arguments are required here
--> ../../src/test/ui/mismatched_types/closure-arg-count.rs:13:15
|
13 | [1, 2, 3].sort_by(|(tuple, tuple2)| panic!());
| ^^^^^^^ -------------------------- takes 1 argument
| |
| expected closure that takes 2 arguments
```
instead of
```rust
error[E0281]: type mismatch: the type `[closure@../../src/test/ui/mismatched_types/closure-arg-count.rs:13:23: 13:49]` implements the trait `for<'r> std::ops::FnMut<(&'r {integer},)>`, but the trait `for<'r, 'r> std::ops::FnMut<(&'r {integer}, &'r {integer})>` is required (expected a tuple with 2 elements, found one with 1 elements)
--> ../../src/test/ui/mismatched_types/closure-arg-count.rs:13:15
|
13 | [1, 2, 3].sort_by(|(tuple, tuple2)| panic!());
| ^^^^^^^
```
Fix#21857, re #24680.
Minimize single span suggestions into a label
changes
```
14 | println!("☃{}", tup[0]);
| ^^^^^^
|
help: to access tuple elements, use tuple indexing syntax as shown
| println!("☃{}", tup.0);
```
into
```
14 | println!("☃{}", tup[0]);
| ^^^^^^ to access tuple elements, use `tup.0`
```
Also makes suggestions explicit in the backend in preparation of adding multiple suggestions to a single diagnostic. Currently that's already possible, but results in a full help message + modified code snippet per suggestion, and has no rate limit (might show 100+ suggestions).
Checker:: Execute levenshtein before other context checking
As explain [here]() i think it's better to check for a miss typing before checking context dependent help.
```rust
struct Handle {}
struct Something {
handle: Handle
}
fn main() {
let handle: Handle = Handle {};
let s: Something = Something {
// Checker detect an error and propose a solution with `Handle { /* ... */ }`
// but it's a miss typing of `handle`
handle: Handle
};
}
```
Ping: @nagisa for #39226
Signed-off-by: Freyskeyd <simon.paitrault@gmail.com>
Implementation of repr struct alignment RFC 1358.
The main changes around rustc::ty::Layout::struct:
* Added abi_align field which stores abi alignment before repr align is applied
* align field contains transitive repr alignment
* Added padding vec which stores padding required after fields
The main user of this information is rustc_trans::adt::struct_llfields
which determines the LLVM fields to be used by LLVM, including padding
fields.
A possible future optimisation would be to put the padding Vec in an Option, since it will be unused unless you are using repr align.
When a span starts on a line with nothing but whitespace to the left,
and there are no other annotations in that line, simplify the visual
representation of the span.
Go from:
```rust
error[E0072]: recursive type `A` has infinite size
--> file2.rs:1:1
|
1 | struct A {
| _^ starting here...
2 | | a: A,
3 | | }
| |_^ ...ending here: recursive type has infinite size
|
```
To:
```rust
error[E0072]: recursive type `A` has infinite size
--> file2.rs:1:1
|
1 | / struct A {
2 | | a: A,
3 | | }
| |_^ recursive type has infinite size
```
Remove `starting here...`/`...ending here` labels from all multiline
diagnostics.
The main changes around rustc::ty::Layout::struct and rustc_trans:adt:
* Added primitive_align field which stores alignment before repr align
* Always emit field padding when generating the LLVM struct fields
* Added methods for adjusting field indexes from the layout index to the
LLVM struct field index
The main user of this information is rustc_trans::adt::struct_llfields
which determines the LLVM fields to be used by LLVM, including padding
fields.
Add a way to get shorter spans until `char` for pointing at defs
```rust
error[E0072]: recursive type `X` has infinite size
--> file.rs:10:1
|
10 | struct X {
| ^^^^^^^^ recursive type has infinite size
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `X` representable
```
vs
```rust
error[E0072]: recursive type `X` has infinite size
--> file.rs:10:1
|
10 | struct X {
| _^ starting here...
11 | | x: X,
12 | | }
| |_^ ...ending here: recursive type has infinite size
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `X` representable
```
Re: #35965, #38246. Follow up to #38328.
r? @jonathandturner
Highlight and simplify mismatched types
Shorten mismatched types errors by replacing subtypes that are not
different with `_`, and highlighting only the subtypes that are
different.
Given a file
```rust
struct X<T1, T2> {
x: T1,
y: T2,
}
fn foo() -> X<X<String, String>, String> {
X { x: X {x: "".to_string(), y: 2}, y: "".to_string()}
}
fn bar() -> Option<String> {
"".to_string()
}
```
provide the following output
```rust
error[E0308]: mismatched types
--> file.rs:6:5
|
6 | X { x: X {x: "".to_string(), y: 2}, y: "".to_string()}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found {integer}
|
= note: expected type `X<X<_, std::string::String>, _>`
^^^^^^^^^^^^^^^^^^^ // < highlighted
found type `X<X<_, {integer}>, _>`
^^^^^^^^^ // < highlighted
error[E0308]: mismatched types
--> file.rs:6:5
|
10 | "".to_string()
| ^^^^^^^^^^^^^^ expected struct `std::option::Option`, found `std::string::String`
|
= note: expected type `Option<std::string::String>`
^^^^^^^ ^ // < highlighted
found type `std::string::String`
```
Fix#21025. Re: #40186. Follow up to #39906.
I'm looking to change how this output is accomplished so that it doesn't create list of strings to pass around, but rather add an elided `Ty` placeholder, and use the same string formatting for normal types. I'll be doing that soonish.
r? @nikomatsakis
Use proper span for tuple index parsed as float
Fix diagnostic suggestion from:
```rust
help: try parenthesizing the first index
| (1, (2, 3)).((1, (2, 3)).1).1;
```
to the correct:
```rust
help: try parenthesizing the first index
| ((1, (2, 3)).1).1;
```
Fix#41081.
```rust
error[E0072]: recursive type `X` has infinite size
--> file.rs:10:1
|
10 | struct X {
| ^^^^^^^^ recursive type has infinite size
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `X` representable
```
vs
```rust
error[E0072]: recursive type `X` has infinite size
--> file.rs:10:1
|
10 | struct X {
| _^ starting here...
11 | | x: X,
12 | | }
| |_^ ...ending here: recursive type has infinite size
|
= help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `X` representable
```
Point at only one char on `Span::next_point`
Avoid pointing at two chars so the diagnostic output doesn't display a
multiline span when starting beyond a line end.
Fix#41155.
Instead of
```rust
error: expected one of `(`, `const`, `default`, `extern`, `fn`, `type`, or `unsafe`, found `}`
--> <anon>:3:1
|
1 | impl S { pub
| _____________- starting here...
2 | |
| | ...ending here: expected one of 7 possible tokens here
3 | }
| ^ unexpected token
```
show
```rust
error: expected one of `(`, `const`, `default`, `extern`, `fn`, `type`, or `unsafe`, found `}`
--> <anon>:13:1
|
12 | pub
| - expected one of 7 possible tokens here
13 | }
| ^ unexpected token
```
Explicit help message for binop type mismatch
When trying to do `1 + Some(2)`, or some other binary operation on two
types different types without an appropriate trait implementation, provide
an explicit help message:
```rust
help: `{integer} + std::option::Option<{integer}>` has no implementation
```
Re: #39579, #38564, #37626, #39942, #34698.
When trying to do a binary operation with missing implementation, for
example `1 + Some(2)`, provide an explicit help message:
```
note: no implementation for `{integer} + std::option::Option<{integer}>`
```
Use `rustc_on_unimplemented` for the suggestions. Move cfail test to ui.
don't try to blame tuple fields for immutability
Tuple fields don't have an `&T` in their declaration that can be changed
to `&mut T` - skip them..
Fixes#41104.
r? @nikomatsakis
Make 'overlapping_inherent_impls' lint a hard error
This is ought to be implemented in PR #40728. Unfortunately, when I rebased the PR to resolve merge conflict, the "hard error" code disappeared. This PR complements the initial PR.
Now the following rust code gives the following error:
```rust
struct Foo;
impl Foo {
fn id() {}
}
impl Foo {
fn id() {}
}
fn main() {}
```
```
error[E0592]: duplicate definitions with name `id`
--> /home/topecongiro/test.rs:4:5
|
4 | fn id() {}
| ^^^^^^^^^^ duplicate definitions for `id`
...
8 | fn id() {}
| ---------- other definition for `id`
error: aborting due to previous error
```
Fix diagnostic suggestion from:
```rust
help: try parenthesizing the first index
| (1, (2, 3)).((1, (2, 3)).1).1;
```
to the correct:
```rust
help: try parenthesizing the first index
| ((1, (2, 3)).1).1;
```
Do not recommend private fields called as method
```rust
error: no method named `dog_age` found for type `animal::Dog` in the current scope
--> $DIR/private-field.rs:26:23
|
26 | let dog_age = dog.dog_age();
| ^^^^^^^ private field, not a method
```
Fix#27654.
Add a `TyErr` type to represent unknown types in places where
parse errors have happened, while still able to build the AST.
Initially only used to represent incorrectly written fn arguments and
avoid "expected X parameters, found Y" errors when called with the
appropriate amount of parameters. We cannot use `TyInfer` for this as
`_` is not allowed as a valid argument type.
Example output:
```rust
error: expected one of `:` or `@`, found `,`
--> file.rs:12:9
|
12 | fn bar(x, y: usize) {}
| ^
error[E0061]: this function takes 2 parameters but 3 parameters were supplied
--> file.rs:19:9
|
12 | fn bar(x, y) {}
| --------------- defined here
...
19 | bar(1, 2, 3);
| ^^^^^^^ expected 2 parameters
```
For the most part, the current code performs similarly, although it
differs in some particulars. I'll be nice to have these tests for
judging future changes, as well.
First, we keep a `CoerceMany` now to find the LUB of all the break
expressions. Second, this `CoerceMany` is actually an
`Option<CoerceMany>`, and we store `None` for loops where "break with an
expression" is disallowed. This avoids silly duplicate errors about a
type mismatch, since the loops pass already reports an error that the
break cannot have an expression. Finally, since we now detect an invalid
break target during HIR lowering, refactor `find_loop` to be infallible.
Adjust tests as needed:
- some spans from breaks are slightly different
- break up a single loop into multiple since `CoerceMany` silences
redundant and derived errors
- add a ui test that we only give on error for loop-break-value
macros: improve `Span`'s expansion information
This PR improves `Span`'s expansion information. More specifically:
- It refactors AST node span construction to preserve expansion information.
- Today, we only use the underlying tokens' `BytePos`s, throwing away the `ExpnId`s.
- This improves the accuracy of AST nodes' expansion information, fixing #30506.
- It refactors `span.expn_id: ExpnId` to `span.ctxt: SyntaxContext` and removes `ExpnId`.
- This gives all tokens as much hygiene information as `Ident`s.
- This is groundwork for procedural macros 2.0 `TokenStream` API.
- This is also groundwork for declarative macros 2.0, which will need this hygiene information for some non-`Ident` tokens.
- It simplifies processing of spans' expansion information throughout the compiler.
- It fixes#40649.
- It fixes#39450 and fixes part of #23480.
r? @nrc
Clarify suggetion for field used as method
Instead of
```rust
error: no method named `src_addr` found for type `&wire::ipv4::Repr` in the current scope
--> src/wire/ipv4.rs:409:34
|
409 | packet.set_src_addr(self.src_addr());
| ^^^^^^^^
|
note: did you mean to write `self.src_addr`?
--> src/wire/ipv4.rs:409:34
|
409 | packet.set_src_addr(self.src_addr());
| ^^^^^^^^
```
present
```rust
error: no method named `src_addr` found for type `&wire::ipv4::Repr` in the current scope
--> src/wire/ipv4.rs:409:34
|
409 | packet.set_src_addr(self.src_addr());
| ^^^^^^^^ field, not a method
|
= help: did you mean to write `self.src_addr` instead of `self.src_addr(...)`?
```
Fix#38321.
This converts all of borrowck's `mut` suggestions to a new
`mc::ImmutabilityBlame` API instead of the current mix of various hacks.
Fixes#35937.
Fixes#40823.
* Point at where the token was expected instead of the last token
successfuly parsed.
* Only show `unexpected token` if the next char and the unexpected token
don't have the same span.
* Change some cfail and pfail tests to ui test.
* Don't show all possible tokens in span label if they are more than 6.
```rust
error: expected one of `.`, `;`, `?`, `}`, or an operator, found `)`
--> $DIR/token-error-correct-3.rs:29:9
|
25 | foo()
| - expected one of `.`, `;`, `?`, `}`, or an operator after this
...
29 | } else {
| ^ unexpected token
```
```rust
struct S;
impl S {
pub hello_method(&self) {
println!("Hello");
}
}
fn main() { S.hello_method(); }
```
```rust
error: can't qualify macro invocation with `pub`
--> file.rs:3:4
|
3 | pub hello_method(&self) {
| ^^^- - expected `!` here for a macro invocation
| |
| did you mean to write `fn` here for a method declaration?
|
= help: try adjusting the macro to put `pub` inside the invocation
```
Given the following statement
```rust
pub (a) fn afn() {}
```
Provide the following diagnostic:
```rust
error: incorrect restriction in `pub`
--> file.rs:15:1
|
15 | pub (a) fn afn() {}
| ^^^^^^^
|
= help: some valid visibility restrictions are:
`pub(crate)`: visible only on the current crate
`pub(super)`: visible only in the current module's parent
`pub(in path::to::module)`: visible only on the specified path
help: to make this visible only to module `a`, add `in` before the path:
| pub (in a) fn afn() {}
```
Remove cruft from old `pub(path)` syntax.
Point to let when modifying field of immutable variable
Point at the immutable local variable when trying to modify one of its
fields.
Given a file:
```rust
struct Foo {
pub v: Vec<String>
}
fn main() {
let f = Foo { v: Vec::new() };
f.v.push("cat".to_string());
}
```
present the following output:
```
error: cannot borrow immutable field `f.v` as mutable
--> file.rs:7:13
|
6 | let f = Foo { v: Vec::new() };
| - this should be `mut`
7 | f.v.push("cat".to_string());
| ^^^
error: aborting due to previous error
```
Fix#27593.
Point out correct turbofish usage on `Foo<Bar<Baz>>`
Whenever we parse a chain of binary operations, as long as the first
operation is `<` and the subsequent operations are either `>` or `<`,
present the following diagnostic help:
use `::<...>` instead of `<...>` if you meant to specify type arguments
This will lead to spurious recommendations on situations like
`2 < 3 < 4` but should be clear from context that the help doesn't apply
in that case.
Fixes#40396.
Whenever we parse a chain of binary operations, as long as the first
operation is `<` and the subsequent operations are either `>` or `<`,
present the following diagnostic help:
use `::<...>` instead of `<...>` if you meant to specify type arguments
This will lead to spurious recommendations on situations like
`2 < 3 < 4` but should be clear from context that the help doesn't apply
in that case.
Point at the immutable local variable when trying to modify one of its
fields.
Given a file:
```rust
struct Foo {
pub v: Vec<String>
}
fn main() {
let f = Foo { v: Vec::new() };
f.v.push("cat".to_string());
}
```
present the following output:
```
error: cannot borrow immutable field `f.v` as mutable
--> file.rs:7:13
|
6 | let f = Foo { v: Vec::new() };
| - this should be `mut`
7 | f.v.push("cat".to_string());
| ^^^
error: aborting due to previous error
```
fix#40294 obligation cause.body_id is not always a NodeExpr
Hello!
This fixes#40294 and moves tests related to #38812 to a much more sensible directory.
Thanks to @nikomatsakis and @eddyb
Fix suggestion span error with a line containing multibyte characters
This PR fixes broken suggestions caused by multibyte characters.
e.g. for this code, rustc provides a broken suggestion ([playground](https://is.gd/DWGLu7)):
```rust
fn main() {
let tup = (1,);
println!("☃{}", tup[0]);
}
```
```
error: cannot index a value of type `({integer},)`
--> <anon>:3:21
|
3 | println!("☃{}", tup[0]);
| ^^^^^^
|
help: to access tuple elements, use tuple indexing syntax as shown
| println!("☃{}"tup.00]);
error: aborting due to previous error
```
`CodeSuggestion::splice_lines` is misusing `Loc.col` (`CharPos`) as a byte offset when slicing source.
When declaring nested unsafe blocks (`unsafe {unsafe {}}`) that trigger
the "unnecessary `unsafe` block" error, point out the enclosing `unsafe
block` or `unsafe fn` that makes it unnecessary.
Group "missing variable bind" spans in `or` matches and clarify wording
for the two possible cases: when a variable from the first pattern is
not in any of the subsequent patterns, and when a variable in any of the
other patterns is not in the first one.
Before:
```
error[E0408]: variable `a` from pattern #1 is not bound in pattern #2
--> file.rs:10:23
|
10 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => { println!("{:?}", a); }
| ^^^^^^^^^^^ pattern doesn't bind `a`
error[E0408]: variable `b` from pattern #2 is not bound in pattern #1
--> file.rs:10:32
|
10 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => { println!("{:?}", a); }
| ^ pattern doesn't bind `b`
error[E0408]: variable `a` from pattern #1 is not bound in pattern #3
--> file.rs:10:37
|
10 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => { println!("{:?}", a); }
| ^^^^^^^^ pattern doesn't bind `a`
error[E0408]: variable `d` from pattern #1 is not bound in pattern #3
--> file.rs:10:37
|
10 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => { println!("{:?}", a); }
| ^^^^^^^^ pattern doesn't bind `d`
error[E0408]: variable `c` from pattern #3 is not bound in pattern #1
--> file.rs:10:43
|
10 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => { println!("{:?}", a); }
| ^ pattern doesn't bind `c`
error[E0408]: variable `d` from pattern #1 is not bound in pattern #4
--> file.rs:10:48
|
10 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => { println!("{:?}", a); }
| ^^^^^^^^ pattern doesn't bind `d`
error: aborting due to 6 previous errors
```
After:
```
error[E0408]: variable `a` is not bound in all patterns
--> file.rs:20:37
|
20 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => {
intln!("{:?}", a); }
| - ^^^^^^^^^^^ ^^^^^^^^ - variable
t in all patterns
| | | |
| | | pattern doesn't bind `a`
| | pattern doesn't bind `a`
| variable not in all patterns
error[E0408]: variable `d` is not bound in all patterns
--> file.rs:20:37
|
20 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => {
intln!("{:?}", a); }
| - - ^^^^^^^^ ^^^^^^^^ pattern
esn't bind `d`
| | | |
| | | pattern doesn't bind `d`
| | variable not in all patterns
| variable not in all patterns
error[E0408]: variable `b` is not bound in all patterns
--> file.rs:20:37
|
20 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => {
intln!("{:?}", a); }
| ^^^^^^^^^^^ - ^^^^^^^^ ^^^^^^^^ pattern
esn't bind `b`
| | | |
| | | pattern doesn't bind `b`
| | variable not in all patterns
| pattern doesn't bind `b`
error[E0408]: variable `c` is not bound in all patterns
--> file.rs:20:48
|
20 | T::T1(a, d) | T::T2(d, b) | T::T3(c) | T::T4(a) => {
intln!("{:?}", a); }
| ^^^^^^^^^^^ ^^^^^^^^^^^ - ^^^^^^^^ pattern
esn't bind `c`
| | | |
| | | variable not in all
tterns
| | pattern doesn't bind `c`
| pattern doesn't bind `c`
error: aborting due to 4 previous errors
```
* Have only one presentation for binding consistency errors
* Point to same binding in multiple patterns when possible
* Check inconsistent bindings in all arms
* Simplify wording of diagnostic message
* Sort emition and spans of binding errors for deterministic output
transition borrowck to visit all **bodies** and not item-likes
This is a better structure for incremental compilation and also more compatible with the eventual borrowck mir. It also fixes#38520 as a drive-by fix.
r? @eddyb
Tracking issue: https://github.com/rust-lang/rust/issues/40180
This calling convention can be used for definining interrupt handlers on
32-bit and 64-bit x86 targets. The compiler then uses `iret` instead of
`ret` for returning and ensures that all registers are restored to their
original values.
Usage:
```
extern "x86-interrupt" fn handler(stack_frame: &ExceptionStackFrame) {…}
```
for interrupts and exceptions without error code and
```
extern "x86-interrupt" fn page_fault_handler(stack_frame: &ExceptionStackFrame,
error_code: u64) {…}
```
for exceptions that push an error code (e.g., page faults or general
protection faults). The programmer must ensure that the correct version
is used for each interrupt.
For more details see the [LLVM PR][1] and the corresponding [proposal][2].
[1]: https://reviews.llvm.org/D15567
[2]: http://lists.llvm.org/pipermail/cfe-dev/2015-September/045171.html
These are some samples that I have been focusing on improving over
time. In this PR, I mainly want to stem the bleeding where we in some
cases we show an error that gives you no possible way to divine the
problem.
[MIR] SwitchInt Everywhere
Something I've been meaning to do for a very long while. This PR essentially gets rid of 3 kinds of conditional branching and only keeps the most general one - `SwitchInt`. Primary benefits are such that dealing with MIR now does not involve dealing with 3 different ways to do conditional control flow. On the other hand, constructing a `SwitchInt` currently requires more code than what previously was necessary to build an equivalent `If` terminator. Something trivially "fixable" with some constructor methods somewhere (MIR needs stuff like that badly in general).
Some timings (tl;dr: slightly faster^1 (unexpected), but also uses slightly more memory at peak (expected)):
^1: Not sure if the speed benefits are because of LLVM liking the generated code better or the compiler itself getting compiled better. Either way, its a net benefit. The CORE and SYNTAX timings done for compilation without optimisation.
```
AFTER:
Building stage1 std artifacts (x86_64-unknown-linux-gnu -> x86_64-unknown-linux-gnu)
Finished release [optimized] target(s) in 31.50 secs
Finished release [optimized] target(s) in 31.42 secs
Building stage1 compiler artifacts (x86_64-unknown-linux-gnu -> x86_64-unknown-linux-gnu)
Finished release [optimized] target(s) in 439.56 secs
Finished release [optimized] target(s) in 435.15 secs
CORE: 99% (24.81 real, 0.13 kernel, 24.57 user); 358536k resident
CORE: 99% (24.56 real, 0.15 kernel, 24.36 user); 359168k resident
SYNTAX: 99% (49.98 real, 0.48 kernel, 49.42 user); 653416k resident
SYNTAX: 99% (50.07 real, 0.58 kernel, 49.43 user); 653604k resident
BEFORE:
Building stage1 std artifacts (x86_64-unknown-linux-gnu -> x86_64-unknown-linux-gnu)
Finished release [optimized] target(s) in 31.84 secs
Building stage1 compiler artifacts (x86_64-unknown-linux-gnu -> x86_64-unknown-linux-gnu)
Finished release [optimized] target(s) in 451.17 secs
CORE: 99% (24.66 real, 0.20 kernel, 24.38 user); 351096k resident
CORE: 99% (24.36 real, 0.17 kernel, 24.18 user); 352284k resident
SYNTAX: 99% (52.24 real, 0.56 kernel, 51.66 user); 645544k resident
SYNTAX: 99% (51.55 real, 0.48 kernel, 50.99 user); 646428k resident
```
cc @nikomatsakis @eddyb
improve error message when two-arg assert_eq! receives a trailing comma
Previously, `assert_eq!(left, right,)` (respectively, `assert_ne!(left,
right,)`; note the trailing comma) would result in a confusing "requires
at least a format string argument" error. In reality, a format string is
optional, but the trailing comma puts us into the "match a token tree of
zero or more tokens" branch of the macro (in order to support the
optional format string), and passing the empty token tree into
`format_args!` results in the confusing error. If instead we match a
token tree of one or more tokens, we get a much more sensible
"unexpected end of macro invocation" error.
While we're here, fix up a stray space before a comma in the match
guards.
Resolves#39369.
-----
**Before:**
```
$ rustc scratch.rs
error: requires at least a format string argument
--> scratch.rs:2:5
|
2 | assert_eq!(1, 2,);
| ^^^^^^^^^^^^^^^^^^
|
= note: this error originates in a macro outside of the current crate
error: aborting due to previous error
```
**After:**
```
$ ./build/x86_64-unknown-linux-gnu/stage1/bin/rustc scratch.rs
error: unexpected end of macro invocation
--> scratch.rs:2:20
|
2 | assert_eq!(1, 2,);
| ^
```
Improve error message for uninferrable types #38812
Hello,
I tried to improve the error message for uninferrable types. The error code is `E0282`.
```rust
error[E0282]: type annotations needed
--> /home/cengizIO/issue38812.rs:2:11
|
2 | let x = vec![];
| - ^^^^^^ cannot infer type for `T`
| |
| consider giving `x` a type
|
= note: this error originates in a macro outside of the current crate
```
and
```rust
error[E0282]: type annotations needed
--> /home/cengizIO/issue38812.rs:2:15
|
2 | let (x,) = (vec![],);
| ---- ^^^^^^ cannot infer type for `T`
| |
| consider giving a type to pattern
|
= note: this error originates in a macro outside of the current crate
```
Rust compiler now tries to find uninferred `local`s with type `_` and adds them into the error message.
I'm probably wrong on wording that I used. Please feel free to suggest better alternatives.
Thanks @nikomatsakis for mentoring 🍺
Any comments/feedback is more than welcome!
Thank you
Previously, `assert_eq!(left, right,)` (respectively, `assert_ne!(left,
right,)`; note the trailing comma) would result in a confusing "requires
at least a format string argument" error. In reality, a format string is
optional, but the trailing comma puts us into the "match a token tree of
zero or more tokens" branch of the macro (in order to support the
optional format string), and passing the empty token tree into
`format_args!` results in the confusing error. If instead we match a
token tree of one or more tokens, we get a much more sensible
"unexpected end of macro invocation" error.
While we're here, fix up a stray space before a comma in the match
guards.
Resolves#39369.
This is the full and proper fix for #32330. This also makes some effort
to give a nice error message (as evidenced by the `ui` test), sending
users over to the tracking issue for a full explanation.
Don't suggest to use things which weren't found either
Fixes#38054
The best code I can come up with, suggestions are welcome.
Basically, removing ```. Did you mean to use `DoesntExist1`?``` in the code below, because it is useless.
```rust
error[E0432]: unresolved import `DoesntExist1`
--> src/lib.rs:1:5
|
1 | use DoesntExist1;
| ^^^^^^^^^^^^ no `DoesntExist1` in the root
error[E0432]: unresolved import `DoesntExist2`
--> src/lib.rs:2:5
|
2 | use DoesntExist2;
| ^^^^^^^^^^^^ no `DoesntExist2` in the root. Did you mean to use `DoesntExist1`?
```
Expand derive macros in the MacroExpander
This removes the expand_derives function, and sprinkles the functionality throughout the Invocation Collector, Expander and Resolver.
Fixes https://github.com/rust-lang/rust/issues/39326
r? @jseyfried
Previously, the note/message for the source of a lint being the command
line unconditionally named the individual lint, even if the actual
command specified a lint group (e.g., `-D warnings`); here, we take note
of the actual command options so we can be more specific.
This remains in the matter of #36846.
Warning or error messages set via a lint group attribute
(e.g. `#[deny(warnings)]`) should still make it clear which individual
lint (by name) was triggered, similarly to how we include "on by
default" language for default lints. This—and, while we're here, the
existing "on by default" language—can be tucked into a note rather than
cluttering the main error message. This occasions the slightest of
refactorings (we now have to get the diagnostic-builder with the main
message first, before matching on the lint source).
This is in the matter of #36846.
Add clearer error message using `&str + &str`
This is the first part of #39018. One of the common things for new users
coming from more dynamic languages like JavaScript, Python or Ruby is to
use `+` to concatenate strings. However, this doesn't work that way in
Rust unless the first type is a `String`. This commit adds a check for
this use case and outputs a new error as well as a suggestion to guide
the user towards the desired behavior. It also adds a new test case to
test the output of the error.
Privatize constructors of tuple structs with private fields
This PR implements the strictest version of such "privatization" - it just sets visibilities for struct constructors, this affects everything including imports.
```
visibility(struct_ctor) = min(visibility(struct), visibility(field_1), ..., visibility(field_N))
```
Needs crater run before proceeding.
Resolves https://github.com/rust-lang/rfcs/issues/902
r? @nikomatsakis
This is the first part of #39018. One of the common things for new users
coming from more dynamic languages like JavaScript, Python or Ruby is to
use `+` to concatenate strings. However, this doesn't work that way in
Rust unless the first type is a `String`. This commit adds a check for
this use case and outputs a new error as well as a suggestion to guide
the user towards the desired behavior. It also adds a new test case to
test the output of the error.
rustc: Remove all "consider using an explicit lifetime parameter" suggestions
These give so many incorrect suggestions that having them is
detrimental to the user experience. The compiler should not be
suggesting changes to the code that are wrong - it is infuriating: not
only is the compiler telling you that _you don't understand_ borrowing,
_the compiler itself_ appears to not understand borrowing. It does not
inspire confidence.
r? @nikomatsakis
These give so many incorrect suggestions that having them is
detrimental to the user experience. The compiler should not be
suggesting changes to the code that are wrong - it is infuriating: not
only is the compiler telling you that _you don't understand_ borrowing,
_the compiler itself_ appears to not understand borrowing. It does not
inspire confidence.
Point to immutable borrow arguments and fields when trying to use them as
mutable borrows. Add label to primary span on "cannot borrow as mutable"
errors.
Present the following output when trying to access an immutable borrow's
field as mutable:
```
error[E0389]: cannot borrow data mutably in a `&` reference
--> $DIR/issue-38147-1.rs:27:9
|
26 | fn f(&self) {
| ----- use `&mut self` here to make mutable
27 | f.s.push('x');
| ^^^ assignment into an immutable reference
```
And the following when trying to access an immutable struct field as mutable:
```
error: cannot borrow immutable borrowed content `*self.s` as mutable
--> $DIR/issue-38147-3.rs:17:9
|
12 | s: &'a String
| ------------- use `&'a mut String` here to make mutable
...|
16 | fn f(&self) {
| ----- use `&mut self` here to make mutable
17 | self.s.push('x');
| ^^^^^^ cannot borrow as mutable
```
Use multiline Diagnostic for candidate in other module
```
error[E0574]: expected struct, variant or union type, found enum `Result`
--> $DIR/issue-16058.rs:19:9
|
19 | Result {
| ^^^^^^ not a struct, variant or union type
|
= help: possible better candidates are found in other modules, you can import them into scope:
`use std::fmt::Result;`
`use std::io::Result;`
`use std:🧵:Result;`
error: aborting due to previous error
```
E0034: provide disambiguated syntax for candidates
For a given file
```rust
trait A { fn foo(&self) {} }
trait B : A { fn foo(&self) {} }
fn bar<T: B>(a: &T) {
a.foo()
}
```
provide the following output
```
error[E0034]: multiple applicable items in scope
--> file.rs:6:5
|
6 | a.foo(1)
| ^^^ multiple `foo` found
|
note: candidate #1 is defined in the trait `A`
--> file.rs:2:11
|
2 | trait A { fn foo(&self, a: usize) {} }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to use it here write `A::foo(&a, 1)` instead
--> file.rs:6:5
|
6 | a.foo(1)
| ^^^
note: candidate #2 is defined in the trait `B`
--> file.rs:3:15
|
3 | trait B : A { fn foo(&self, a: usize) {} }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to use it here write `B::foo(&a, 1)` instead
--> file.rs:6:5
|
6 | a.foo(1)
| ^^^
```
Fix#37767.
Fix lint attributes on non-item nodes.
Currently, late lint checking uses two HIR visitors: LateContext and
IdVisitor. IdVisitor only overrides visit_id, and for each node searches
for builtin lints previously added to the session; LateContext overrides
a number of methods, and runs late lints. When LateContext encounters an
item, it first has IdVisitor walk everything in it except nested items
(OnlyBodies), then recurses into it itself - i.e. there are two separate
walks.
Aside from apparently being unnecessary, this separation prevents lint
attributes (allow/deny/warn) on non-item HIR nodes from working
properly. Test case:
```rust
// generates warning without this change
fn main() { #[allow(unreachable_code)] loop { break; break; } }
```
LateContext contains logic to merge attributes seen into the current lint
settings while walking (with_lint_attrs), but IdVisitor does not. So
such attributes will affect late lints (because they are called from
LateContext), and if the node contains any items within it, they will
affect builtin lints within those items (because that IdVisitor is run
while LateContext is within the attributed node), but otherwise the
attributes will be ignored for builtin lints.
This change simply removes IdVisitor and moves its visit_id into
LateContext itself. Hopefully this doesn't break anything...
Also added walk calls to visit_lifetime and visit_lifetime_def
respectively, so visit_lifetime_def will recurse into the lifetime and
visit_lifetime will recurse into the name. In principle this could
confuse lint plugins. This is "necessary" because walk_lifetime calls
visit_id on the lifetime; of course, an alternative would be directly
calling visit_id (which would require manually iterating over the
lifetimes in visit_lifetime_def), but that seems less clean.