Skip to content

Commit fcc50f7

Browse files
committed
Auto merge of rust-lang#124605 - pitaj:lex-guarded-strings, r=<try>
Experiment: Reserve guarded string literal syntax (RFC 3593) on all editions Purpose: crater run to see if we even need to make this change on an edition boundary. This syntax change applies to all editions, because the particular syntax `#"foo"#` is unlikely to exist in the wild. Subset of rust-lang#123951 Tracking issue: rust-lang#123735 RFC: rust-lang/rfcs#3593
2 parents 8387315 + b64c7f4 commit fcc50f7

File tree

11 files changed

+345
-9
lines changed

11 files changed

+345
-9
lines changed

compiler/rustc_lexer/src/cursor.rs

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::str::Chars;
44
///
55
/// Next characters can be peeked via `first` method,
66
/// and position can be shifted forward via `bump` method.
7+
#[derive(Clone)]
78
pub struct Cursor<'a> {
89
len_remaining: usize,
910
/// Iterator over chars. Slightly faster than a &str.

compiler/rustc_lexer/src/lib.rs

+84-8
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ pub mod unescape;
2929
#[cfg(test)]
3030
mod tests;
3131

32+
use std::num::NonZeroU8;
33+
3234
pub use crate::cursor::Cursor;
3335

