Skip to content

Import suggestion breaks #[cfg] attribute for previous imports #115618

Closed
@marcospb19

Description

@marcospb19

Code

#[cfg(unix)]
use std::os::unix::fs;

fn main() {
    let _ = stdout();

    #[cfg(unix)]
    {
        // Using unix specific stuff here.
        let _function = fs::chroot::<&str>;
    }
}

Current output

error[E0425]: cannot find function `stdout` in this scope
 --> src/main.rs:5:13
  |
5 |     let _ = stdout();
  |             ^^^^^^ not found in this scope
  |
help: consider importing this function
  |
2 + use std::io::stdout;
  |

Desired output

...
help: consider importing this function
  |
3 + use std::io::stdout;
  |

((( with `3` instead of `2` )))

Rationale and extra context

After applying the suggestion, you end up with this code:

#[cfg(unix)]
use std::io::stdout;
use std::os::unix::fs;

fn main() {
    let _ = stdout();

    #[cfg(unix)]
    {
        // Using unix specific stuff here.
        let _function = fs::chroot::<&str>;
    }
}

Note that the cfg(unix) attribute is at the wrong place, so code won't compile on Windows anymore.

I'd say the ideal solution is to either:

  • Suggest import after the last import line.
  • Suggest import following some other rule where it's guaranteed to not fall under an attribute.

Other cases

No response

Anything else?

Comes from rust-lang/rust-enhanced#516 (Sublime Text's "extension" for Rust).

The extension relies on rustc's import suggestions to apply fixes (user is prompted), accepting the fix breaks your code.

Useful label: D-invalid-suggestion

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions