Skip to content

Commit 5f6267c

Browse files
committed
resolve: Make visibility resolution more speculative
To avoid potential duplicate diagnostics and separate the error reporting logic
1 parent e2c962d commit 5f6267c

File tree

5 files changed

+87
-70
lines changed

5 files changed

+87
-70
lines changed

src/librustc_resolve/build_reduced_graph.rs

+36-60
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::resolve_imports::ImportDirectiveSubclass::{self, GlobImport, SingleIm
1212
use crate::{Module, ModuleData, ModuleKind, NameBinding, NameBindingKind, Segment, ToNameBinding};
1313
use crate::{ModuleOrUniformRoot, ParentScope, PerNS, Resolver, ResolverArenas, ExternPreludeEntry};
1414
use crate::Namespace::{self, TypeNS, ValueNS, MacroNS};
15-
use crate::{ResolutionError, Determinacy, PathResult, CrateLint};
15+
use crate::{ResolutionError, VisResolutionError, Determinacy, PathResult, CrateLint};
1616

1717
use rustc::bug;
1818
use rustc::hir::def::{self, *};
@@ -32,8 +32,7 @@ use syntax::attr;
3232
use syntax::ast::{self, Block, ForeignItem, ForeignItemKind, Item, ItemKind, NodeId};
3333
use syntax::ast::{MetaItemKind, StmtKind, TraitItem, TraitItemKind};
3434
use syntax::token::{self, Token};
35-
use syntax::print::pprust;
36-
use syntax::{span_err, struct_span_err};
35+
use syntax::span_err;
3736
use syntax::source_map::{respan, Spanned};
3837
use syntax::symbol::{kw, sym};
3938
use syntax::visit::{self, Visitor};
@@ -192,22 +191,25 @@ impl<'a> AsMut<Resolver<'a>> for BuildReducedGraphVisitor<'a, '_> {
192191

193192
impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
194193
fn resolve_visibility(&mut self, vis: &ast::Visibility) -> ty::Visibility {
195-
self.resolve_visibility_speculative(vis, false)
194+
self.resolve_visibility_speculative(vis, false).unwrap_or_else(|err| {
195+
self.r.report_vis_error(err);
196+
ty::Visibility::Public
197+
})
196198
}
197199

198-
fn resolve_visibility_speculative(
200+
fn resolve_visibility_speculative<'ast>(
199201
&mut self,
200-
vis: &ast::Visibility,
202+
vis: &'ast ast::Visibility,
201203
speculative: bool,
202-
) -> ty::Visibility {
204+
) -> Result<ty::Visibility, VisResolutionError<'ast>> {
203205
let parent_scope = &self.parent_scope;
204206
match vis.node {
205-
ast::VisibilityKind::Public => ty::Visibility::Public,
207+
ast::VisibilityKind::Public => Ok(ty::Visibility::Public),
206208
ast::VisibilityKind::Crate(..) => {
207-
ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX))
209+
Ok(ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)))
208210
}
209211
ast::VisibilityKind::Inherited => {
210-
ty::Visibility::Restricted(parent_scope.module.normal_ancestor_id)
212+
Ok(ty::Visibility::Restricted(parent_scope.module.normal_ancestor_id))
211213
}
212214
ast::VisibilityKind::Restricted { ref path, id, .. } => {
213215
// For visibilities we are not ready to provide correct implementation of "uniform
@@ -217,32 +219,19 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
217219
let ident = path.segments.get(0).expect("empty path in visibility").ident;
218220
let crate_root = if ident.is_path_segment_keyword() {
219221
None
220-
} else if ident.span.rust_2018() {
221-
let msg = "relative paths are not supported in visibilities on 2018 edition";
222-
self.r.session.struct_span_err(ident.span, msg)
223-
.span_suggestion(
224-
path.span,
225-
"try",
226-
format!("crate::{}", pprust::path_to_string(&path)),
227-
Applicability::MaybeIncorrect,
228-
)
229-
.emit();
230-
return ty::Visibility::Public;
231-
} else {
232-
let ctxt = ident.span.ctxt();
222+
} else if ident.span.rust_2015() {
233223
Some(Segment::from_ident(Ident::new(
234-
kw::PathRoot, path.span.shrink_to_lo().with_ctxt(ctxt)
224+
kw::PathRoot, path.span.shrink_to_lo().with_ctxt(ident.span.ctxt())
235225
)))
226+
} else {
227+
return Err(VisResolutionError::Relative2018(ident.span, path));
236228
};
237229

238230
let segments = crate_root.into_iter()
239231
.chain(path.segments.iter().map(|seg| seg.into())).collect::<Vec<_>>();
240-
let expected_found_error = |this: &Self, res: Res| {
241-
let path_str = Segment::names_to_string(&segments);
242-
struct_span_err!(this.r.session, path.span, E0577,
243-
"expected module, found {} `{}`", res.descr(), path_str)
244-
.span_label(path.span, "not a module").emit();
245-
};
232+
let expected_found_error = |res| Err(VisResolutionError::ExpectedFound(
233+
path.span, Segment::names_to_string(&segments), res
234+
));
246235
match self.r.resolve_path(
247236
&segments,
248237
Some(TypeNS),
@@ -258,42 +247,27 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
258247
}
259248
if module.is_normal() {
260249
if res == Res::Err {
261-
ty::Visibility::Public
250+
Ok(ty::Visibility::Public)
262251
} else {
263252
let vis = ty::Visibility::Restricted(res.def_id());
264253
if self.r.is_accessible_from(vis, parent_scope.module) {
265-
vis
254+
Ok(vis)
266255
} else {
267-
struct_span_err!(self.r.session, path.span, E0742,
268-
"visibilities can only be restricted to ancestor modules")
269-
.emit();
270-
ty::Visibility::Public
256+
Err(VisResolutionError::AncestorOnly(path.span))
271257
}
272258
}
273259
} else {
274-
expected_found_error(self, res);
275-
ty::Visibility::Public
260+
expected_found_error(res)
276261
}
277262
}
278-
PathResult::Module(..) => {
279-
self.r.session.span_err(path.span, "visibility must resolve to a module");
280-
ty::Visibility::Public
281-
}
282-
PathResult::NonModule(partial_res) => {
283-
expected_found_error(self, partial_res.base_res());
284-
ty::Visibility::Public
285-
}
286-
PathResult::Failed { span, label, suggestion, .. } => {
287-
self.r.report_error(
288-
span, ResolutionError::FailedToResolve { label, suggestion }
289-
);
290-
ty::Visibility::Public
291-
}
292-
PathResult::Indeterminate => {
293-
span_err!(self.r.session, path.span, E0578,
294-
"cannot determine resolution for the visibility");
295-
ty::Visibility::Public
296-
}
263+
PathResult::Module(..) =>
264+
Err(VisResolutionError::ModuleOnly(path.span)),
265+
PathResult::NonModule(partial_res) =>
266+
expected_found_error(partial_res.base_res()),
267+
PathResult::Failed { span, label, suggestion, .. } =>
268+
Err(VisResolutionError::FailedToResolve(span, label, suggestion)),
269+
PathResult::Indeterminate =>
270+
Err(VisResolutionError::Indeterminate(path.span)),
297271
}
298272
}
299273
}
@@ -766,9 +740,11 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
766740
// NOTE: The field may be an expansion placeholder, but expansion sets
767741
// correct visibilities for unnamed field placeholders specifically, so the
768742
// constructor visibility should still be determined correctly.
769-
let field_vis = self.resolve_visibility_speculative(&field.vis, true);
770-
if ctor_vis.is_at_least(field_vis, &*self.r) {
771-
ctor_vis = field_vis;
743+
if let Ok(field_vis) =
744+
self.resolve_visibility_speculative(&field.vis, true) {
745+
if ctor_vis.is_at_least(field_vis, &*self.r) {
746+
ctor_vis = field_vis;
747+
}
772748
}
773749
}
774750
let ctor_res = Res::Def(

src/librustc_resolve/diagnostics.rs

+40
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use rustc::ty::{self, DefIdTree};
1111
use rustc::util::nodemap::FxHashSet;
1212
use rustc_feature::BUILTIN_ATTRIBUTES;
1313
use syntax::ast::{self, Ident, Path};
14+
use syntax::print::pprust;
1415
use syntax::source_map::SourceMap;
1516
use syntax::struct_span_err;
1617
use syntax::symbol::{Symbol, kw};
@@ -22,6 +23,7 @@ use crate::resolve_imports::{ImportDirective, ImportDirectiveSubclass, ImportRes
2223
use crate::path_names_to_string;
2324
use crate::{BindingError, CrateLint, HasGenericParams, LegacyScope, Module, ModuleOrUniformRoot};
2425
use crate::{PathResult, ParentScope, ResolutionError, Resolver, Scope, ScopeSet, Segment};
26+
use crate::VisResolutionError;
2527

2628
use rustc_error_codes::*;
2729

@@ -357,6 +359,44 @@ impl<'a> Resolver<'a> {
357359
}
358360
}
359361

362+
crate fn report_vis_error(&self, vis_resolution_error: VisResolutionError<'_>) {
363+
match vis_resolution_error {
364+
VisResolutionError::Relative2018(span, path) => {
365+
let mut err = self.session.struct_span_err(span,
366+
"relative paths are not supported in visibilities on 2018 edition");
367+
err.span_suggestion(
368+
path.span,
369+
"try",
370+
format!("crate::{}", pprust::path_to_string(&path)),
371+
Applicability::MaybeIncorrect,
372+
);
373+
err
374+
}
375+
VisResolutionError::AncestorOnly(span) => {
376+
struct_span_err!(self.session, span, E0742,
377+
"visibilities can only be restricted to ancestor modules")
378+
}
379+
VisResolutionError::FailedToResolve(span, label, suggestion) => {
380+
self.into_struct_error(
381+
span, ResolutionError::FailedToResolve { label, suggestion }
382+
)
383+
}
384+
VisResolutionError::ExpectedFound(span, path_str, res) => {
385+
let mut err = struct_span_err!(self.session, span, E0577,
386+
"expected module, found {} `{}`", res.descr(), path_str);
387+
err.span_label(span, "not a module");
388+
err
389+
}
390+
VisResolutionError::Indeterminate(span) => {
391+
struct_span_err!(self.session, span, E0578,
392+
"cannot determine resolution for the visibility")
393+
}
394+
VisResolutionError::ModuleOnly(span) => {
395+
self.session.struct_span_err(span, "visibility must resolve to a module")
396+
}
397+
}.emit()
398+
}
399+
360400
/// Lookup typo candidate in scope for a macro or import.
361401
fn early_lookup_typo_candidate(
362402
&mut self,

src/librustc_resolve/lib.rs

+9
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,15 @@ enum ResolutionError<'a> {
218218
SelfInTyParamDefault,
219219
}
220220

221+
enum VisResolutionError<'a> {
222+
Relative2018(Span, &'a ast::Path),
223+
AncestorOnly(Span),
224+
FailedToResolve(Span, String, Option<Suggestion>),
225+
ExpectedFound(Span, String, Res),
226+
Indeterminate(Span),
227+
ModuleOnly(Span),
228+
}
229+
221230
// A minimal representation of a path segment. We use this in resolve because
222231
// we synthesize 'path segments' which don't have the rest of an AST or HIR
223232
// `PathSegment`.

src/test/ui/attributes/field-attributes-vis-unresolved.rs

-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ struct S {
2020
struct Z(
2121
#[rustfmt::skip]
2222
pub(in nonexistent) u8 //~ ERROR failed to resolve
23-
//~| ERROR cannot determine resolution for the visibility
2423
);
2524

2625
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,3 @@
1-
error[E0578]: cannot determine resolution for the visibility
2-
--> $DIR/field-attributes-vis-unresolved.rs:22:12
3-
|
4-
LL | pub(in nonexistent) u8
5-
| ^^^^^^^^^^^
6-
71
error[E0433]: failed to resolve: maybe a missing crate `nonexistent`?
82
--> $DIR/field-attributes-vis-unresolved.rs:17:12
93
|
@@ -16,7 +10,6 @@ error[E0433]: failed to resolve: maybe a missing crate `nonexistent`?
1610
LL | pub(in nonexistent) u8
1711
| ^^^^^^^^^^^ maybe a missing crate `nonexistent`?
1812

19-
error: aborting due to 3 previous errors
13+
error: aborting due to 2 previous errors
2014

21-
Some errors have detailed explanations: E0433, E0578.
22-
For more information about an error, try `rustc --explain E0433`.
15+
For more information about this error, try `rustc --explain E0433`.

0 commit comments

Comments
 (0)