Skip to content

Commit 35cb3ee

Browse files
authored
Unrolled build for rust-lang#137474
Rollup merge of rust-lang#137474 - VlaDexa:shebang-placement, r=wesleywiser pretty-print: Print shebang at the top of the output Shebang should stay at the top of the file, even after pretty-printing. Closes rust-lang#134643
2 parents f97b3c6 + 3d41095 commit 35cb3ee

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
@@ -240,6 +240,11 @@ pub fn print_crate<'a>(
240240
let mut s =
241241
State { s: pp::Printer::new(), comments: Some(Comments::new(sm, filename, input)), ann };
242242

243+
// We need to print shebang before anything else
244+
// otherwise the resulting code will not compile
245+
// and shebang will be useless.
246+
s.maybe_print_shebang();
247+
243248
if is_expanded && !krate.attrs.iter().any(|attr| attr.has_name(sym::no_core)) {
244249
// We need to print `#![no_std]` (and its feature gate) so that
245250
// compiling pretty-printed source won't inject libstd again.
@@ -560,6 +565,20 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
560565
self.word(st)
561566
}
562567

568+
fn maybe_print_shebang(&mut self) {
569+
if let Some(cmnt) = self.peek_comment() {
570+
// Comment is a shebang if it's:
571+
// Isolated, starts with #! and doesn't continue with `[`
572+
// See [rustc_lexer::strip_shebang] and [gather_comments] from pprust/state.rs for details
573+
if cmnt.style == CommentStyle::Isolated
574+
&& cmnt.lines.first().map_or(false, |l| l.starts_with("#!"))
575+
{
576+
let cmnt = self.next_comment().unwrap();
577+
self.print_comment(cmnt);
578+
}
579+
}
580+
}
581+
563582
fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
564583
self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
565584
}

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)