Skip to content

Commit 6a3545e

Browse files
committed
Auto merge of #27439 - vberger:more_perseverant_resolve, r=nrc
(This is a second try at #26242. This time I think things should be ok.) The current algorithm handling import resolutions works sequentially, handling imports in the order they appear in the source file, and blocking/bailing on the first one generating an error/being unresolved. This can lead to situations where the order of the `use` statements can make the difference between "this code compiles" and "this code fails on an unresolved import" (see #18083 for example). This is especially true when considering glob imports. This PR changes the behaviour of the algorithm to instead try to resolve all imports in a module. If one fails, it is recorded and the next one is tried (instead of directly giving up). Also, all errors generated are stored (and not reported directly). The main loop of the algorithms guaranties that the algorithm will always finish: if a round of resolution does not resolve anything new, we are stuck and give up. At this point, the new version of the algorithm will display all errors generated by the last round of resolve. This way we are sure to not silence relevant errors or help messages, but also to not give up too early. **As a consequence, the import resolution becomes independent of the order in which the `use` statements are written in the source files.** I personally don't see any situations where this could be a problem, but this might need some thought. I passed `rpass` and `cfail` tests on my computer, and now am compiling a full stage2 compiler to ensure the crates reporting errors in my previous attempts still build correctly. I guess once I have checked it, this will need a crater run? Fixes #18083. r? @alexcrichton , cc @nrc @brson
2 parents dbe415a + 58e35d7 commit 6a3545e

File tree

7 files changed

+189
-54
lines changed

7 files changed

+189
-54
lines changed

src/librustc_resolve/lib.rs

+14-19
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
html_root_url = "http://doc.rust-lang.org/nightly/")]
2121

2222
#![feature(associated_consts)]
23+
#![feature(borrow_state)]
2324
#![feature(rc_weak)]
2425
#![feature(rustc_diagnostic_macros)]
2526
#![feature(rustc_private)]
@@ -176,7 +177,7 @@ pub enum ResolutionError<'a> {
176177
/// error E0431: `self` import can only appear in an import list with a non-empty prefix
177178
SelfImportOnlyInImportListWithNonEmptyPrefix,
178179
/// error E0432: unresolved import
179-
UnresolvedImport(Option<(&'a str, Option<&'a str>)>),
180+
UnresolvedImport(Option<(&'a str, &'a str)>),
180181
/// error E0433: failed to resolve
181182
FailedToResolve(&'a str),
182183
/// error E0434: can't capture dynamic environment in a fn item
@@ -359,8 +360,7 @@ fn resolve_error<'b, 'a:'b, 'tcx:'a>(resolver: &'b Resolver<'a, 'tcx>, span: syn
359360
}
360361
ResolutionError::UnresolvedImport(name) => {
361362
let msg = match name {
362-
Some((n, Some(p))) => format!("unresolved import `{}`{}", n, p),
363-
Some((n, None)) => format!("unresolved import (maybe you meant `{}::*`?)", n),
363+
Some((n, p)) => format!("unresolved import `{}`{}", n, p),
364364
None => "unresolved import".to_owned()
365365
};
366366
span_err!(resolver.session, span, E0432, "{}", msg);
@@ -539,8 +539,8 @@ enum ResolveResult<T> {
539539
}
540540

541541
impl<T> ResolveResult<T> {
542-
fn indeterminate(&self) -> bool {
543-
match *self { Indeterminate => true, _ => false }
542+
fn success(&self) -> bool {
543+
match *self { Success(_) => true, _ => false }
544544
}
545545
}
546546

@@ -732,7 +732,12 @@ impl Module {
732732
}
733733

734734
fn all_imports_resolved(&self) -> bool {
735-
self.imports.borrow().len() == self.resolved_import_count.get()
735+
if self.imports.borrow_state() == ::std::cell::BorrowState::Writing {
736+
// it is currently being resolved ! so nope
737+
false
738+
} else {
739+
self.imports.borrow().len() == self.resolved_import_count.get()
740+
}
736741
}
737742
}
738743

@@ -1815,19 +1820,9 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
18151820
let imports = module_.imports.borrow();
18161821
let import_count = imports.len();
18171822
if index != import_count {
1818-
let sn = self.session
1819-
.codemap()
1820-
.span_to_snippet((*imports)[index].span)
1821-
.unwrap();
1822-
if sn.contains("::") {
1823-
resolve_error(self,
1824-
(*imports)[index].span,
1825-
ResolutionError::UnresolvedImport(None));
1826-
} else {
1827-
resolve_error(self,
1828-
(*imports)[index].span,
1829-
ResolutionError::UnresolvedImport(Some((&*sn, None))));
1830-
}
1823+
resolve_error(self,
1824+
(*imports)[index].span,
1825+
ResolutionError::UnresolvedImport(None));
18311826
}
18321827

18331828
// Descend into children and anonymous children.

src/librustc_resolve/resolve_imports.rs

+61-28
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,11 @@ impl ImportResolution {
184184
}
185185
}
186186

