Skip to content

prevent checking redundant_field_names lint on Derived code - #17555

Closed
azdle wants to merge 3 commits into
rust-lang:masterfrom
azdle:rfn-on-derive-bug
Closed

azdle wants to merge 3 commits into
rust-lang:masterfrom
azdle:rfn-on-derive-bug

Conversation

@azdle

@azdle azdle commented Aug 12, 2026 •

Copy link
Copy Markdown

View all comments

This check was removed in #17294 and replaced with a later per-field check, however the field's spans can (maybe always do?) point back to the fields in the original struct declaration for struct expressions in derived code. This was causing this lint to warn on derive-generated code.

I wrote a more complete explanation here: #17525 (comment)

changelog: [redundant_field_names]: don't check derived expressions

Fixes: #17525

@rustbot rustbot added S-waiting-on-community-reviews Status: This is awaiting for positive reviews from the community before a maintainer is assigned. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties labels Aug 12, 2026
@rustbot

rustbot commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the pull request, and welcome!

You should hear from one of our reviewers after this PR gets at least 2 reviews from the community.

Please see the contribution instructions for more information. Namely, in order to ensure the minimum review times lag, PR authors and assigned reviewers should ensure that the review label (S-waiting-on-review and S-waiting-on-author) stays updated, invoking these commands when appropriate:

  • @rustbot author: the review is finished, PR author should check the comments and take action accordingly
  • @rustbot review: the author is ready for a review, this PR will be queued again in the reviewer's queue

@azdle

azdle commented Aug 12, 2026

Copy link
Copy Markdown
Author

Also, I should say, I didn't add a test for this because I would need a proc macro crate to generate code that would always, itself, fail the lint. As far as I can tell there isn't one for that yet and adding a dedicated crate for that to the test suite would dwarf this change and I wasn't sure if I should or not. I'm happy to add that if it's wanted.

@Jarcho Jarcho left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't fix all the ways proc-macros can mess up when generating code. In thiserror it's generating $field: $field as though it were in the callers context even though the colon should have the macro's context. It happens to generate the expression as a whole in the correct context, but nothing stops macros from messing that up as well.

After the current in_external_macro check you can add:

field.span.check_text(cx, |src| {
  let field_name = field.ident.as_str();
  src.strip_prefix(name)
    .and_then(|src| src.strip_suffix(name))
    .is_some_and(|src| src.trim() == ":")
})

View changes since this review

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action from the author. (Use `@rustbot ready` to update this status) and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties labels Aug 12, 2026
@rustbot

rustbot commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@Jarcho

Jarcho commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

To add a test you can use

use proc_macros::with_span;
with_span! {
  field_name
  Struct { field_name: field_name }
}

The macro skips the first token and outputs the rest with the span of each set to the first token. This emulates the problematic code gen of other proc-macros.

@azdle

azdle commented Aug 13, 2026

Copy link
Copy Markdown
Author

To add a test you can use

use proc_macros::with_span;
with_span! {
  field_name
  Struct { field_name: field_name }
}

The macro skips the first token and outputs the rest with the span of each set to the first token. This emulates the problematic code gen of other proc-macros.

I'm not quite sure I understand this suggestion. In playing with it in a test, the lint produces warnings for code on the second line with or without the fix I'm suggesting. The expression as a whole still has a span that is in_external_macro -> false. Which feels correct to me since the 'macro code' is still written locally in the test. So, I don't think that's quite the same case. But, maybe I misunderstood your intention and/or what with_span! does?

Though, I did also discover tests/ui/auxiliary/proc_macro_derive.rs, which I assume would be built as 'external macros' for the tests (that's the only way proc macros work, right?), so using a macro from there would end up with an expression that is in_external_macro -> true. I would just need to add a macro in there that uses the input TokenStream to get the field names (who's spans are in_external_macro -> false) and use those write some redundant field names to test the exact case I was originally trying to fix. Does that sound like a reasonable way to test this?

I haven't had the time to fully understand your first comment yet, so apologies if I'm completely speaking past any context from that.

@Jarcho

Jarcho commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

with_span exists to emulates the bad token output of other proc-macros so we don't have to write an endless number of them. Usually the tokens are output with something like quote_spanned!(name.span=> Struct { $name: $name ) which would make every token share the same span, none of which are marked as being from a macro.

@azdle
azdle force-pushed the rfn-on-derive-bug branch from 3e13057 to 2425efc Compare August 13, 2026 21:32
@rustbot

This comment has been minimized.

@azdle
azdle force-pushed the rfn-on-derive-bug branch from 2425efc to c814fdd Compare August 13, 2026 21:33
@azdle

azdle commented Aug 13, 2026 •

Copy link
Copy Markdown
Author

which would make every token share the same span, none of which are marked as being from a macro.

Assuming this is also true about the with_span, that wouldn't be able to trigger the bug then. There isn't a problem when all of the spans marked as being from a macro or when all the spans are not marked as being from a macro.

The bug is specifically when only the fields' idents are not from a macro, but the outer construction/format of the struct expression is. Which I think is how these macros are generally intended to be built, so I don't think this is a case of 'all the ways proc-macros can mess up when generating code'.

I threw a separate commit in with a test on a super simple derive proc macro (with no span overrides at all) that fails before the existing fix commit that I hope shows what I mean.

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties and removed S-waiting-on-author Status: This is awaiting some action from the author. (Use `@rustbot ready` to update this status) labels Aug 13, 2026
@Jarcho

Jarcho commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

