Skip to content

Commit e6723e0

Browse files
Rollup merge of rust-lang#137565 - compiler-errors:macro-ex, r=estebank
Try to point of macro expansion from resolver and method errors if it involves macro var In the case that a macro caller passes an identifier into a macro generating a path or method expression, point out that identifier in the context of the *macro* so it's a bit more clear how the macro is involved in causing the error. r? ````````@estebank```````` or reassign
2 parents 147243c + 09e5846 commit e6723e0

File tree

17 files changed

+225
-15
lines changed

17 files changed

+225
-15
lines changed

compiler/rustc_hir_analysis/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,8 @@ hir_analysis_variances_of = {$variances}
620620
hir_analysis_where_clause_on_main = `main` function is not allowed to have a `where` clause
621621
.label = `main` cannot have a `where` clause
622622
623+
hir_analysis_within_macro = due to this macro variable
624+
623625
hir_analysis_wrong_number_of_generic_arguments_to_intrinsic =
624626
intrinsic has wrong number of {$descr} parameters: found {$found}, expected {$expected}
625627
.label = expected {$expected} {$descr} {$expected ->

compiler/rustc_hir_analysis/src/errors.rs

+2
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ pub(crate) struct AssocItemNotFound<'a> {
8484
pub label: Option<AssocItemNotFoundLabel<'a>>,
8585
#[subdiagnostic]
8686
pub sugg: Option<AssocItemNotFoundSugg<'a>>,
87+
#[label(hir_analysis_within_macro)]
88+
pub within_macro_span: Option<Span>,
8789
}
8890

8991
#[derive(Subdiagnostic)]

compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs

+3
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
151151
qself: &qself_str,
152152
label: None,
153153
sugg: None,
154+
// Try to get the span of the identifier within the path's syntax context
155+
// (if that's different).
156+
within_macro_span: assoc_name.span.within_macro(span, tcx.sess.source_map()),
154157
};
155158

156159
if is_dummy {

compiler/rustc_hir_typeck/src/expr.rs

+23-12
Original file line numberDiff line numberDiff line change
@@ -3069,7 +3069,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
30693069
"ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
30703070
ident, base, expr, base_ty
30713071
);
3072-
let mut err = self.no_such_field_err(ident, base_ty, base.hir_id);
3072+
let mut err = self.no_such_field_err(ident, base_ty, expr);
30733073

30743074
match *base_ty.peel_refs().kind() {
30753075
ty::Array(_, len) => {
@@ -3282,29 +3282,38 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
32823282
);
32833283
}
32843284

3285-
fn no_such_field_err(&self, field: Ident, expr_t: Ty<'tcx>, id: HirId) -> Diag<'_> {
3285+
fn no_such_field_err(
3286+
&self,
3287+
field: Ident,
3288+
base_ty: Ty<'tcx>,
3289+
expr: &hir::Expr<'tcx>,
3290+
) -> Diag<'_> {
32863291
let span = field.span;
3287-
debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, expr_t);
3292+
debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty);
32883293

3289-
let mut err = self.dcx().create_err(NoFieldOnType { span, ty: expr_t, field });
3290-
if expr_t.references_error() {
3294+
let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field });
3295+
if base_ty.references_error() {
32913296
err.downgrade_to_delayed_bug();
32923297
}
32933298