187+
struct ImportResolvingError {
188+
span: Span,
189+
path: String,
190+
help: String,
191+
}
187192

188193
struct ImportResolver<'a, 'b:'a, 'tcx:'b> {
189194
resolver: &'a mut Resolver<'b, 'tcx>
@@ -208,15 +213,28 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
208213
i, self.resolver.unresolved_imports);
209214

210215
let module_root = self.resolver.graph_root.get_module();
211-
self.resolve_imports_for_module_subtree(module_root.clone());
216+
let errors = self.resolve_imports_for_module_subtree(module_root.clone());
212217

213218
if self.resolver.unresolved_imports == 0 {
214219
debug!("(resolving imports) success");
215220
break;
216221
}
217222

218223
if self.resolver.unresolved_imports == prev_unresolved_imports {
219-
self.resolver.report_unresolved_imports(module_root);
224+
// resolving failed
225+
if errors.len() > 0 {
226+
for e in errors {
227+
resolve_error(self.resolver,
228+
e.span,
229+
ResolutionError::UnresolvedImport(Some((&e.path, &e.help))));
230+
}
231+
} else {
232+
// Report unresolved imports only if no hard error was already reported
233+
// to avoid generating multiple errors on the same import.
234+
// Imports that are still indeterminate at this point are actually blocked
235+
// by errored imports, so there is no point reporting them.
236+
self.resolver.report_unresolved_imports(module_root);
237+
}
220238
break;
221239
}
222240

@@ -227,11 +245,13 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
227245

228246
/// Attempts to resolve imports for the given module and all of its
229247
/// submodules.
230-
fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>) {
248+
fn resolve_imports_for_module_subtree(&mut self, module_: Rc<Module>)
249+
-> Vec<ImportResolvingError> {
250+
let mut errors = Vec::new();
231251
debug!("(resolving imports for module subtree) resolving {}",
232252
module_to_string(&*module_));
233253
let orig_module = replace(&mut self.resolver.current_module, module_.clone());
234-
self.resolve_imports_for_module(module_.clone());
254+
errors.extend(self.resolve_imports_for_module(module_.clone()));
235255
self.resolver.current_module = orig_module;
236256

237257
build_reduced_graph::populate_module_if_necessary(self.resolver, &module_);
@@ -241,53 +261,67 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
241261
// Nothing to do.
242262
}
243263
Some(child_module) => {
244-
self.resolve_imports_for_module_subtree(child_module);
264+
errors.extend(self.resolve_imports_for_module_subtree(child_module));
245265
}
246266
}
247267
}
248268

249269
for (_, child_module) in module_.anonymous_children.borrow().iter() {
250-
self.resolve_imports_for_module_subtree(child_module.clone());
270+
errors.extend(self.resolve_imports_for_module_subtree(child_module.clone()));
251271
}
272+
273+
errors
252274
}
253275

