Add lint for unused macros
Addresses parts of #34938, to add a lint for unused macros.
We now output warnings by default when we encounter a macro that we didn't use for expansion.
Issues to be resolved before this PR is ready for merge:
- [x] fix the NodeId issue described above
- [x] remove all unused macros from rustc and the libraries or set `#[allow(unused_macros)]` next to them if they should be kept for some reason. This is needed for successful boostrap and bors to accept the PR. -> #41934
- [x] ~~implement the full extent of #34938, that means the macro match arm checking as well.~~ *let's not do this for now*
This commit extends the current unused macro linter
to support directives like #[allow(unused_macros)]
or #[deny(unused_macros)] directly next to the macro
definition, or in one of the modules the macro is
inside. Before, we only supported such directives
at a per crate level, due to the crate's NodeId
being passed to session.add_lint.
We also had to implement handling of the macro's
NodeId in the lint visitor.
Suggest using enum when a variant is used as a type
Given a file:
```rust
enum Fruit {
Apple(i64),
Orange(i64),
}
fn should_return_fruit() -> Apple {
Apple(5)
}
```
Provide the following output:
```rust
error[E0412]: cannot find type `Apple` in this scope
--> file.rs:16:29
|
16 | fn should_return_fruit() -> Apple {
| ^^^^^ not found in this scope
|
help: there is an enum variant `Fruit::Apple`, did you mean to use `Fruit`?
--> file.rs:12:5
|
12 | Apple(i64),
| ^^^^^^^^^^
error[E0425]: cannot find function `Apple` in this scope
--> file.rs:17:5
|
17 | Apple(5)
| ^^^^^ not found in this scope
|
= help: possible candidate is found in another module, you can import it into scope:
`use Fruit::Apple;`
```
Fix#35675.
Given a file:
```rust
enum Fruit {
Apple(i64),
Orange(i64),
}
fn should_return_fruit() -> Apple {
Apple(5)
}
```
Provide the following output:
```rust
error[E0412]: cannot find type `Apple` in this scope
--> file.rs:16:29
|
16 | fn should_return_fruit() -> Apple {
| ^^^^^ not found in this scope
|
help: there is an enum variant `Fruit::Apple`, did you mean to use `Fruit`?
--> file.rs:12:5
|
12 | Apple(i64),
| ^^^^^^^^^^
error[E0425]: cannot find function `Apple` in this scope
--> file.rs:17:5
|
17 | Apple(5)
| ^^^^^ not found in this scope
|
= help: possible candidate is found in another module, you can import it into scope:
`use Fruit::Apple;`
```
Allow `use` macro imports to shadow global macros
Terminology:
- global scope: builtin macros, macros from the prelude, `#[macro_use]`, or `#![plugin(..)]`.
- legacy scope: crate-local `macro_rules!`.
- modern scope: `use` macro imports, `macro` (once implemented).
Today, the legacy scope can shadow the global scope (modulo RFC 1560 expanded shadowing restrictions). However, the modern scope cannot shadow or be shadowed by either the global or legacy scopes, leading to ambiguity errors.
This PR allows the modern scope to shadow the global scope (subject to some restrictions).
More specifically, a name in the global scope is as shadowable as a glob import in the module `self`. In other words, we imagine a special, implicit glob import in each module item:
```rust
mod foo {
#[lexical_only] // Not accessible via `foo::<name>`, like pre-RFC 1560 `use` imports.
#[shadowable_by_legacy_scope] // for back-compat
use <global_macros>::*;
}
```
r? @nrc
This commit deletes the internal liblog in favor of the implementation that
lives on crates.io. Similarly it's also setting a convention for adding crates
to the compiler. The main restriction right now is that we want compiler
implementation details to be unreachable from normal Rust code (e.g. requires a
feature), and by default everything in the sysroot is reachable via `extern
crate`.
The proposal here is to require that crates pulled in have these lines in their
`src/lib.rs`:
#![cfg_attr(rustbuild, feature(staged_api, rustc_private))]
#![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))]
This'll mean that by default they're not using these attributes but when
compiled as part of the compiler they do a few things:
* Mark themselves as entirely unstable via the `staged_api` feature and the
`#![unstable]` attribute.
* Allow usage of other unstable crates via `feature(rustc_private)` which is
required if the crate relies on any other crates to compile (other than std).
Forbid conflicts between macros 1.0 exports and macros 2.0 exports
This PR forbids for conflicts between `#[macro_export]`/`#[macro_reexport]` macro exports and `pub use` macro exports. For example,
```rust
// crate A:
pub use macros::foo;
//^ This is allowed today, will be forbidden by this PR.
// crate B:
extern crate A; // This triggers a confusing error today.
use A::foo; // This could refer to refer to either macro export in crate A.
```
r? @nrc
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
This commit searchs modules for macro suggestions.
It also removes imported macro_rules from macro_names,
and adds more corner case checks for which macros
should be suggested in specific contexts.
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`?
```
Partially implement RFC 1647 (`Self` in impl headers)
The name resolution part is easy, but the typeck part contains an unexpected problem.
It turns out that `Self` type *depends* on bounds and `where` clauses, so we need to convert them first to determine what the `Self` type is! If bounds/`where` clauses can refer to `Self` then we have a cyclic dependency.
This is required to support impls like this:
```
// Found in libcollections
impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> { .... }
^^^^^ associated type `Item` is found using information from bounds
```
I'm not yet sure how to resolve this issue.
One possible solution (that feels hacky) is to make two passes over generics - first collect predicates ignoring everything involving `Self`, then determine `Self`, then collect predicates again without ignoring anything. (Some kind of lazy on-demand checking or something looks like a proper solution.)
This patch in its current state doesn't solve the problem with `Self` in bounds, so the only observable things it does is improving error messages and supporting `impl Trait<Self> for Type {}`.
There's also a question about feature gating. It's non-trivial to *detect* "newly resolved" `Self`s to feature gate them, but it's simple to *enable* the new resolution behavior when the feature gate is already specified. Alternatively this can be considered a bug fix and merged without a feature gate.
cc https://github.com/rust-lang/rust/issues/38864
r? @nikomatsakis
cc @eddyb
Whitespace ignoring diff https://github.com/rust-lang/rust/pull/38920/files?w=1
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
```
* Add support for `#[proc_macro]`
* Reactivate `proc_macro` feature and gate `#[proc_macro_attribute]` under it
* Have `#![feature(proc_macro)]` imply `#![feature(use_extern_macros)]`,
error on legacy import of proc macros via `#[macro_use]`
resolve: Do not use "resolve"/"resolution" in error messages
Use less jargon-y wording instead.
`cannot find <struct> <S> in <this scope>` and `cannot find <struct> <S> in <module a::b>` are used for base messages (this also harmonizes nicely with "you can import it into scope" suggestions) and `not found in <this scope>` and `not found in <a::b>` are used for short labels in fall-back case.
I tweaked some other diagnostics to avoid using "resolve" (see, e.g., `librustc_resolve/macros.rs`), but haven't touched messages for imports.
Closes https://github.com/rust-lang/rust/issues/38750
r? @nrc
resolve: clean up the semantics of `self` in an import list
Change `self` in an import list `use foo::bar::{self, ...};` to import `bar` only in the type namespace. Today, `bar` is imported in every namespace in which `foo::bar` is defined.
This is a [breaking-change], see https://github.com/rust-lang/rust/issues/38293#issue-194817974 for examples of code that would break.
Fixes#38293.
r? @nrc
Remove not(stage0) from deny(warnings)
Historically this was done to accommodate bugs in lints, but there hasn't been a
bug in a lint since this feature was added which the warnings affected. Let's
completely purge warnings from all our stages by denying warnings in all stages.
This will also assist in tracking down `stage0` code to be removed whenever
we're updating the bootstrap compiler.
i128 and u128 support
Brings i128 and u128 support to nightly rust, behind a feature flag. The goal of this PR is to do the bulk of the work for 128 bit integer support. Smaller but just as tricky features needed for stabilisation like 128 bit enum discriminants are left for future PRs.
Rebased version of #37900, which in turn was a rebase + improvement of #35954 . Sadly I couldn't reopen#37900 due to github. There goes my premium position in the homu queue...
[plugin-breaking-change]
cc #35118 (tracking issue)
This commit introduces 128-bit integers. Stage 2 builds and produces a working compiler which
understands and supports 128-bit integers throughout.
The general strategy used is to have rustc_i128 module which provides aliases for iu128, equal to
iu64 in stage9 and iu128 later. Since nowhere in rustc we rely on large numbers being supported,
this strategy is good enough to get past the first bootstrap stages to end up with a fully working
128-bit capable compiler.
In order for this strategy to work, number of locations had to be changed to use associated
max_value/min_value instead of MAX/MIN constants as well as the min_value (or was it max_value?)
had to be changed to use xor instead of shift so both 64-bit and 128-bit based consteval works
(former not necessarily producing the right results in stage1).
This commit includes manual merge conflict resolution changes from a rebase by @est31.
Historically this was done to accommodate bugs in lints, but there hasn't been a
bug in a lint since this feature was added which the warnings affected. Let's
completely purge warnings from all our stages by denying warnings in all stages.
This will also assist in tracking down `stage0` code to be removed whenever
we're updating the bootstrap compiler.
Use `DefId`s instead of `NodeId`s for `pub(restricted)` visibilities
This is groundwork for hygiene 2.0, specifically privacy checking hygienic intercrate name resolutions.
r? @nrc
Allow legacy custom derive authors to disable warnings in downstream crates
This PR allows legacy custom derive authors to use a pre-deprecated method `registry.register_custom_derive()` instead of `registry.register_syntax_extension()` to avoid downstream deprecation warnings.
r? @nrc
annotate stricter lifetimes on LateLintPass methods to allow them to forward to a Visitor
this unblocks clippy (rustup blocked after #37918)
clippy has lots of lints that internally call an `intravisit::Visitor`, but the current lifetimes on `LateLintPass` methods conflicted with the required lifetimes (there was no connection between the HIR elements and the `TyCtxt`)
r? @Manishearth
For a given file
```rust
use std::*;
use std::{};
```
output the following warnings
```
warning: unused import: `use std::{};`, #[warn(unused_imports)] on by default
--> file.rs:2:1
|
2 | use std::{};
| ^^^^^^^^^^^^
warning: unused import: `std::*;`, #[warn(unused_imports)] on by default
--> file.rs:1:5
|
1 | use std::*;
| ^^^^^^^
```
Avoid loading needless proc-macro dependencies
Fixes#37958 when no proc-macros are exported; in particular, without `pub extern crate proc_macros;`, `#![feature(macro_reexport)]`, or `#![feature(use_extern_macros)]`.
I opened https://github.com/rust-lang/cargo/issues/3334 for exported proc macros.
r? @alexcrichton
This implements RFC 1624, tracking issue #37339.
- `FnCtxt` (in typeck) gets a stack of `LoopCtxt`s, which store the
currently deduced type of that loop, the desired type, and a list of
break expressions currently seen. `loop` loops get a fresh type
variable as their initial type (this logic is stolen from that for
arrays). `while` loops get `()`.
- `break {expr}` looks up the broken loop, and unifies the type of
`expr` with the type of the loop.
- `break` with no expr unifies the loop's type with `()`.
- When building MIR, `loop` loops no longer construct a `()` value at
termination of the loop; rather, the `break` expression assigns the
result of the loop. `while` loops are unchanged.
- `break` respects contexts in which expressions may not end with braced
blocks. That is, `while break { break-value } { while-body }` is
illegal; this preserves backwards compatibility.
- The RFC did not make it clear, but I chose to make `break ()` inside
of a `while` loop illegal, just in case we wanted to do anything with
that design space in the future.
This is my first time dealing with this part of rustc so I'm sure
there's plenty of problems to pick on here ^_^
Clean up `ast::Attribute`, `ast::CrateConfig`, and string interning
This PR
- removes `ast::Attribute_` (changing `Attribute` from `Spanned<Attribute_>` to a struct),
- moves a `MetaItem`'s name from the `MetaItemKind` variants to a field of `MetaItem`,
- avoids needlessly wrapping `ast::MetaItem` with `P`,
- moves string interning into `syntax::symbol` (`ast::Name` is a reexport of `symbol::Symbol` for now),
- replaces `InternedString` with `Symbol` in the AST, HIR, and various other places, and
- refactors `ast::CrateConfig` from a `Vec` to a `HashSet`.
r? @eddyb