3299+
if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) {
3300+
err.span_label(within_macro_span, "due to this macro variable");
3301+
}
3302+
32943303
// try to add a suggestion in case the field is a nested field of a field of the Adt
3295-
let mod_id = self.tcx.parent_module(id).to_def_id();
3296-
let (ty, unwrap) = if let ty::Adt(def, args) = expr_t.kind()
3304+
let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id();
3305+
let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind()
32973306
&& (self.tcx.is_diagnostic_item(sym::Result, def.did())
32983307
|| self.tcx.is_diagnostic_item(sym::Option, def.did()))
32993308
&& let Some(arg) = args.get(0)
33003309
&& let Some(ty) = arg.as_type()
33013310
{
33023311
(ty, "unwrap().")
33033312
} else {
3304-
(expr_t, "")
3313+
(base_ty, "")
33053314
};
33063315
for (found_fields, args) in
3307-
self.get_field_candidates_considering_privacy_for_diag(span, ty, mod_id, id)
3316+
self.get_field_candidates_considering_privacy_for_diag(span, ty, mod_id, expr.hir_id)
33083317
{
33093318
let field_names = found_fields.iter().map(|field| field.name).collect::<Vec<_>>();
33103319
let mut candidate_fields: Vec<_> = found_fields
@@ -3317,7 +3326,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
33173326
args,
33183327
vec![],
33193328
mod_id,
3320-
id,
3329+
expr.hir_id,
33213330
)
33223331
})
33233332
.map(|mut field_path| {
@@ -3328,7 +3337,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
33283337
candidate_fields.sort();
33293338

33303339
let len = candidate_fields.len();
3331-
if len > 0 {
3340+
// Don't suggest `.field` if the base expr is from a different
3341+
// syntax context than the field.
3342+
if len > 0 && expr.span.eq_ctxt(field.span) {
33323343
err.span_suggestions(
33333344
field.span.shrink_to_lo(),
33343345
format!(
@@ -3963,7 +3974,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
39633974
_ => (),
39643975
};
39653976

3966-
self.no_such_field_err(field, container, expr.hir_id).emit();
3977+
self.no_such_field_err(field, container, expr).emit();
39673978

39683979
break;
39693980
}

compiler/rustc_hir_typeck/src/method/suggest.rs

+21-3
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
158158
self.typeck_results.borrow_mut().used_trait_imports.insert(import_id);
159159
}
160160

161-
let (span, sugg_span, source, item_name, args) = match self.tcx.hir_node(call_id) {
161+
let (span, expr_span, source, item_name, args) = match self.tcx.hir_node(call_id) {
162162
hir::Node::Expr(&hir::Expr {
163163
kind: hir::ExprKind::MethodCall(segment, rcvr, args, _),
164164
span,
@@ -194,6 +194,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
194194
node => unreachable!("{node:?}"),
195195
};
196196

197+
// Try to get the span of the identifier within the expression's syntax context
198+
// (if that's different).
199+
let within_macro_span = span.within_macro(expr_span, self.tcx.sess.source_map());
200+
197201
// Avoid suggestions when we don't know what's going on.
198202
if let Err(guar) = rcvr_ty.error_reported() {
199203
return guar;
@@ -207,10 +211,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
207211
call_id,
208212
source,
209213
args,
210-
sugg_span,
214+
expr_span,
211215
&mut no_match_data,
212216
expected,
213217
trait_missing_method,
218+
within_macro_span,
214219
),
215220

216221
MethodError::Ambiguity(mut sources) => {
@@ -221,6 +226,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
221226
"multiple applicable items in scope"
222227
);
223228
err.span_label(item_name.span, format!("multiple `{item_name}` found"));
229+
if let Some(within_macro_span) = within_macro_span {
230+
err.span_label(within_macro_span, "due to this macro variable");
231+
}
224232

225233
self.note_candidates_on_method_error(
226234
rcvr_ty,
@@ -230,7 +238,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
230238
span,
231239
&mut err,
232240
&mut sources,
233-
Some(sugg_span),
241+
Some(expr_span),
234242
);
235243
err.emit()
236244
}
@@ -252,6 +260,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
252260
.span_if_local(def_id)
253261
.unwrap_or_else(|| self.tcx.def_span(def_id));
254262
err.span_label(sp, format!("private {kind} defined here"));
263+
if let Some(within_macro_span) = within_macro_span {
264+
err.span_label(within_macro_span, "due to this macro variable");
265+
}
255266
self.suggest_valid_traits(&mut err, item_name, out_of_scope_traits, true);
256267
err.emit()
257268
}
@@ -268,6 +279,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
268279
if !needs_mut {
269280
err.span_label(bound_span, "this has a `Sized` requirement");
270281
}
282+
if let Some(within_macro_span) = within_macro_span {
283+
err.span_label(within_macro_span, "due to this macro variable");
284+
}
271285
if !candidates.is_empty() {
272286
let help = format!(
273287
"{an}other candidate{s} {were} found in the following trait{s}",
@@ -581,6 +595,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
581595
no_match_data: &mut NoMatchData<'tcx>,
582596
expected: Expectation<'tcx>,
583597
trait_missing_method: bool,
598+
within_macro_span: Option<Span>,
584599
) -> ErrorGuaranteed {
585600
let mode = no_match_data.mode;
586601
let tcx = self.tcx;
@@ -721,6 +736,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
721736
if tcx.sess.source_map().is_multiline(sugg_span) {
722737
err.span_label(sugg_span.with_hi(span.lo()), "");
723738
}
739+
if let Some(within_macro_span) = within_macro_span {
740+
err.span_label(within_macro_span, "due to this macro variable");
741+
}
724742

725743
if short_ty_str.len() < ty_str.len() && ty_str.len() > 10 {
726744
ty_str = short_ty_str;

compiler/rustc_resolve/src/late/diagnostics.rs

+8
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,14 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
429429
let mut err = self.r.dcx().struct_span_err(base_error.span, base_error.msg.clone());
430430
err.code(code);
431431

432+
// Try to get the span of the identifier within the path's syntax context
433+
// (if that's different).
434+
if let Some(within_macro_span) =
435+
base_error.span.within_macro(span, self.r.tcx.sess.source_map())
436+
{
437+
err.span_label(within_macro_span, "due to this macro variable");
438+
}
439+
432440
self.detect_missing_binding_available_from_pattern(&mut err, path, following_seg);
433441
self.suggest_at_operator_in_slice_pat_with_range(&mut err, path);
434442
self.suggest_swapping_misplaced_self_ty_and_trait(&mut err, source, res, base_error.span);

compiler/rustc_span/src/lib.rs

+31
Original file line numberDiff line numberDiff line change
@@ -1057,6 +1057,37 @@ impl Span {
10571057
}
10581058
}
10591059

1060+
/// Returns the `Span` within the syntax context of "within". This is useful when
1061+
/// "self" is an expansion from a macro variable, since this can be used for
1062+
/// providing extra macro expansion context for certain errors.
1063+
///
1064+
/// ```text
1065+
/// macro_rules! m {
1066+
/// ($ident:ident) => { ($ident,) }
1067+
/// }
1068+
///
1069+
/// m!(outer_ident);
1070+
/// ```
1071+
///
1072+
/// If "self" is the span of the outer_ident, and "within" is the span of the `($ident,)`
1073+
/// expr, then this will return the span of the `$ident` macro variable.
1074+
pub fn within_macro(self, within: Span, sm: &SourceMap) -> Option<Span> {
1075+
match Span::prepare_to_combine(self, within) {
1076+
// Only return something if it doesn't overlap with the original span,
1077+
// and the span isn't "imported" (i.e. from unavailable sources).
1078+
// FIXME: This does limit the usefulness of the error when the macro is
1079+
// from a foreign crate; we could also take into account `-Zmacro-backtrace`,
1080+
// which doesn't redact this span (but that would mean passing in even more
1081+
// args to this function, lol).
1082+
Ok((self_, _, parent))
1083+
if self_.hi < self.lo() || self.hi() < self_.lo && !sm.is_imported(within) =>
1084+
{
1085+
Some(Span::new(self_.lo, self_.hi, self_.ctxt, parent))
1086+
}
1087+
_ => None,
1088+
}
1089+
}
1090+
10601091
pub fn from_inner(self, inner: InnerSpan) -> Span {
10611092
let span = self.data();
10621093
Span::new(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
trait Trait {}
2+
impl Trait for () {}
3+
4+
macro_rules! fully_qualified {
5+
($id:ident) => {
6+
<() as Trait>::$id
7+
}
8+
}
9+
10+
macro_rules! type_dependent {
11+
($t:ident, $id:ident) => {
12+
T::$id
13+
}
14+
}
15+
16+
fn t<T: Trait>() {
17+
let x: fully_qualified!(Assoc);
18+
//~^ ERROR cannot find associated type `Assoc` in trait `Trait`
19+
let x: type_dependent!(T, Assoc);
20+
//~^ ERROR associated type `Assoc` not found for `T`
21+
}
22+
23+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
error[E0576]: cannot find associated type `Assoc` in trait `Trait`
2+
--> $DIR/ident-from-macro-expansion.rs:17:29
3+
|
4+
LL | <() as Trait>::$id
5+
| --- due to this macro variable
6+
...
7+
LL | let x: fully_qualified!(Assoc);
8+
| ^^^^^ not found in `Trait`
9+
10+
error[E0220]: associated type `Assoc` not found for `T`
11+
--> $DIR/ident-from-macro-expansion.rs:19:31
12+
|
13+
LL | T::$id
14+
| --- due to this macro variable
15+
...
16+
LL | let x: type_dependent!(T, Assoc);
17+
| ^^^^^ associated type `Assoc` not found
18+
19+
error: aborting due to 2 previous errors
20+
21+
Some errors have detailed explanations: E0220, E0576.
22+
For more information about an error, try `rustc --explain E0220`.

tests/ui/hygiene/generate-mod.stderr

+6
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
error[E0412]: cannot find type `FromOutside` in this scope
22
--> $DIR/generate-mod.rs:35:13
33
|
4+
LL | type A = $FromOutside;
5+
| ------------ due to this macro variable
6+
...
47
LL | genmod!(FromOutside, Outer);
58
| ^^^^^^^^^^^ not found in this scope
69

710
error[E0412]: cannot find type `Outer` in this scope
811
--> $DIR/generate-mod.rs:35:26
912
|
13+
LL | struct $Outer;
14+
| ------ due to this macro variable
15+
...
1016
LL | genmod!(FromOutside, Outer);
1117
| ^^^^^ not found in this scope
1218

tests/ui/hygiene/globs.stderr

+6
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@ error[E0425]: cannot find function `f` in this scope
5050
LL | n!(f);
5151
| ----- in this macro invocation
5252
...
53+
LL | $j();
54+
| -- due to this macro variable
55+
...
5356
LL | n!(f);
5457
| ^ not found in this scope
5558
|
@@ -63,6 +66,9 @@ error[E0425]: cannot find function `f` in this scope
6366
LL | n!(f);
6467
| ----- in this macro invocation
6568
...
69+
LL | $j();
70+
| -- due to this macro variable
71+
...
6672
LL | f
6773
| ^ not found in this scope
6874
|

tests/ui/macros/macro-parameter-span.stderr

+3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
error[E0425]: cannot find value `x` in this scope
22
--> $DIR/macro-parameter-span.rs:11:9
33
|
4+
LL | $id
5+
| --- due to this macro variable
6+
...
47
LL | x
58
| ^ not found in this scope
69

tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr

+3
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,9 @@ LL | no_curly__no_rhs_dollar__no_round!(a);
338338
error[E0425]: cannot find value `a` in this scope
339339
--> $DIR/syntax-errors.rs:152:37
340340
|
341+
LL | ( $i:ident ) => { count($i) };
342+
| -- due to this macro variable
343+
...
341344
LL | no_curly__rhs_dollar__no_round!(a);
342345
| ^ not found in this scope
343346

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
macro_rules! dot {
2+
($id:ident) => {
3+
().$id();
4+
}
5+
}
6+
7+
macro_rules! dispatch {
8+
($id:ident) => {
9+
<()>::$id();
10+
}
11+
}
12+
13+
fn main() {
14+
dot!(hello);
15+
//~^ ERROR no method named `hello` found for unit type `()` in the current scope
16+
dispatch!(hello);
17+
//~^ ERROR no function or associated item named `hello` found for unit type `()` in the current scope
18+
}

0 commit comments

Comments
 (0)