254276
/// Attempts to resolve imports for the given module only.
255-
fn resolve_imports_for_module(&mut self, module: Rc<Module>) {
277+
fn resolve_imports_for_module(&mut self, module: Rc<Module>) -> Vec<ImportResolvingError> {
278+
let mut errors = Vec::new();
279+
256280
if module.all_imports_resolved() {
257281
debug!("(resolving imports for module) all imports resolved for \
258282
{}",
259283
module_to_string(&*module));
260-
return;
284+
return errors;
261285
}
262286

263-
let imports = module.imports.borrow();
287+
let mut imports = module.imports.borrow_mut();
264288
let import_count = imports.len();
265-
while module.resolved_import_count.get() < import_count {
289+
let mut indeterminate_imports = Vec::new();
290+
while module.resolved_import_count.get() + indeterminate_imports.len() < import_count {
266291
let import_index = module.resolved_import_count.get();
267-
let import_directive = &(*imports)[import_index];
268292
match self.resolve_import_for_module(module.clone(),
269-
import_directive) {
293+
&imports[import_index]) {
270294
ResolveResult::Failed(err) => {
295+
let import_directive = &imports[import_index];
271296
let (span, help) = match err {
272297
Some((span, msg)) => (span, format!(". {}", msg)),
273298
None => (import_directive.span, String::new())
274299
};
275-
resolve_error(self.resolver,
276-
span,
277-
ResolutionError::UnresolvedImport(
278-
Some((&*import_path_to_string(
279-
&import_directive.module_path,
280-
import_directive.subclass),
281-
Some(&*help))))
282-
);
300+
errors.push(ImportResolvingError {
301+
span: span,
302+
path: import_path_to_string(
303+
&import_directive.module_path,
304+
import_directive.subclass
305+
),
306+
help: help
307+
});
308+
}
309+
ResolveResult::Indeterminate => {}
310+
ResolveResult::Success(()) => {
311+
// count success
312+
module.resolved_import_count
313+
.set(module.resolved_import_count.get() + 1);
314+
continue;
283315
}
284-
ResolveResult::Indeterminate => break, // Bail out. We'll come around next time.
285-
ResolveResult::Success(()) => () // Good. Continue.
286316
}
317+
// This resolution was not successful, keep it for later
318+
indeterminate_imports.push(imports.swap_remove(import_index));
287319

288-
module.resolved_import_count
289-
.set(module.resolved_import_count.get() + 1);
290320
}
321+
322+
imports.extend(indeterminate_imports);
323+
324+
errors
291325
}
292326

293327
/// Attempts to resolve the given import. The return value indicates
@@ -367,11 +401,10 @@ impl<'a, 'b:'a, 'tcx:'b> ImportResolver<'a, 'b, 'tcx> {
367401
}
368402

369403
// Decrement the count of unresolved globs if necessary. But only if
370-
// the resolution result is indeterminate -- otherwise we'll stop
371-
// processing imports here. (See the loop in
372-
// resolve_imports_for_module).
404+
// the resolution result is a success -- other cases will
405+
// be handled by the main loop.
373406

374-
if !resolution_result.indeterminate() {
407+
if resolution_result.success() {
375408
match import_directive.subclass {
376409
GlobImport => {
377410
assert!(module_.glob_count.get() >= 1);

src/test/compile-fail/import-shadow-6.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212

1313
#![no_implicit_prelude]
1414

15-
use qux::*;
16-
use foo::*; //~ERROR a type named `Baz` has already been imported in this module
15+
use qux::*; //~ERROR a type named `Baz` has already been imported in this module
16+
use foo::*;
1717

1818
mod foo {
1919
pub type Baz = isize;

src/test/compile-fail/issue-25396.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,14 @@
1111
use foo::baz;
1212
use bar::baz; //~ ERROR a module named `baz` has already been imported
1313

14-
use foo::Quux;
1514
use bar::Quux; //~ ERROR a trait named `Quux` has already been imported
15+
use foo::Quux;
1616

17-
use foo::blah;
18-
use bar::blah; //~ ERROR a type named `blah` has already been imported
17+
use foo::blah; //~ ERROR a type named `blah` has already been imported
18+
use bar::blah;
1919

20-
use foo::WOMP;
21-
use bar::WOMP; //~ ERROR a value named `WOMP` has already been imported
20+
use foo::WOMP; //~ ERROR a value named `WOMP` has already been imported
21+
use bar::WOMP;
2222

2323
fn main() {}
2424

src/test/run-pass/import-glob-1.rs

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// This should resolve fine. Prior to fix, the last import
12+
// was being tried too early, and marked as unrsolved before
13+
// the glob import had a chance to be resolved.
14+
15+
mod bar {
16+
pub use self::middle::*;
17+
18+
mod middle {
19+
pub use self::baz::Baz;
20+
21+
mod baz {
22+
pub enum Baz {
23+
Baz1,
24+
Baz2
25+
}
26+
}
27+
}
28+
}
29+
30+
mod foo {
31+
use bar::Baz::{Baz1, Baz2};
32+
}
33+
34+
fn main() {}

src/test/run-pass/issue-18083.rs

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// These crossed imports should resolve fine, and not block on
12+
// each other and be reported as unresolved.
13+
14+
mod a {
15+
use b::{B};
16+
pub use self::inner::A;
17+
18+
mod inner {
19+
pub struct A;
20+
}
21+
}
22+
23+
mod b {
24+
use a::{A};
25+
pub use self::inner::B;
26+
27+
mod inner {
28+
pub struct B;
29+
}
30+
}
31+
32+
fn main() {}

src/test/run-pass/issue-4865-1.rs

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// This should resolve fine.
12+
// Prior to fix, the crossed imports between a and b
13+
// would block on the glob import, itself never being resolved
14+
// because these previous imports were not resolved.
15+
16+
pub mod a {
17+
use b::fn_b;
18+
use c::*;
19+
20+
pub fn fn_a(){
21+
}
22+
}
23+
24+
pub mod b {
25+
use a::fn_a;
26+
use c::*;
27+
28+
pub fn fn_b(){
29+
}
30+
}
31+
32+
pub mod c{
33+
pub fn fn_c(){
34+
}
35+
}
36+
37+
use a::fn_a;
38+
use b::fn_b;
39+
40+
fn main() {
41+
}

0 commit comments

Comments
 (0)