resolve: Improve import failure detection and lay groundwork for RFC 1422
This PR improves import failure detection and lays some groundwork for RFC 1422.
More specifically, it
- Avoids recomputing the resolution of an import directive's module path.
- Refactors code in `resolve_imports` that does not scale to the arbitrarily many levels of visibility that will be required by RFC 1422.
- Replaces `ModuleS`'s fields `public_glob_count`, `private_glob_count`, and `resolved_globs` with a list of glob import directives `globs`.
- Replaces `NameResolution`'s fields `pub_outstanding_references` and `outstanding_references` with a field `single_imports` of a newly defined type `SingleImports`.
- Improves import failure detection by detecting cycles that include single imports (currently, only cycles of globs are detected). This fixes#32119.
r? @nikomatsakis
resolve: Minimize hacks in name resolution of primitive types
When resolving the first unqualified segment in a path with `n` segments and `n - 1` associated item segments, e.g. (`a` or `a::assoc` or `a::assoc::assoc` etc) try to resolve `a` without considering primitive types first. If the "normal" lookup fails or results in a module, then try to resolve `a` as a primitive type as a fallback.
This way backward compatibility is respected, but the restriction from E0317 can be lifted, i.e. primitive names mostly can be shadowed like any other names.
Furthermore, if names of primitive types are [put into prelude](https://github.com/petrochenkov/rust/tree/prim2) (now it's possible to do), then most of names will be resolved in conventional way and amount of code relying on this fallback will be greatly reduced. Although, it's not entirely convenient to put them into prelude right now due to temporary conflicts like `use prelude::v1::*; use usize;` in libcore/libstd, I'd better wait for proper glob shadowing before doing it.
I wish the `no_prelude` attribute were unstable as intended :(
cc @jseyfried @arielb1
r? @eddyb
Disallow methods from traits that are not in scope
This PR only allows a trait method to be used if the trait is in scope (fixes#31379).
This is a [breaking-change]. For example, the following would break:
```rust
mod foo {
pub trait T { fn f(&self) {} }
impl T for () {}
}
mod bar { pub use foo::T; }
fn main() {
pub use bar::*;
struct T; // This shadows the trait `T`,
().f() // making this an error.
}
```
r? @nikomatsakis
The initial wording does not make sense due to an extra 'to'.
There are two potential candidates we can change this to:
- 'you can import it into scope'
- 'to import it into scope'
In keeping the changes minimal, we choose the first, as this is more in line with the grammar of the extended candidates help message.
Fix name resolution in lexical scopes
Currently, `resolve_item_in_lexical_scope` does not check the "ribs" (type parameters and local variables). This can allow items that should be shadowed by type parameters to be named.
For example,
```rust
struct T { i: i32 }
fn f<T>() {
let t = T { i: 0 }; // This use of `T` resolves to the struct, not the type parameter
}
mod Foo {
pub fn f() {}
}
fn g<Foo>() {
Foo::f(); // This use of `Foo` resolves to the module, not the type parameter
}
```
This PR changes `resolve_item_in_lexical_scope` so that it fails when the item is shadowed by a rib (fixes#32120).
This is a [breaking-change], but it looks unlikely to cause breakage in practice.
r? @nikomatsakis
Forbid glob-importing from a type alias
This PR forbids glob-importing from a type alias or trait (fixes#30560):
```rust
type Alias = ();
use Alias::*; // This is currently allowed but shouldn't be
```
This is a [breaking-change]. Since the disallowed glob imports don't actually import anything, any breakage can be fixed by removing the offending glob import.
r? @alexcrichton
Fix a regression in import resolution
This fixes#32089 (caused by #31726) by deducing that name resolution has failed (as opposed to being determinate) in more cases.
r? @nikomatsakis
This PR privacy checks paths as they are resolved instead of in `librustc_privacy` (fixes#12334 and fixes#31779). This removes the need for the `LastPrivate` system introduced in PR #9735, the limitations of which cause #31779.
This PR also reports privacy violations in paths to intra- and inter-crate items the same way -- it always reports the first inaccessible segment of the path.
Since it fixes#31779, this is a [breaking-change]. For example, the following code would break:
```rust
mod foo {
pub use foo::bar::S;
mod bar { // `bar` should be private to `foo`
pub struct S;
}
}
impl foo::S {
fn f() {}
}
fn main() {
foo::bar::S::f(); // This is now a privacy error
}
```
r? @alexcrichton
This fixes a bug (#31845) introduced in #31105 in which lexical scopes contain items from all anonymous module ancestors, even if the path to the anonymous module includes a normal module:
```rust
fn f() {
fn g() {}
mod foo {
fn h() {
g(); // This erroneously resolves on nightly
}
}
}
```
This is a [breaking-change] on nightly but not on stable or beta.
r? @nikomatsakis
The standard library doesn't depend on rustc_bitflags, so move it to explicit
dependencies on all other crates. Additionally, the arena/fmt_macros deps could
be dropped from libsyntax.
The standard library doesn't depend on rustc_bitflags, so move it to explicit
dependencies on all other crates. Additionally, the arena/fmt_macros deps could
be dropped from libsyntax.
Now that #31461 is merged, a failing resolution can never become indeterminate or succeed, so we no longer have to keep trying to resolve failing import directives.
r? @nrc
This commit adds functionality that allows the name resolution pass
to search for entities (traits/types/enums/structs) by name, in
order to show recommendations along with the errors.
For now, only E0405 and E0412 have suggestions attached, as per the
request in bug #21221, but it's likely other errors can also benefit
from the ability to generate suggestions.
This commit adds functionality that allows the name resolution pass
to search for entities (traits/types/enums/structs) by name, in
order to show recommendations along with the errors.
For now, only E0405 and E0412 have suggestions attached, as per the
request in bug #21221, but it's likely other errors can also benefit
from the ability to generate suggestions.
This PR fixes two unrelated diagnostics bugs in resolve.
First, it reports privacy errors for an import only after the import resolution is determined, fixing #31402.
Second, it expands the per-module map from block ids to anonymous modules so that it also maps module declarations ids to modules, and it uses this map to in `with_scope` to fix#31644.
r? @nrc
r? @brson
cc @alexcrichton
I still need to add error code explanation test with this, but I can't figure out a way to generate the `.md` files in order to test example source codes.
Will fix#27328.
Refactor away resolve_name_in_module in resolve_imports.rs
Rewrite and improve the core name resolution procedure in NameResolution::result and Module::resolve_name
Refactor the duplicate checking code into NameResolution::try_define
This PR refactors away `Module`'s `external_module_children` and instead puts `extern crate` declarations in `children` like other items, simplifying duplicate checking and name resolution.
This PR also allows values to share a name with extern crates, which are only defined in the type namespace. Other than that, it is a pure refactoring.
r? @nrc
This fixes an ICE introduced by #31065 that occurs when a path cannot be resolved because of a certain class of unresolved import (`Indeterminate` imports).
For example, this currently causes an ICE:
```rust
mod foo { pub use self::*; }
fn main() { foo::f() }
```
r? @nrc
We no longer require `use` and `extern crate` items to precede other items in modules thanks to [RFC #385](https://github.com/rust-lang/rfcs/pull/385), but we still require `use` and `extern crate` items to precede statements in blocks (other items can appear anywhere in a block).
I think that this is a needless distinction between imports and other items that contradicts the intent of the RFC.
This commit removes the `-D warnings` flag being passed through the makefiles to
all crates to instead be a crate attribute. We want these attributes always
applied for all our standard builds, and this is more amenable to Cargo-based
builds as well.
Note that all `deny(warnings)` attributes are gated with a `cfg(stage0)`
attribute currently to match the same semantics we have today
This fixes#23880, a scoping bug in which items in a block are shadowed by local variables and type parameters that are in scope.
After this PR, an item in a block will shadow any local variables or type parameters above the item in the scope hierarchy. Items in a block will continue to be shadowed by local variables in the same block (even if the item is defined after the local variable).
This is a [breaking-change]. For example, the following code breaks:
```rust
fn foo() {
let mut f = 1;
{
fn f() {}
f += 1; // This will resolve to the function instead of the local variable
}
}
This fixes a bug in which items in a block are shadowed by local variables and type parameters that are in scope.
It is a [breaking-change]. For example, the following code breaks:
```rust
fn foo() {
let mut f = 1;
{
fn f() {}
f += 1; // This will now resolve to the function instead of the local variable
}
}
```
Any breakage can be fixed by renaming the item that is no longer shadowed.
This PR adds some minor error correction to the parser - if there is a missing ident, we recover and carry on. It also makes compilation more robust so that non-fatal errors (which is still most of them, unfortunately) in parsing do not cause us to abort compilation. The effect is that a program with a missing or incorrect ident can get all the way to type checking.
This commit removes the `-D warnings` flag being passed through the makefiles to
all crates to instead be a crate attribute. We want these attributes always
applied for all our standard builds, and this is more amenable to Cargo-based
builds as well.
Note that all `deny(warnings)` attributes are gated with a `cfg(stage0)`
attribute currently to match the same semantics we have today
I tried to add an inline `span_suggestion()` to the error as well, but since generics don't have their own span it becomes too fragile/complicated to work.
r? @steveklabnik
fixes#19477
Fix a bug allowing an item and an external crate to collide so long as the external crate is declared after the item. For example,
```rust
mod core { pub fn f() {} } // This would be an error if it followed the `extern crate`
extern crate core; // This declaration is shadowed by the preceding module
fn main() { core::f(); }
```
This is a [breaking-change], but it looks unlikely to cause breakage in practice, and any breakage can be fixed by removing colliding `extern crate` declarations, which are shadowed and hence unused.
Add note when item accessed from module via `m.i` rather than `m::i`.
(I tried to make this somewhat future-proofed, in that the `UnresolvedNameContext` could be expanded in the future with other cases besides paths that are known to be modules.)
This supersedes PR #30356 ; since I'm responsible for a bunch of new code here, someone else should review it. :)
This fixes a bug in which unused imports can get wrongly marked as used when checking for unused qualifications in `resolve_path` (issue #30078), and it removes unused imports that were previously undetected because of the bug.
We can now handle name resolution errors and get past type checking (if we're a bit lucky). This is the first step towards doing code completion for partial programs (we need error recovery in the parser and early access to save-analysis).
Instead of `ast::Ident`, bindings, paths and labels in HIR now keep a new structure called `hir::Ident` containing mtwt-renamed `name` and the original not-renamed `unhygienic_name`. `name` is supposed to be used by default, `unhygienic_name` is rarely used.
This is not ideal, but better than the status quo for two reasons:
- MTWT tables can be cleared immediately after lowering to HIR
- This is less bug-prone, because it is impossible now to forget applying `mtwt::resolve` to a name. It is still possible to use `name` instead of `unhygienic_name` by mistake, but `unhygienic_name`s are used only in few very special circumstances, so it shouldn't be a problem.
Besides name resolution `unhygienic_name` is used in some lints and debuginfo. `unhygienic_name` can be very well approximated by "reverse renaming" `token::intern(name.as_str())` or even plain string `name.as_str()`, except that it would break gensyms like `iter` in desugared `for` loops. This approximation is likely good enough for lints and debuginfo, but not for name resolution, unfortunately (see https://github.com/rust-lang/rust/issues/27639), so `unhygienic_name` has to be kept.
cc https://github.com/rust-lang/rust/issues/29782
r? @nrc
Fixes https://github.com/rust-lang/rust/issues/28692
Fixes https://github.com/rust-lang/rust/issues/28992
Fixes some other similar issues (see the tests)
[breaking-change], needs crater run (cc @brson or @alexcrichton )
The pattern with parens `UnitVariant(..)` for unit variants seems to be popular in rustc (see the second commit), but mostly used by one person (@nikomatsakis), according to git blame. If it causes breakage on crates.io I'll add an exceptional case for it.
Fixes#13677
This does the same sort of suggestion for misspelt macros that we already do for misspelt identifiers.
Example. Compiling this program:
```rust
macro_rules! foo {
($e:expr) => ( $e )
}
fn main() {
fob!("hello!");
}
```
gives the following error message:
```
/Users/mcp/temp/test.rs:7:5: 7:8 error: macro undefined: 'fob!'
/Users/mcp/temp/test.rs:7 fob!("hello!");
^~~
/Users/mcp/temp/test.rs:7:5: 7:8 help: did you mean `foo`?
/Users/mcp/temp/test.rs:7 fob!("hello!");
```
I had to move the levenshtein distance function into libsyntax for this. Maybe this should live somewhere else (some utility crate?), but I couldn't find a crate to put it in that is imported by libsyntax and the other rustc crates.