Skip to content

pretty-print: Print shebang at the top of the output #137474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,11 @@ pub fn print_crate<'a>(
let mut s =
State { s: pp::Printer::new(), comments: Some(Comments::new(sm, filename, input)), ann };

// We need to print shebang before anything else
// otherwise the resulting code will not compile
// and shebang will be useless.
s.maybe_print_shebang();

if is_expanded && !krate.attrs.iter().any(|attr| attr.has_name(sym::no_core)) {
// We need to print `#![no_std]` (and its feature gate) so that
// compiling pretty-printed source won't inject libstd again.
Expand Down Expand Up @@ -574,6 +579,20 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
self.word(st)
}

fn maybe_print_shebang(&mut self) {
if let Some(cmnt) = self.peek_comment() {
// Comment is a shebang if it's:
// Isolated, starts with #! and doesn't continue with `[`
// See [rustc_lexer::strip_shebang] and [gather_comments] from pprust/state.rs for details
if cmnt.style == CommentStyle::Isolated
&& cmnt.lines.first().map_or(false, |l| l.starts_with("#!"))
{
let cmnt = self.next_comment().unwrap();
self.print_comment(cmnt);
}
}
}

fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
}
Expand Down
12 changes: 12 additions & 0 deletions tests/pretty/shebang-at-top.pp
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env rust
#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use ::std::prelude::rust_2015::*;
#[macro_use]
extern crate std;
//@ pretty-mode:expanded
//@ pp-exact:shebang-at-top.pp
//@ pretty-compare-only

fn main() {}
6 changes: 6 additions & 0 deletions tests/pretty/shebang-at-top.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env rust
//@ pretty-mode:expanded
//@ pp-exact:shebang-at-top.pp
//@ pretty-compare-only

fn main() {}
Loading