3436
use self::LiteralKind::*;
@@ -179,24 +181,27 @@ pub enum DocStyle {
179181
/// `rustc_ast::ast::LitKind`).
180182
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
181183
pub enum LiteralKind {
182-
/// "12_u8", "0o100", "0b120i99", "1f32".
184+
/// `12_u8`, `0o100`, `0b120i99`, `1f32`.
183185
Int { base: Base, empty_int: bool },
184-
/// "12.34f32", "1e3", but not "1f32".
186+
/// `12.34f32`, `1e3`, but not `1f32`.
185187
Float { base: Base, empty_exponent: bool },
186-
/// "'a'", "'\\'", "'''", "';"
188+
/// `'a'`, `'\\'`, `'''`, `';`
187189
Char { terminated: bool },
188-
/// "b'a'", "b'\\'", "b'''", "b';"
190+
/// `b'a'`, `b'\\'`, `b'''`, `b';`
189191
Byte { terminated: bool },
190-
/// ""abc"", ""abc"
192+
/// `"abc"`, `"abc`
191193
Str { terminated: bool },
192-
/// "b"abc"", "b"abc"
194+
/// `b"abc"`, `b"abc`
193195
ByteStr { terminated: bool },
194196
/// `c"abc"`, `c"abc`
195197
CStr { terminated: bool },
196-
/// "r"abc"", "r#"abc"#", "r####"ab"###"c"####", "r#"a". `None` indicates
198+
/// `#"abc"#`, `#"a`, `##"a"#`. `None` indicates no closing quote.
199+
/// Allows fewer hashes to close the string to support older editions.
200+
GuardedStr { n_start_hashes: Option<NonZeroU8>, n_end_hashes: u8 },
201+
/// `r"abc"`, `r#"abc"#`, `r####"ab"###"c"####`, `r#"a`. `None` indicates
197202
/// an invalid literal.
198203
RawStr { n_hashes: Option<u8> },
199-
/// "br"abc"", "br#"abc"#", "br####"ab"###"c"####", "br#"a". `None`
204+
/// `br"abc"`, `br#"abc"#`, `br####"ab"###"c"####`, `br#"a`. `None`
200205
/// indicates an invalid literal.
201206
RawByteStr { n_hashes: Option<u8> },
202207
/// `cr"abc"`, "cr#"abc"#", `cr#"a`. `None` indicates an invalid literal.
@@ -365,6 +370,49 @@ impl Cursor<'_> {
365370
_ => self.ident_or_unknown_prefix(),
366371
},
367372

373+
// Guarded string literal (reserved syntax).
374+
'#' if matches!(self.first(), '"' | '#') => {
375+
// Create a backup to restore later if this
376+
// turns out to not be a guarded literal.
377+
let backup = self.clone();
378+
379+
let mut n_start_hashes: u32 = 1; // Already captured one `#`.
380+
while self.first() == '#' {
381+
n_start_hashes += 1;
382+
self.bump();
383+
}
384+
385+
if self.first() == '"' {
386+
self.bump();
387+
388+
let res = self.guarded_double_quoted_string(n_start_hashes);
389+
let suffix_start = self.pos_within_token();
390+
391+
if let (Ok(n_end_hashes), Ok(n)) = (res, u8::try_from(n_start_hashes)) {
392+
self.eat_literal_suffix();
393+
394+
Literal {
395+
kind: GuardedStr {
396+
n_start_hashes: NonZeroU8::new(n),
397+
// Always succeeds because `n_end_hashes <= n`
398+
n_end_hashes: n_end_hashes.try_into().unwrap(),
399+
},
400+
suffix_start,
401+
}
402+
} else {
403+
Literal {
404+
kind: GuardedStr { n_start_hashes: None, n_end_hashes: 0 },
405+
suffix_start,
406+
}
407+
}
408+
} else {
409+
// Not a guarded string, so restore old state.
410+
*self = backup;
411+
// Return a pound token.
412+
Pound
413+
}
414+
}
415+
368416
// Byte literal, byte string literal, raw byte string literal or identifier.
369417
'b' => self.c_or_byte_string(
370418
|terminated| ByteStr { terminated },
@@ -758,6 +806,34 @@ impl Cursor<'_> {
758806
false
759807
}
760808

809+
/// Eats the double-quoted string and returns `n_hashes` and an error if encountered.
810+
fn guarded_double_quoted_string(&mut self, n_start_hashes: u32) -> Result<u32, RawStrError> {
811+
debug_assert!(self.prev() == '"');
812+
813+
// Lex the string itself as a normal string literal
814+
// so we can recover that for older editions later.
815+
if !self.double_quoted_string() {
816+
return Err(RawStrError::NoTerminator {
817+
expected: n_start_hashes,
818+
found: 0,
819+
possible_terminator_offset: None,
820+
});
821+
}
822+
823+
// Consume closing '#' symbols.
824+
// Note that this will not consume extra trailing `#` characters:
825+
// `###"abcde"####` is lexed as a `GuardedStr { n_hashes: 3 }`
826+
// followed by a `#` token.
827+
let mut n_end_hashes = 0;
828+
while self.first() == '#' && n_end_hashes < n_start_hashes {
829+
n_end_hashes += 1;
830+
self.bump();
831+
}
832+
833+
// Handle `n_end_hashes < n_start_hashes` later.
834+
Ok(n_end_hashes)
835+
}
836+
761837
/// Eats the double-quoted string and returns `n_hashes` and an error if encountered.
762838
fn raw_double_quoted_string(&mut self, prefix_len: u32) -> Result<u8, RawStrError> {
763839
// Wrap the actual function to handle the error with too many hashes.

compiler/rustc_parse/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,10 @@ parse_require_colon_after_labeled_expression = labeled expression must be follow
670670
.label = the label
671671
.suggestion = add `:` after the label
672672
673+
parse_reserved_guarded_string = invalid string literal
674+
.note = unprefixed guarded string literals are reserved for future use
675+
.suggestion_whitespace = consider inserting whitespace here
676+
673677
parse_return_types_use_thin_arrow = return types are denoted using `->`
674678
.suggestion = use `->` instead
675679

compiler/rustc_parse/src/errors.rs

+18
Original file line numberDiff line numberDiff line change
@@ -2001,6 +2001,24 @@ pub enum UnknownPrefixSugg {
20012001
},
20022002
}
20032003

2004+
#[derive(Diagnostic)]
2005+
#[diag(parse_reserved_guarded_string)]
2006+
#[note]
2007+
pub struct ReservedGuardedString {
2008+
#[primary_span]
2009+
pub span: Span,
2010+
#[subdiagnostic]
2011+
pub sugg: Option<GuardedStringSugg>,
2012+
}
2013+
#[derive(Subdiagnostic)]
2014+
#[suggestion(
2015+
parse_suggestion_whitespace,
2016+
code = " ",
2017+
applicability = "maybe-incorrect",
2018+
style = "verbose"
2019+
)]
2020+
pub struct GuardedStringSugg(#[primary_span] pub Span);
2021+
20042022
#[derive(Diagnostic)]
20052023
#[diag(parse_too_many_hashes)]
20062024
pub struct TooManyHashes {

compiler/rustc_parse/src/lexer/mod.rs

+24
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,30 @@ impl<'psess, 'src> StringReader<'psess, 'src> {
490490
self.report_raw_str_error(start, 1);
491491
}
492492
}
493+
// RFC 3598 reserved this syntax for future use.
494+
rustc_lexer::LiteralKind::GuardedStr { n_start_hashes, n_end_hashes } => {
495+
let span = self.mk_sp(start, self.pos);
496+
497+
if let Some(n_start_hashes) = n_start_hashes {
498+
let n = u32::from(n_start_hashes.get());
499+
let e = u32::from(n_end_hashes);
500+
let expn_data = span.ctxt().outer_expn_data();
501+
502+
let space_pos = start + BytePos(n);
503+
let space_span = self.mk_sp(space_pos, space_pos);
504+
505+
let sugg = if expn_data.is_root() {
506+
Some(errors::GuardedStringSugg(space_span))
507+
} else {
508+
None
509+
};
510+
511+
self.dcx().emit_err(errors::ReservedGuardedString { span, sugg });
512+
self.cook_unicode(token::Str, Mode::Str, start, end, 1 + n, 1 + e) // ##" "##
513+
} else {
514+
self.dcx().emit_fatal(errors::ReservedGuardedString { span, sugg: None });
515+
}
516+
}
493517
rustc_lexer::LiteralKind::RawByteStr { n_hashes } => {
494518
if let Some(n_hashes) = n_hashes {
495519
let n = u32::from(n_hashes);

src/librustdoc/html/highlight.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -850,7 +850,8 @@ impl<'src> Classifier<'src> {
850850
| LiteralKind::RawStr { .. }
851851
| LiteralKind::RawByteStr { .. }
852852
| LiteralKind::CStr { .. }
853-
| LiteralKind::RawCStr { .. } => Class::String,
853+
| LiteralKind::RawCStr { .. }
854+
| LiteralKind::GuardedStr { .. } => Class::String,
854855
// Number literals.
855856
LiteralKind::Float { .. } | LiteralKind::Int { .. } => Class::Number,
856857
},

src/tools/rust-analyzer/crates/parser/src/lexed_str.rs

+4
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,10 @@ impl<'a> Converter<'a> {
331331
}
332332
C_STRING
333333
}
334+
rustc_lexer::LiteralKind::GuardedStr { .. } => {
335+
err = "Invalid string literal";
336+
STRING
337+
}
334338
};
335339

336340
let err = if err.is_empty() { None } else { Some(err) };

src/tools/rust-analyzer/crates/proc-macro-srv/src/server/rust_analyzer_span.rs

+1
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ impl server::FreeFunctions for RaSpanServer {
120120
3 + n_hashes.unwrap_or_default() as usize,
121121
1 + n_hashes.unwrap_or_default() as usize,
122122
),
123+
LiteralKind::GuardedStr { .. } => return Err(()),
123124
};
124125

