Skip to content

rustfmt leaves behind a too-long line inside a closure #6344

Open
@RalfJung

Description

@RalfJung

Here's some example code:

impl<'tcx> LateLintPass<'tcx> for UnqualifiedLocalImports {
    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
        let hir::ItemKind::Use(path, _kind) = item.kind else { return };
        let is_local_import = |res: &Res| {
            matches!(res, hir::def::Res::Def(def_kind, def_id) if def_id.is_local() && !matches!(def_kind, DefKind::Macro(_)))
        };
    }
}

It's not the best code, that line is too long. So let's format it. Now we have:

impl<'tcx> LateLintPass<'tcx> for UnqualifiedLocalImports {
    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
        let hir::ItemKind::Use(path, _kind) = item.kind else {
            return;
        };
        let is_local_import = |res: &Res| matches!(res, hir::def::Res::Def(def_kind, def_id) if def_id.is_local() && !matches!(def_kind, DefKind::Macro(_)));
    }
}

Now the line is even longer! It's way past the 100 character limit.

I guess rustfmt is reluctant to introduce linebreaks inside a macro, but then it should just avoid touching this code -- but instead it makes things worse by putting the entire closure on a single line.

Activity

ytmimi

ytmimi commented on Sep 22, 2024

@ytmimi
Contributor

This is a case where the macro fails to parse, and I assume that since it's formatted on one line and the closure only contains a single item rustfmt really wants to update the closure to not use braces.

If you formatted the matches! call by hand like this rustfmt should leave it alone:

impl<'tcx> LateLintPass<'tcx> for UnqualifiedLocalImports {
    fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
        let hir::ItemKind::Use(path, _kind) = item.kind else { return };
        let is_local_import = |res: &Res| {
            matches!(
                res,
                hir::def::Res::Def(def_kind, def_id)
                    if def_id.is_local() && !matches!(def_kind, DefKind::Macro(_))
            )
        };
    }
}

I'll add that If #5554 lands that's the formatting that the input would produce.

added
e-max widtherror[internal]: line formatted, but exceeded maximum width
on Sep 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @RalfJung@ytmimi

        Issue actions

          rustfmt leaves behind a too-long line inside a closure · Issue #6344 · rust-lang/rustfmt