Skip to content

Commit c748002

Browse files
committed
rovide helpful diagnostics for shebang lookalikes
1 parent a18bd8a commit c748002

File tree

5 files changed

+28
-1
lines changed

5 files changed

+28
-1
lines changed

Diff for: compiler/rustc_parse/src/parser/attr.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,22 @@ impl<'a> Parser<'a> {
125125
let lo = self.token.span;
126126
// Attributes can't have attributes of their own [Editor's note: not with that attitude]
127127
self.collect_tokens_no_attrs(|this| {
128+
let pound_hi = this.token.span.hi();
128129
assert!(this.eat(exp!(Pound)), "parse_attribute called in non-attribute position");
129130

131+
let not_lo = this.token.span.lo();
130132
let style =
131133
if this.eat(exp!(Not)) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer };
132134

133-
this.expect(exp!(OpenBracket))?;
135+
let mut bracket_res = this.expect(exp!(OpenBracket));
136+
// If `#!` is not followed by `[`
137+
if let Err(err) = &mut bracket_res
138+
&& style == ast::AttrStyle::Inner
139+
&& pound_hi == not_lo
140+
{
141+
err.note("shebangs `#!` must be at the start of the file");
142+
}
143+
bracket_res?;
134144
let item = this.parse_attr_item(ForceCollect::No)?;
135145
this.expect(exp!(CloseBracket))?;
136146
let attr_sp = lo.to(this.prev_token.span);

Diff for: tests/ui/parser/shebang/issue-71471-ignore-tidy.stderr

+2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ error: expected `[`, found `B`
33
|
44
LL | #!B
55
| ^ expected `[`
6+
|
7+
= note: shebangs `#!` must be at the start of the file
68

79
error: aborting due to 1 previous error
810

Diff for: tests/ui/parser/shebang/shebang-must-start-file.stderr

+2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ error: expected `[`, found `/`
33
|
44
LL | #!/bin/bash
55
| ^ expected `[`
6+
|
7+
= note: shebangs `#!` must be at the start of the file
68

79
error: aborting due to 1 previous error
810

Diff for: tests/ui/parser/shebang/shebang-split.rs

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// empty line
2+
# !/bin/env
3+
4+
//@ reference: input.shebang
5+
//@ error-pattern: expected `[`\n\n

Diff for: tests/ui/parser/shebang/shebang-split.stderr

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
error: expected `[`, found `/`
2+
--> $DIR/shebang-split.rs:2:4
3+
|
4+
LL | # !/bin/env
5+
| ^ expected `[`
6+
7+
error: aborting due to 1 previous error
8+

0 commit comments

Comments
 (0)