125126
let (lit, suffix) = s.split_at(suffix_start as usize);

src/tools/rust-analyzer/crates/proc-macro-srv/src/server/token_id.rs

+1
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ impl server::FreeFunctions for TokenIdServer {
113113
3 + n_hashes.unwrap_or_default() as usize,
114114
1 + n_hashes.unwrap_or_default() as usize,
115115
),
116+
LiteralKind::GuardedStr { .. } => return Err(()),
116117
};
117118

118119
let (lit, suffix) = s.split_at(suffix_start as usize);
+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
//@ compile-flags: -Zunstable-options
2+
//@ edition:2024
3+
4+
macro_rules! demo1 {
5+
( $a:tt ) => { println!("one tokens") };
6+
}
7+
8+
macro_rules! demo2 {
9+
( $a:tt $b:tt ) => { println!("two tokens") };
10+
}
11+
12+
macro_rules! demo3 {
13+
( $a:tt $b:tt $c:tt ) => { println!("three tokens") };
14+
}
15+
16+
macro_rules! demo4 {
17+
( $a:tt $b:tt $c:tt $d:tt ) => { println!("four tokens") };
18+
}
19+
20+
macro_rules! demo5 {
21+
( $a:tt $b:tt $c:tt $d:tt $e:tt ) => { println!("five tokens") };
22+
}
23+
24+
macro_rules! demo6 {
25+
( $a:tt $b:tt $c:tt $d:tt $e:tt $f:tt ) => { println!("six tokens") };
26+
}
27+
28+
macro_rules! demo7 {
29+
( $a:tt $b:tt $c:tt $d:tt $e:tt $f:tt $g:tt ) => { println!("seven tokens") };
30+
}
31+
32+
fn main() {
33+
demo1!("");
34+
demo2!(# "");
35+
demo3!(# ""#);
36+
demo2!(# "foo");
37+
demo3!(## "foo");
38+
demo3!(# "foo"#);
39+
demo4!(### "foo");
40+
demo4!(## "foo"#);
41+
demo7!(### "foo"###);
42+
43+
demo2!("foo"#);
44+
demo4!("foo"###);
45+
46+
demo2!(blah"xx"); //~ ERROR prefix `blah` is unknown
47+
demo2!(blah#"xx"#);
48+
//~^ ERROR prefix `blah` is unknown
49+
//~| ERROR invalid string literal
50+
51+
demo1!(#""); //~ ERROR invalid string literal
52+
demo1!(#""#); //~ ERROR invalid string literal
53+
demo1!(####""); //~ ERROR invalid string literal
54+
demo1!(#"foo"); //~ ERROR invalid string literal
55+
demo1!(###"foo"); //~ ERROR invalid string literal
56+
demo1!(#"foo"#); //~ ERROR invalid string literal
57+
demo1!(###"foo"#); //~ ERROR invalid string literal
58+
demo1!(###"foo"##); //~ ERROR invalid string literal
59+
demo1!(###"foo"###); //~ ERROR invalid string literal
60+
}

0 commit comments

Comments
 (0)