The bug is entirely that the field span is being marked incorrectly because all three tokens are given the same span. When the macro outputs foo: foo with all tokens having the same span the expression field's span then gets exactly the same span. Anything else the macro outputs is irrelevant to this since the span of the generation of the expression field is the broken part. We catch this by checking the source text of the field expression to see if it matches what we expect it to. This is the most reliable thing we can use.

@azdle

azdle commented Aug 13, 2026

Copy link
Copy Markdown
Author

The bug is entirely that the field span is being marked incorrectly because all three tokens are given the same span. When the macro outputs foo: foo with all tokens having the same span [...]

They don't all have the same span.

In the returned TokenStream in my test the two v are in span 0, but the colon between them is in span 9.

    Group {
        delimiter: Brace,
        stream: TokenStream [
            Ident {
                ident: "DerivedS",
                span: #0 bytes(2011..2019),
            },
            Group {
                delimiter: Brace,
                stream: TokenStream [
                    Ident {
                        ident: "v",
                        span: #0 bytes(2030..2031),
                    },
                    Punct {
                        ch: ':',
                        spacing: Alone,
                        span: #9 bytes(1944..1997),
                    },
                    Ident {
                        ident: "v",
                        span: #0 bytes(2030..2031),
                    },
                ],
                span: #9 bytes(1944..1997),
            },
        ],
        span: #9 bytes(1944..1997),
    },

@Jarcho

Jarcho commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

Looking further it looks like rustc actually ignores the colon token, which is just wrong since it loses the context the expression field was written in.

@CommanderStorm CommanderStorm left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

community review:
not sure if this should have is_from_proc_macro too. What do you think?

@rustbot author

View changes since this review

Comment on lines +52 to +54
if expr.span.in_external_macro(cx.sess().source_map()) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

usually, there is an is_from_proc_macro check right next to this I think.
Is it purposely ommitted?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I omitted it because it didn't seem to be necessary in my testing and I figured it would be better to revert less since the reason it was removed was for performance reasons. But I can't say I know for sure why it was there or why it was removed in the first place.

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action from the author. (Use `@rustbot ready` to update this status) and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties labels Aug 27, 2026
Comment on lines 52 to 56
if expr.span.in_external_macro(cx.sess().source_map()) {
return;
}
if let ExprKind::Struct(ref se) = expr.kind
&& self.msrv.meets(msrvs::FIELD_INIT_SHORTHAND)

@CommanderStorm CommanderStorm Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After looking at #17684 I think this would be better because the kind-if-let is super cheap..

Suggested change
if expr.span.in_external_macro(cx.sess().source_map()) {
return;
}
if let ExprKind::Struct(ref se) = expr.kind
&& self.msrv.meets(msrvs::FIELD_INIT_SHORTHAND)
if let ExprKind::Struct(ref se) = expr.kind
&& self.msrv.meets(msrvs::FIELD_INIT_SHORTHAND)
&& expr.span.in_external_macro(cx.sess().source_map())

View changes since the review

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That seems reasonable to me. Applied this change (though with the necessary !), the tests all still pass.

&& segment.args.is_none()
&& segment.ident == field.ident
&& field.span.eq_ctxt(field.ident.span)
&& !field.span.in_external_macro(cx.sess().source_map())

@CommanderStorm CommanderStorm Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also from #17684

can this still happen if we have !expr.span.in_external_macro iterate on the fields, find it an shorthand...

How about this? (removing !field.span.in_external_macro..)

Suggested change

View changes since the review

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left this in because I think it's more technically correct to leave it in. I suspect (but didn't prove) that if you had a macro that generates struct fields, but not the whole struct body, you'd possibly get false positives out of this with just the check on expr and not also on field.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't make my last point very clearly, what I meant was it seems like it would be more technically correct if the field.span.in_external_macro call worked like it seems like it should. I can't think of a case where it'll do anything with the current behavior of that call.

So removing it will currently do nothing, but I think it makes sense to leave in under the assumption that the behavior of field.span.in_external_macro will get fixed.

@azdle

azdle commented Oct 6, 2026

Copy link
Copy Markdown
Author

@CommanderStorm, sorry I didn't see your review until now. I forgot this was a thing until some automation tried to update our project to building with rust v1.99.0 and failed on these errors again.

Since it's been awhile, here's a quick summary of what I think is going on here:

#17294 removed a check on expr.span.in_external_macro, replacing it with a check on field.span.in_external_macro for each field in the macro expression. This is probably more technically correct. However, rustc places the field at the span of the original field name when a proc macro emits something like #field_name: #field_name, ignoring that the construction of the whole field happened in the proc macro.

That seems like something that should probably be fixed in rustc, but since that never happened and the original issue has gotten a lot of pings from being mentioned in issues and workarounds, I think this is probably still worth reverting back to including the old check until that does get fixed.

@CommanderStorm CommanderStorm left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Community review: lgtm from my side I guess

View changes since this review

@rustbot

This comment has been minimized.

@azdle
azdle force-pushed the rfn-on-derive-bug branch from 5759302 to d846193 Compare October 7, 2026 21:41
@rustbot

rustbot commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different master commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@CommanderStorm

Copy link
Copy Markdown
Contributor

@rustbot ready

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties and removed S-waiting-on-author Status: This is awaiting some action from the author. (Use `@rustbot ready` to update this status) labels Oct 23, 2026
@Jarcho

Jarcho commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

The issue has been fixed upstream.

@Jarcho Jarcho closed this Oct 25, 2026
@rustbot rustbot removed S-waiting-on-community-reviews Status: This is awaiting for positive reviews from the community before a maintainer is assigned. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties labels Oct 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

redundant_field_names triggered on derived code

4 participants