Skip to content

Commit f9d7e1a

Browse files
Deny keyword lifetimes pre-expansion
1 parent cb8a7ea commit f9d7e1a

14 files changed

+102
-71
lines changed

compiler/rustc_ast_passes/messages.ftl

-6
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,6 @@ ast_passes_inherent_cannot_be = inherent impls cannot be {$annotation}
156156
.type = inherent impl for this type
157157
.only_trait = only trait implementations may be annotated with {$annotation}
158158
159-
ast_passes_invalid_label =
160-
invalid label name `{$name}`
161-
162159
ast_passes_invalid_unnamed_field =
163160
unnamed fields are not allowed outside of structs or unions
164161
.label = unnamed field declared here
@@ -170,9 +167,6 @@ ast_passes_invalid_unnamed_field_ty =
170167
ast_passes_item_underscore = `{$kind}` items in this context need a name
171168
.label = `_` is not a valid name for this `{$kind}` item
172169
173-
ast_passes_keyword_lifetime =
174-
lifetimes cannot use keyword names
175-
176170
ast_passes_match_arm_with_no_body =
177171
`match` arm with no body
178172
.suggestion = add a body after the pattern

compiler/rustc_ast_passes/src/ast_validation.rs

-30
Original file line numberDiff line numberDiff line change
@@ -274,19 +274,6 @@ impl<'a> AstValidator<'a> {
274274
self.session.dcx()
275275
}
276276

277-
fn check_lifetime(&self, ident: Ident) {
278-
let valid_names = [kw::UnderscoreLifetime, kw::StaticLifetime, kw::Empty];
279-
if !valid_names.contains(&ident.name) && ident.without_first_quote().is_reserved() {
280-
self.dcx().emit_err(errors::KeywordLifetime { span: ident.span });
281-
}
282-
}
283-
284-
fn check_label(&self, ident: Ident) {
285-
if ident.without_first_quote().is_reserved() {
286-
self.dcx().emit_err(errors::InvalidLabel { span: ident.span, name: ident.name });
287-
}
288-
}
289-
290277
fn visibility_not_permitted(&self, vis: &Visibility, note: errors::VisibilityNotPermittedNote) {
291278
if let VisibilityKind::Inherited = vis.kind {
292279
return;
@@ -892,16 +879,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
892879
self.walk_ty(ty)
893880
}
894881

895-
fn visit_label(&mut self, label: &'a Label) {
896-
self.check_label(label.ident);
897-
visit::walk_label(self, label);
898-
}
899-
900-
fn visit_lifetime(&mut self, lifetime: &'a Lifetime, _: visit::LifetimeCtxt) {
901-
self.check_lifetime(lifetime.ident);
902-
visit::walk_lifetime(self, lifetime);
903-
}
904-
905882
fn visit_field_def(&mut self, field: &'a FieldDef) {
906883
self.deny_unnamed_field(field);
907884
visit::walk_field_def(self, field)
@@ -1328,13 +1305,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
13281305
}
13291306
}
13301307

