Skip to content

Commit 3d41095

Browse files
committed
Put shebang at the top of pretty-print
1 parent 15469f8 commit 3d41095

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

compiler/rustc_ast_pretty/src/pprust/state.rs

+19
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,11 @@ pub fn print_crate<'a>(
243243
let mut s =
244244
State { s: pp::Printer::new(), comments: Some(Comments::new(sm, filename, input)), ann };
245245

246+
// We need to print shebang before anything else
247+
// otherwise the resulting code will not compile
248+
// and shebang will be useless.
249+
s.maybe_print_shebang();
250+
246251
if is_expanded && !krate.attrs.iter().any(|attr| attr.has_name(sym::no_core)) {
247252
// We need to print `#![no_std]` (and its feature gate) so that
248253
// compiling pretty-printed source won't inject libstd again.
@@ -574,6 +579,20 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
574579
self.word(st)
575580
}
576581

582+
fn maybe_print_shebang(&mut self) {
583+
if let Some(cmnt) = self.peek_comment() {
584+
// Comment is a shebang if it's:
585+
// Isolated, starts with #! and doesn't continue with `[`
586+
// See [rustc_lexer::strip_shebang] and [gather_comments] from pprust/state.rs for details
587+
if cmnt.style == CommentStyle::Isolated
588+
&& cmnt.lines.first().map_or(false, |l| l.starts_with("#!"))
589+
{
590+
let cmnt = self.next_comment().unwrap();
591+
self.print_comment(cmnt);
592+
}
593+
}
594+
}
595+
577596
fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
578597
self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
579598
}

tests/pretty/shebang-at-top.pp

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env rust
2+
#![feature(prelude_import)]
3+
#![no_std]
4+
#[prelude_import]
5+
use ::std::prelude::rust_2015::*;
6+
#[macro_use]
7+
extern crate std;
8+
//@ pretty-mode:expanded
9+
//@ pp-exact:shebang-at-top.pp
10+
//@ pretty-compare-only
11+
12+
fn main() {}

tests/pretty/shebang-at-top.rs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#!/usr/bin/env rust
2+
//@ pretty-mode:expanded
3+
//@ pp-exact:shebang-at-top.pp
4+
//@ pretty-compare-only
5+
6+
fn main() {}

0 commit comments

Comments
 (0)