Skip to content

Commit cdc5400

Browse files
committed
review comments and tweaks
1 parent fa0b721 commit cdc5400

File tree

6 files changed

+119
-78
lines changed

6 files changed

+119
-78
lines changed

src/librustc_resolve/late.rs

+62-48
Original file line numberDiff line numberDiff line change
@@ -320,22 +320,7 @@ impl<'a> PathSource<'a> {
320320
}
321321
}
322322

323-
struct LateResolutionVisitor<'a, 'b> {
324-
r: &'b mut Resolver<'a>,
325-
326-
/// The module that represents the current item scope.
327-
parent_scope: ParentScope<'a>,
328-
329-
/// The current set of local scopes for types and values.
330-
/// FIXME #4948: Reuse ribs to avoid allocation.
331-
ribs: PerNS<Vec<Rib<'a>>>,
332-
333-
/// The current set of local scopes, for labels.
334-
label_ribs: Vec<Rib<'a, NodeId>>,
335-
336-
/// The trait that the current context can refer to.
337-
current_trait_ref: Option<(Module<'a>, TraitRef)>,
338-
323+
struct DiagnosticMetadata {
339324
/// The current trait's associated types' ident, used for diagnostic suggestions.
340325
current_trait_assoc_types: Vec<Ident>,
341326

@@ -356,7 +341,27 @@ struct LateResolutionVisitor<'a, 'b> {
356341
current_type_ascription: Vec<Span>,
357342

358343
/// Only used for better errors on `let <pat>: <expr, not type>;`.
359-
current_let_binding: Option<(Span, Span)>,
344+
current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
345+
}
346+
347+
struct LateResolutionVisitor<'a, 'b> {
348+
r: &'b mut Resolver<'a>,
349+
350+
/// The module that represents the current item scope.
351+
parent_scope: ParentScope<'a>,
352+
353+
/// The current set of local scopes for types and values.
354+
/// FIXME #4948: Reuse ribs to avoid allocation.
355+
ribs: PerNS<Vec<Rib<'a>>>,
356+
357+
/// The current set of local scopes, for labels.
358+
label_ribs: Vec<Rib<'a, NodeId>>,
359+
360+
/// The trait that the current context can refer to.
361+
current_trait_ref: Option<(Module<'a>, TraitRef)>,
362+
363+
/// Fields used to add information to diagnostic errors.
364+
diagnostic_metadata: DiagnosticMetadata,
360365
}
361366

362367
/// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
@@ -380,18 +385,18 @@ impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
380385
self.resolve_expr(expr, None);
381386
}
382387
fn visit_local(&mut self, local: &'tcx Local) {
383-
debug!("visit_local {:?} {:?} {:?}", local, local.pat, local.pat.kind);
384-
let val = match local {
385-
Local { pat, ty: Some(ty), init: None, .. } => match pat.kind {
386-
// We check for this to avoid tuple struct fields.
387-
PatKind::Wild => None,
388-
_ => Some((pat.span, ty.span)),
389-
},
390-
_ => None,
388+
let local_spans = match local.pat.kind {
389+
// We check for this to avoid tuple struct fields.
390+
PatKind::Wild => None,
391+
_ => Some((
392+
local.pat.span,
393+
local.ty.as_ref().map(|ty| ty.span),
394+
local.init.as_ref().map(|init| init.span),
395+
)),
391396
};
392-
let original = replace(&mut self.current_let_binding, val);
397+
let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
393398
self.resolve_local(local);
394-
self.current_let_binding = original;
399+
self.diagnostic_metadata.current_let_binding = original;
395400
}
396401
fn visit_ty(&mut self, ty: &'tcx Ty) {
397402
match ty.kind {
@@ -433,7 +438,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
433438
}
434439
}
435440
fn visit_fn(&mut self, fn_kind: FnKind<'tcx>, declaration: &'tcx FnDecl, sp: Span, _: NodeId) {
436-
let previous_value = replace(&mut self.current_function, Some(sp));
441+
let previous_value = replace(&mut self.diagnostic_metadata.current_function, Some(sp));
437442
debug!("(resolving function) entering function");
438443
let rib_kind = match fn_kind {
439444
FnKind::ItemFn(..) => FnItemRibKind,
@@ -459,7 +464,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
459464
debug!("(resolving function) leaving function");
460465
})
461466
});
462-
self.current_function = previous_value;
467+
self.diagnostic_metadata.current_function = previous_value;
463468
}
464469

465470
fn visit_generics(&mut self, generics: &'tcx Generics) {
@@ -493,7 +498,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LateResolutionVisitor<'a, '_> {
493498
// (We however cannot ban `Self` for defaults on *all* generic
494499
// lists; e.g. trait generics can usefully refer to `Self`,
495500
// such as in the case of `trait Add<Rhs = Self>`.)
496-
if self.current_self_item.is_some() { // (`Some` if + only if we are in ADT's generics.)
501+
if self.diagnostic_metadata.current_self_item.is_some() {
502+
// (`Some` if + only if we are in ADT's generics.)
497503
default_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
498504
}
499505

@@ -562,13 +568,15 @@ impl<'a, 'b> LateResolutionVisitor<'a, '_> {
562568
},
563569
label_ribs: Vec::new(),
564570
current_trait_ref: None,
565-
current_trait_assoc_types: Vec::new(),
566-
current_self_type: None,
567-
current_self_item: None,
568-
current_function: None,
569-
unused_labels: Default::default(),
570-
current_type_ascription: Vec::new(),
571-
current_let_binding: None,
571+
diagnostic_metadata: DiagnosticMetadata {
572+
current_trait_assoc_types: Vec::new(),
573+
current_self_type: None,
574+
current_self_item: None,
575+
current_function: None,
576+
unused_labels: Default::default(),
577+
current_type_ascription: Vec::new(),
578+
current_let_binding: None,
579+
}
572580
}
573581
}
574582

@@ -928,16 +936,22 @@ impl<'a, 'b> LateResolutionVisitor<'a, '_> {
928936

929937
fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
930938
// Handle nested impls (inside fn bodies)
931-
let previous_value = replace(&mut self.current_self_type, Some(self_type.clone()));
939+
let previous_value = replace(
940+
&mut self.diagnostic_metadata.current_self_type,
941+
Some(self_type.clone()),
942+
);
932943
let result = f(self);
933-
self.current_self_type = previous_value;
944+
self.diagnostic_metadata.current_self_type = previous_value;
934945
result
935946
}
936947

937948
fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
938-
let previous_value = replace(&mut self.current_self_item, Some(self_item.id));
949+
let previous_value = replace(
950+
&mut self.diagnostic_metadata.current_self_item,
951+
Some(self_item.id),
952+
);
939953
let result = f(self);
940-
self.current_self_item = previous_value;
954+
self.diagnostic_metadata.current_self_item = previous_value;
941955
result
942956
}
943957

@@ -948,14 +962,14 @@ impl<'a, 'b> LateResolutionVisitor<'a, '_> {
948962
f: impl FnOnce(&mut Self) -> T,
949963
) -> T {
950964
let trait_assoc_types = replace(
951-
&mut self.current_trait_assoc_types,
965+
&mut self.diagnostic_metadata.current_trait_assoc_types,
952966
trait_items.iter().filter_map(|item| match &item.kind {
953967
TraitItemKind::Type(bounds, _) if bounds.len() == 0 => Some(item.ident),
954968
_ => None,
955969
}).collect(),
956970
);
957971
let result = f(self);
958-
self.current_trait_assoc_types = trait_assoc_types;
972+
self.diagnostic_metadata.current_trait_assoc_types = trait_assoc_types;
959973
result
960974
}
961975

@@ -1782,7 +1796,7 @@ impl<'a, 'b> LateResolutionVisitor<'a, '_> {
17821796

17831797
fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
17841798
if let Some(label) = label {
1785-
self.unused_labels.insert(id, label.ident.span);
1799+
self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
17861800
self.with_label_rib(NormalRibKind, |this| {
17871801
let ident = label.ident.modern_and_legacy();
17881802
this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
@@ -1886,7 +1900,7 @@ impl<'a, 'b> LateResolutionVisitor<'a, '_> {
18861900
Some(node_id) => {
18871901
// Since this res is a label, it is never read.
18881902
self.r.label_res_map.insert(expr.id, node_id);
1889-
self.unused_labels.remove(&node_id);
1903+
self.diagnostic_metadata.unused_labels.remove(&node_id);
18901904
}
18911905
}
18921906

@@ -1948,9 +1962,9 @@ impl<'a, 'b> LateResolutionVisitor<'a, '_> {
19481962
}
19491963
}
19501964
ExprKind::Type(ref type_expr, _) => {
1951-
self.current_type_ascription.push(type_expr.span);
1965+
self.diagnostic_metadata.current_type_ascription.push(type_expr.span);
19521966
visit::walk_expr(self, expr);
1953-
self.current_type_ascription.pop();
1967+
self.diagnostic_metadata.current_type_ascription.pop();
19541968
}
19551969
// `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
19561970
// resolve the arguments within the proper scopes so that usages of them inside the
@@ -2109,7 +2123,7 @@ impl<'a> Resolver<'a> {
21092123
pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
21102124
let mut late_resolution_visitor = LateResolutionVisitor::new(self);
21112125
visit::walk_crate(&mut late_resolution_visitor, krate);
2112-
for (id, span) in late_resolution_visitor.unused_labels.iter() {
2126+
for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
21132127
self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
21142128
}
21152129
}

src/librustc_resolve/late/diagnostics.rs

+29-19
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,23 @@ impl<'a> LateResolutionVisitor<'a, '_> {
7272
let path_str = Segment::names_to_string(path);
7373
let item_str = path.last().unwrap().ident;
7474
let code = source.error_code(res.is_some());
75-
let (base_msg, fallback_label, base_span, is_local) = if let Some(res) = res {
75+
let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
7676
(format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
7777
format!("not a {}", expected),
7878
span,
7979
match res {
80+
Res::Def(DefKind::Fn, _) => {
81+
// Verify whether this is a fn call or an Fn used as a type.
82+
self.r.session.source_map().span_to_snippet(span).map(|snippet| {
83+
snippet.ends_with(')')
84+
}).unwrap_or(false)
85+
}
86+
Res::Def(DefKind::Ctor(..), _) |
87+
Res::Def(DefKind::Method, _) |
88+
Res::Def(DefKind::Const, _) |
89+
Res::Def(DefKind::AssocConst, _) |
90+
Res::SelfCtor(_) |
91+
Res::PrimTy(_) |
8092
Res::Local(_) => true,
8193
_ => false,
8294
})
@@ -139,7 +151,7 @@ impl<'a> LateResolutionVisitor<'a, '_> {
139151
"`self` value is a keyword only available in methods with a `self` parameter",
140152
),
141153
});
142-
if let Some(span) = &self.current_function {
154+
if let Some(span) = &self.diagnostic_metadata.current_function {
143155
err.span_label(*span, "this function doesn't have a `self` parameter");
144156
}
145157
return (err, Vec::new());
@@ -262,19 +274,17 @@ impl<'a> LateResolutionVisitor<'a, '_> {
262274
if !levenshtein_worked {
263275
err.span_label(base_span, fallback_label);
264276
self.type_ascription_suggestion(&mut err, base_span);
265-
if let Some(span) = self.current_let_binding.and_then(|(pat_sp, ty_sp)| {
266-
if ty_sp.contains(base_span) && is_local {
267-
Some(pat_sp.between(ty_sp))
268-
} else {
269-
None
277+
match self.diagnostic_metadata.current_let_binding {
278+
Some((pat_sp, Some(ty_sp), None))
279+
if ty_sp.contains(base_span) && could_be_expr => {
280+
err.span_suggestion_short(
281+
pat_sp.between(ty_sp),
282+
"use `=` if you meant to assign",
283+
" = ".to_string(),
284+
Applicability::MaybeIncorrect,
285+
);
270286
}
271-
}) {
272-
err.span_suggestion(
273-
span,
274-
"maybe you meant to assign a value instead of defining this let binding's type",
275-
" = ".to_string(),
276-
Applicability::MaybeIncorrect,
277-
);
287+
_ => {}
278288
}
279289
}
280290
(err, candidates)
@@ -510,7 +520,9 @@ impl<'a> LateResolutionVisitor<'a, '_> {
510520

511521
// Fields are generally expected in the same contexts as locals.
512522
if filter_fn(Res::Local(ast::DUMMY_NODE_ID)) {
513-
if let Some(node_id) = self.current_self_type.as_ref().and_then(extract_node_id) {
523+
if let Some(node_id) = self.diagnostic_metadata.current_self_type.as_ref()
524+
.and_then(extract_node_id)
525+
{
514526
// Look for a field with the same name in the current self_type.
515527
if let Some(resolution) = self.r.partial_res_map.get(&node_id) {
516528
match resolution.base_res() {
@@ -529,7 +541,7 @@ impl<'a> LateResolutionVisitor<'a, '_> {
529541
}
530542
}
531543

532-
for assoc_type_ident in &self.current_trait_assoc_types {
544+
for assoc_type_ident in &self.diagnostic_metadata.current_trait_assoc_types {
533545
if *assoc_type_ident == ident {
534546
return Some(AssocSuggestion::AssocItem);
535547
}
@@ -663,11 +675,9 @@ impl<'a> LateResolutionVisitor<'a, '_> {
663675
err: &mut DiagnosticBuilder<'_>,
664676
base_span: Span,
665677
) {
666-
debug!("type_ascription_suggetion {:?}", base_span);
667678
let cm = self.r.session.source_map();
668679
let base_snippet = cm.span_to_snippet(base_span);
669-
debug!("self.current_type_ascription {:?}", self.current_type_ascription);
670-
if let Some(sp) = self.current_type_ascription.last() {
680+
if let Some(sp) = self.diagnostic_metadata.current_type_ascription.last() {
671681
let mut sp = *sp;
672682
loop {
673683
// Try to find the `:`; bail on first non-':' / non-whitespace.

src/libsyntax/parse/parser/stmt.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ impl<'a> Parser<'a> {
239239
err.span_suggestion_short(
240240
colon_sp,
241241
"use `=` if you meant to assign",
242-
"=".to_string(),
242+
" =".to_string(),
243243
Applicability::MachineApplicable
244244
);
245245
err.emit();

src/test/ui/privacy/privacy-ns2.rs

+1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ fn test_single2() {
3939
use foo2::Bar;
4040

4141
let _x : Box<Bar>; //~ ERROR expected type, found function `Bar`
42+
let _x : Bar(); //~ ERROR expected type, found function `Bar`
4243
}
4344

4445
fn test_list2() {

src/test/ui/privacy/privacy-ns2.stderr

+23-5
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,25 @@ LL | use foo3::Bar;
4545
|
4646

4747
error[E0573]: expected type, found function `Bar`
48-
--> $DIR/privacy-ns2.rs:47:17
48+
--> $DIR/privacy-ns2.rs:42:14
49+
|
50+
LL | let _x : Bar();
51+
| ^^^^^ not a type
52+
help: use `=` if you meant to assign
53+
|
54+
LL | let _x = Bar();
55+
| ^
56+
help: possible better candidates are found in other modules, you can import them into scope
57+
|
58+
LL | use foo1::Bar;
59+
|
60+
LL | use foo2::Bar;
61+
|
62+
LL | use foo3::Bar;
63+
|
64+
65+
error[E0573]: expected type, found function `Bar`
66+
--> $DIR/privacy-ns2.rs:48:17
4967
|
5068
LL | let _x: Box<Bar>;
5169
| ^^^
@@ -63,24 +81,24 @@ LL | use foo3::Bar;
6381
|
6482

6583
error[E0603]: trait `Bar` is private
66-
--> $DIR/privacy-ns2.rs:60:15
84+
--> $DIR/privacy-ns2.rs:61:15
6785
|
6886
LL | use foo3::Bar;
6987
| ^^^
7088

7189
error[E0603]: trait `Bar` is private
72-
--> $DIR/privacy-ns2.rs:64:15
90+
--> $DIR/privacy-ns2.rs:65:15
7391
|
7492
LL | use foo3::Bar;
7593
| ^^^
7694

7795
error[E0603]: trait `Bar` is private
78-
--> $DIR/privacy-ns2.rs:71:16
96+
--> $DIR/privacy-ns2.rs:72:16
7997
|
8098
LL | use foo3::{Bar,Baz};
8199
| ^^^
82100

83-
error: aborting due to 7 previous errors
101+
error: aborting due to 8 previous errors
84102

85103
Some errors have detailed explanations: E0423, E0573, E0603.
86104
For more information about an error, try `rustc --explain E0423`.

0 commit comments

Comments
 (0)