1331-
fn visit_generic_param(&mut self, param: &'a GenericParam) {
1332-
if let GenericParamKind::Lifetime { .. } = param.kind {
1333-
self.check_lifetime(param.ident);
1334-
}
1335-
visit::walk_generic_param(self, param);
1336-
}
1337-
13381308
fn visit_param_bound(&mut self, bound: &'a GenericBound, ctxt: BoundKind) {
13391309
match bound {
13401310
GenericBound::Trait(trait_ref, modifiers) => {

compiler/rustc_ast_passes/src/errors.rs

-15
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,6 @@ use rustc_span::{symbol::Ident, Span, Symbol};
99

1010
use crate::fluent_generated as fluent;
1111

12-
#[derive(Diagnostic)]
13-
#[diag(ast_passes_keyword_lifetime)]
14-
pub struct KeywordLifetime {
15-
#[primary_span]
16-
pub span: Span,
17-
}
18-
19-
#[derive(Diagnostic)]
20-
#[diag(ast_passes_invalid_label)]
21-
pub struct InvalidLabel {
22-
#[primary_span]
23-
pub span: Span,
24-
pub name: Symbol,
25-
}
26-
2712
#[derive(Diagnostic)]
2813
#[diag(ast_passes_visibility_not_permitted, code = E0449)]
2914
pub struct VisibilityNotPermitted {

compiler/rustc_parse/messages.ftl

+6
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,9 @@ parse_invalid_dyn_keyword = invalid `dyn` keyword
392392
parse_invalid_expression_in_let_else = a `{$operator}` expression cannot be directly assigned in `let...else`
393393
parse_invalid_identifier_with_leading_number = identifiers cannot start with a number
394394
395+
parse_invalid_label =
396+
invalid label name `{$name}`
397+
395398
parse_invalid_literal_suffix_on_tuple_index = suffixes on a tuple index are invalid
396399
.label = invalid suffix `{$suffix}`
397400
.tuple_exception_line_1 = `{$suffix}` is *temporarily* accepted on tuple index fields as it was incorrectly accepted on stable for a few releases
@@ -418,6 +421,9 @@ parse_invalid_unicode_escape = invalid unicode character escape
418421
parse_invalid_variable_declaration =
419422
invalid variable declaration
420423
424+
parse_keyword_lifetime =
425+
lifetimes cannot use keyword names
426+
421427
parse_kw_bad_case = keyword `{$kw}` is written in the wrong case
422428
.suggestion = write it in the correct case
423429

compiler/rustc_parse/src/errors.rs

+15
Original file line numberDiff line numberDiff line change
@@ -1907,6 +1907,21 @@ pub struct CannotBeRawIdent {
19071907
pub ident: Symbol,
19081908
}
19091909

1910+
#[derive(Diagnostic)]
1911+
#[diag(parse_keyword_lifetime)]
1912+
pub struct KeywordLifetime {
1913+
#[primary_span]
1914+
pub span: Span,
1915+
}
1916+
1917+
#[derive(Diagnostic)]
1918+
#[diag(parse_invalid_label)]
1919+
pub struct InvalidLabel {
1920+
#[primary_span]
1921+
pub span: Span,
1922+
pub name: Symbol,
1923+
}
1924+
19101925
#[derive(Diagnostic)]
19111926
#[diag(parse_cr_doc_comment)]
19121927
pub struct CrDocComment {

compiler/rustc_parse/src/parser/expr.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -2922,10 +2922,17 @@ impl<'a> Parser<'a> {
29222922
}
29232923

29242924
pub(crate) fn eat_label(&mut self) -> Option<Label> {
2925-
self.token.lifetime().map(|ident| {
2925+
if let Some(ident) = self.token.lifetime() {
2926+
// Disallow `'fn`, but with a better error message than `expect_lifetime`.
2927+
if ident.without_first_quote().is_reserved() {
2928+
self.dcx().emit_err(errors::InvalidLabel { span: ident.span, name: ident.name });
2929+
}
2930+
29262931
self.bump();
2927-
Label { ident }
2928-
})
2932+
Some(Label { ident })
2933+
} else {
2934+
None
2935+
}
29292936
}
29302937

29312938
/// Parses a `match ... { ... }` expression (`match` token already eaten).

compiler/rustc_parse/src/parser/nonterminal.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,11 @@ impl<'a> Parser<'a> {
182182
.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?))
183183
}
184184
NonterminalKind::Lifetime => {
185-
return if self.check_lifetime() {
186-
Ok(ParseNtResult::Lifetime(self.expect_lifetime().ident))
185+
// We want to keep `'keyword` parsing, just like `keyword` is still
186+
// an ident for nonterminal purposes.
187+
return if let Some(ident) = self.token.lifetime() {
188+
self.bump();
189+
Ok(ParseNtResult::Lifetime(ident))
187190
} else {
188191
Err(self.dcx().create_err(UnexpectedNonterminal::Lifetime {
189192
span: self.token.span,

compiler/rustc_parse/src/parser/pat.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -538,12 +538,12 @@ impl<'a> Parser<'a> {
538538
None => PatKind::Path(qself, path),
539539
}
540540
}
541-
} else if let token::Lifetime(lt) = self.token.kind
541+
} else if let Some(lt) = self.token.lifetime()
542542
// In pattern position, we're totally fine with using "next token isn't colon"
543543
// as a heuristic. We could probably just always try to recover if it's a lifetime,
544544
// because we never have `'a: label {}` in a pattern position anyways, but it does
545545
// keep us from suggesting something like `let 'a: Ty = ..` => `let 'a': Ty = ..`
546-
&& could_be_unclosed_char_literal(Ident::with_dummy_span(lt))
546+
&& could_be_unclosed_char_literal(lt)
547547
&& !self.look_ahead(1, |token| matches!(token.kind, token::Colon))
548548
{
549549
// Recover a `'a` as a `'a'` literal
@@ -671,11 +671,13 @@ impl<'a> Parser<'a> {
671671
/// Parse `&pat` / `&mut pat`.
672672
fn parse_pat_deref(&mut self, expected: Option<Expected>) -> PResult<'a, PatKind> {
673673
self.expect_and()?;
674-
if let token::Lifetime(name) = self.token.kind {
674+
if let Some(lifetime) = self.token.lifetime() {
675675
self.bump(); // `'a`
676676

677-
self.dcx()
678-
.emit_err(UnexpectedLifetimeInPattern { span: self.prev_token.span, symbol: name });
677+
self.dcx().emit_err(UnexpectedLifetimeInPattern {
678+
span: self.prev_token.span,
679+
symbol: lifetime.name,
680+
});
679681
}
680682

681683
let mutbl = self.parse_mutability();

compiler/rustc_parse/src/parser/ty.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1205,6 +1205,12 @@ impl<'a> Parser<'a> {
12051205
/// Parses a single lifetime `'a` or panics.
12061206
pub(super) fn expect_lifetime(&mut self) -> Lifetime {
12071207
if let Some(ident) = self.token.lifetime() {
1208+
if ident.without_first_quote().is_reserved()
1209+
&& ![kw::UnderscoreLifetime, kw::StaticLifetime].contains(&ident.name)
1210+
{
1211+
self.dcx().emit_err(errors::KeywordLifetime { span: ident.span });
1212+
}
1213+
12081214
self.bump();
12091215
Lifetime { ident, id: ast::DUMMY_NODE_ID }
12101216
} else {
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Disallow `'keyword` even in cfg'd code.
2+
3+
#[cfg(any())]
4+
fn hello() -> &'ref () {}
5+
//~^ ERROR lifetimes cannot use keyword names
6+
7+
macro_rules! macro_invocation {
8+
($i:item) => {}
9+
}
10+
macro_invocation! {
11+
fn hello() -> &'ref () {}
12+
//~^ ERROR lifetimes cannot use keyword names
13+
}
14+
15+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
error: lifetimes cannot use keyword names
2+
--> $DIR/cfg-keyword-lifetime.rs:4:16
3+
|
4+
LL | fn hello() -> &'ref () {}
5+
| ^^^^
6+
7+
error: lifetimes cannot use keyword names
8+
--> $DIR/cfg-keyword-lifetime.rs:11:20
9+
|
10+
LL | fn hello() -> &'ref () {}
11+
| ^^^^
12+
13+
error: aborting due to 2 previous errors
14+

tests/ui/parser/require-parens-for-chained-comparison.rs

+2
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,14 @@ fn main() {
2424
//~| HELP use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments
2525
//~| ERROR expected
2626
//~| HELP add `'` to close the char literal
27+
//~| ERROR invalid label name
2728

2829
f<'_>();
2930
//~^ comparison operators cannot be chained
3031
//~| HELP use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments
3132
//~| ERROR expected
3233
//~| HELP add `'` to close the char literal
34+
//~| ERROR invalid label name
3335

3436
let _ = f<u8>;
3537
//~^ ERROR comparison operators cannot be chained

tests/ui/parser/require-parens-for-chained-comparison.stderr

+16-4
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ help: use `::<...>` instead of `<...>` to specify lifetime, type, or const argum
5353
LL | let _ = f::<u8, i8>();
5454
| ++
5555

56+
error: invalid label name `'_`
57+
--> $DIR/require-parens-for-chained-comparison.rs:22:15
58+
|
59+
LL | let _ = f<'_, i8>();
60+
| ^^
61+
5662
error: expected `while`, `for`, `loop` or `{` after a label
5763
--> $DIR/require-parens-for-chained-comparison.rs:22:17
5864
|
@@ -75,8 +81,14 @@ help: use `::<...>` instead of `<...>` to specify lifetime, type, or const argum
7581
LL | let _ = f::<'_, i8>();
7682
| ++
7783

84+
error: invalid label name `'_`
85+
--> $DIR/require-parens-for-chained-comparison.rs:29:7
86+
|
87+
LL | f<'_>();
88+
| ^^
89+
7890
error: expected `while`, `for`, `loop` or `{` after a label
79-
--> $DIR/require-parens-for-chained-comparison.rs:28:9
91+
--> $DIR/require-parens-for-chained-comparison.rs:29:9
8092
|
8193
LL | f<'_>();
8294
| ^ expected `while`, `for`, `loop` or `{` after a label
@@ -87,7 +99,7 @@ LL | f<'_'>();
8799
| +
88100

89101
error: comparison operators cannot be chained
90-
--> $DIR/require-parens-for-chained-comparison.rs:28:6
102+
--> $DIR/require-parens-for-chained-comparison.rs:29:6
91103
|
92104
LL | f<'_>();
93105
| ^ ^
@@ -98,13 +110,13 @@ LL | f::<'_>();
98110
| ++
99111

100112
error: comparison operators cannot be chained
101-
--> $DIR/require-parens-for-chained-comparison.rs:34:14
113+
--> $DIR/require-parens-for-chained-comparison.rs:36:14
102114
|
103115
LL | let _ = f<u8>;
104116
| ^ ^
105117
|
106118
= help: use `::<...>` instead of `<...>` to specify lifetime, type, or const arguments
107119
= help: or use `(...)` if you meant to specify fn arguments
108120

109-
error: aborting due to 10 previous errors
121+
error: aborting due to 12 previous errors
110122

tests/ui/self/self_type_keyword.stderr

+6-6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@ error: expected identifier, found keyword `Self`
44
LL | struct Self;
55
| ^^^^ expected identifier, found keyword
66

7+
error: lifetimes cannot use keyword names
8+
--> $DIR/self_type_keyword.rs:6:12
9+
|
10+
LL | struct Bar<'Self>;
11+
| ^^^^^
12+
713
error: expected identifier, found keyword `Self`
814
--> $DIR/self_type_keyword.rs:14:13
915
|
@@ -48,12 +54,6 @@ error: expected identifier, found keyword `Self`
4854
LL | trait Self {}
4955
| ^^^^ expected identifier, found keyword
5056

51-
error: lifetimes cannot use keyword names
52-
--> $DIR/self_type_keyword.rs:6:12
53-
|
54-
LL | struct Bar<'Self>;
55-
| ^^^^^
56-
5757
error: cannot find macro `Self` in this scope
5858
--> $DIR/self_type_keyword.rs:21:9
5959
|

0 commit comments

Comments
 (0)