| 1 |
//! Macro support for format strings |
| 2 |
//! |
| 3 |
//! These structures are used when parsing format strings for the compiler. |
| 4 |
//! Parsing does not happen at runtime: structures of `std::fmt::rt` are |
| 5 |
//! generated instead. |
| 6 |
|
| 7 |
#![doc( |
| 8 |
html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/", |
| 9 |
html_playground_url = "https://play.rust-lang.org/", |
| 10 |
test(attr(deny(warnings))) |
| 11 |
)] |
| 12 |
#![deny(rustc::untranslatable_diagnostic)] |
| 13 |
#![deny(rustc::diagnostic_outside_of_impl)] |
| 14 |
// WARNING: We want to be able to build this crate with a stable compiler, |
| 15 |
// so no `#![feature]` attributes should be added! |
| 16 |
|
| 17 |
fn is_id_start(c: char) -> bool { |
| 18 |
c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) |
| 19 |
} |
| 20 |
|
| 21 |
fn is_id_continue(c: char) -> bool { |
| 22 |
unicode_xid::UnicodeXID::is_xid_continue(c) |
| 23 |
} |
| 24 |
|
| 25 |
// use rustc_lexer::unescape; |
| 26 |
pub use Alignment::*; |
| 27 |
pub use Count::*; |
| 28 |
pub use Piece::*; |
| 29 |
pub use Position::*; |
| 30 |
|
| 31 |
use std::iter; |
| 32 |
use std::str; |
| 33 |
use std::string; |
| 34 |
|
| 35 |
// Extension trait for `Option<T>::is_some_and()` which was not a feature in Rust 1.49 |
| 36 |
pub trait OptionIsSomeAndExt<T> { |
| 37 |
fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool; |
| 38 |
} |
| 39 |
|
| 40 |
impl<T> OptionIsSomeAndExt<T> for Option<T> { |
| 41 |
fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool { |
| 42 |
match self { |
| 43 |
None => false, |
| 44 |
Some(x) => f(x), |
| 45 |
} |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
// Note: copied from rustc_span |
| 50 |
/// Range inside of a `Span` used for diagnostics when we only have access to relative positions. |
| 51 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 52 |
pub struct InnerSpan { |
| 53 |
pub start: usize, |
| 54 |
pub end: usize, |
| 55 |
} |
| 56 |
|
| 57 |
impl InnerSpan { |
| 58 |
pub fn new(start: usize, end: usize) -> InnerSpan { |
| 59 |
InnerSpan { start, end } |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
/// The location and before/after width of a character whose width has changed from its source code |
| 64 |
/// representation |
| 65 |
#[derive(Copy, Clone, PartialEq, Eq)] |
| 66 |
pub struct InnerWidthMapping { |
| 67 |
/// Index of the character in the source |
| 68 |
pub position: usize, |
| 69 |
/// The inner width in characters |
| 70 |
pub before: usize, |
| 71 |
/// The transformed width in characters |
| 72 |
pub after: usize, |
| 73 |
} |
| 74 |
|
| 75 |
impl InnerWidthMapping { |
| 76 |
pub fn new(position: usize, before: usize, after: usize) -> InnerWidthMapping { |
| 77 |
InnerWidthMapping { |
| 78 |
position, |
| 79 |
before, |
| 80 |
after, |
| 81 |
} |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
/// Whether the input string is a literal. If yes, it contains the inner width mappings. |
| 86 |
#[derive(Clone, PartialEq, Eq)] |
| 87 |
enum InputStringKind { |
| 88 |
NotALiteral, |
| 89 |
Literal { |
| 90 |
width_mappings: Vec<InnerWidthMapping>, |
| 91 |
}, |
| 92 |
} |
| 93 |
|
| 94 |
/// The type of format string that we are parsing. |
| 95 |
#[derive(Copy, Clone, Debug, Eq, PartialEq)] |
| 96 |
pub enum ParseMode { |
| 97 |
/// A normal format string as per `format_args!`. |
| 98 |
Format, |
| 99 |
/// An inline assembly template string for `asm!`. |
| 100 |
InlineAsm, |
| 101 |
} |
| 102 |
|
| 103 |
#[derive(Copy, Clone)] |
| 104 |
struct InnerOffset(usize); |
| 105 |
|
| 106 |
impl InnerOffset { |
| 107 |
fn to(self, end: InnerOffset) -> InnerSpan { |
| 108 |
InnerSpan::new(self.0, end.0) |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
/// A piece is a portion of the format string which represents the next part |
| 113 |
/// to emit. These are emitted as a stream by the `Parser` class. |
| 114 |
#[derive(Clone, Debug, PartialEq)] |
| 115 |
pub enum Piece<'a> { |
| 116 |
/// A literal string which should directly be emitted |
| 117 |
String(&'a str), |
| 118 |
/// This describes that formatting should process the next argument (as |
| 119 |
/// specified inside) for emission. |
| 120 |
NextArgument(Box<Argument<'a>>), |
| 121 |
} |
| 122 |
|
| 123 |
/// Representation of an argument specification. |
| 124 |
#[derive(Copy, Clone, Debug, PartialEq)] |
| 125 |
pub struct Argument<'a> { |
| 126 |
/// Where to find this argument |
| 127 |
pub position: Position<'a>, |
| 128 |
/// The span of the position indicator. Includes any whitespace in implicit |
| 129 |
/// positions (`{ }`). |
| 130 |
pub position_span: InnerSpan, |
| 131 |
/// How to format the argument |
| 132 |
pub format: FormatSpec<'a>, |
| 133 |
} |
| 134 |
|
| 135 |
/// Specification for the formatting of an argument in the format string. |
| 136 |
#[derive(Copy, Clone, Debug, PartialEq)] |
| 137 |
pub struct FormatSpec<'a> { |
| 138 |
/// Optionally specified character to fill alignment with. |
| 139 |
pub fill: Option<char>, |
| 140 |
/// Span of the optionally specified fill character. |
| 141 |
pub fill_span: Option<InnerSpan>, |
| 142 |
/// Optionally specified alignment. |
| 143 |
pub align: Alignment, |
| 144 |
/// The `+` or `-` flag. |
| 145 |
pub sign: Option<Sign>, |
| 146 |
/// The `#` flag. |
| 147 |
pub alternate: bool, |
| 148 |
/// The `0` flag. |
| 149 |
pub zero_pad: bool, |
| 150 |
/// The `x` or `X` flag. (Only for `Debug`.) |
| 151 |
pub debug_hex: Option<DebugHex>, |
| 152 |
/// The integer precision to use. |
| 153 |
pub precision: Count<'a>, |
| 154 |
/// The span of the precision formatting flag (for diagnostics). |
| 155 |
pub precision_span: Option<InnerSpan>, |
| 156 |
/// The string width requested for the resulting format. |
| 157 |
pub width: Count<'a>, |
| 158 |
/// The span of the width formatting flag (for diagnostics). |
| 159 |
pub width_span: Option<InnerSpan>, |
| 160 |
/// The descriptor string representing the name of the format desired for |
| 161 |
/// this argument, this can be empty or any number of characters, although |
| 162 |
/// it is required to be one word. |
| 163 |
pub ty: &'a str, |
| 164 |
/// The span of the descriptor string (for diagnostics). |
| 165 |
pub ty_span: Option<InnerSpan>, |
| 166 |
} |
| 167 |
|
| 168 |
/// Enum describing where an argument for a format can be located. |
| 169 |
#[derive(Copy, Clone, Debug, PartialEq)] |
| 170 |
pub enum Position<'a> { |
| 171 |
/// The argument is implied to be located at an index |
| 172 |
ArgumentImplicitlyIs(usize), |
| 173 |
/// The argument is located at a specific index given in the format, |
| 174 |
ArgumentIs(usize), |
| 175 |
/// The argument has a name. |
| 176 |
ArgumentNamed(&'a str), |
| 177 |
} |
| 178 |
|
| 179 |
impl Position<'_> { |
| 180 |
pub fn index(&self) -> Option<usize> { |
| 181 |
match self { |
| 182 |
ArgumentIs(i, ..) | ArgumentImplicitlyIs(i) => Some(*i), |
| 183 |
_ => None, |
| 184 |
} |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
/// Enum of alignments which are supported. |
| 189 |
#[derive(Copy, Clone, Debug, PartialEq)] |
| 190 |
pub enum Alignment { |
| 191 |
/// The value will be aligned to the left. |
| 192 |
AlignLeft, |
| 193 |
/// The value will be aligned to the right. |
| 194 |
AlignRight, |
| 195 |
/// The value will be aligned in the center. |
| 196 |
AlignCenter, |
| 197 |
/// The value will take on a default alignment. |
| 198 |
AlignUnknown, |
| 199 |
} |
| 200 |
|
| 201 |
/// Enum for the sign flags. |
| 202 |
#[derive(Copy, Clone, Debug, PartialEq)] |
| 203 |
pub enum Sign { |
| 204 |
/// The `+` flag. |
| 205 |
Plus, |
| 206 |
/// The `-` flag. |
| 207 |
Minus, |
| 208 |
} |
| 209 |
|
| 210 |
/// Enum for the debug hex flags. |
| 211 |
#[derive(Copy, Clone, Debug, PartialEq)] |
| 212 |
pub enum DebugHex { |
| 213 |
/// The `x` flag in `{:x?}`. |
| 214 |
Lower, |
| 215 |
/// The `X` flag in `{:X?}`. |
| 216 |
Upper, |
| 217 |
} |
| 218 |
|
| 219 |
/// A count is used for the precision and width parameters of an integer, and |
| 220 |
/// can reference either an argument or a literal integer. |
| 221 |
#[derive(Copy, Clone, Debug, PartialEq)] |
| 222 |
pub enum Count<'a> { |
| 223 |
/// The count is specified explicitly. |
| 224 |
CountIs(usize), |
| 225 |
/// The count is specified by the argument with the given name. |
| 226 |
CountIsName(&'a str, InnerSpan), |
| 227 |
/// The count is specified by the argument at the given index. |
| 228 |
CountIsParam(usize), |
| 229 |
/// The count is specified by a star (like in `{:.*}`) that refers to the argument at the given index. |
| 230 |
CountIsStar(usize), |
| 231 |
/// The count is implied and cannot be explicitly specified. |
| 232 |
CountImplied, |
| 233 |
} |
| 234 |
|
| 235 |
pub struct ParseError { |
| 236 |
pub description: string::String, |
| 237 |
pub note: Option<string::String>, |
| 238 |
pub label: string::String, |
| 239 |
pub span: InnerSpan, |
| 240 |
pub secondary_label: Option<(string::String, InnerSpan)>, |
| 241 |
pub suggestion: Suggestion, |
| 242 |
} |
| 243 |
|
| 244 |
pub enum Suggestion { |
| 245 |
None, |
| 246 |
/// Replace inline argument with positional argument: |
| 247 |
/// `format!("{foo.bar}")` -> `format!("{}", foo.bar)` |
| 248 |
UsePositional, |
| 249 |
/// Remove `r#` from identifier: |
| 250 |
/// `format!("{r#foo}")` -> `format!("{foo}")` |
| 251 |
RemoveRawIdent(InnerSpan), |
| 252 |
} |
| 253 |
|
| 254 |
/// The parser structure for interpreting the input format string. This is |
| 255 |
/// modeled as an iterator over `Piece` structures to form a stream of tokens |
| 256 |
/// being output. |
| 257 |
/// |
| 258 |
/// This is a recursive-descent parser for the sake of simplicity, and if |
| 259 |
/// necessary there's probably lots of room for improvement performance-wise. |
| 260 |
pub struct Parser<'a> { |
| 261 |
mode: ParseMode, |
| 262 |
input: &'a str, |
| 263 |
cur: iter::Peekable<str::CharIndices<'a>>, |
| 264 |
/// Error messages accumulated during parsing |
| 265 |
pub errors: Vec<ParseError>, |
| 266 |
/// Current position of implicit positional argument pointer |
| 267 |
pub curarg: usize, |
| 268 |
/// `Some(raw count)` when the string is "raw", used to position spans correctly |
| 269 |
style: Option<usize>, |
| 270 |
/// Start and end byte offset of every successfully parsed argument |
| 271 |
pub arg_places: Vec<InnerSpan>, |
| 272 |
/// Characters whose length has been changed from their in-code representation |
| 273 |
width_map: Vec<InnerWidthMapping>, |
| 274 |
/// Span of the last opening brace seen, used for error reporting |
| 275 |
last_opening_brace: Option<InnerSpan>, |
| 276 |
/// Whether the source string is comes from `println!` as opposed to `format!` or `print!` |
| 277 |
append_newline: bool, |
| 278 |
/// Whether this formatting string was written directly in the source. This controls whether we |
| 279 |
/// can use spans to refer into it and give better error messages. |
| 280 |
/// N.B: This does _not_ control whether implicit argument captures can be used. |
| 281 |
pub is_source_literal: bool, |
| 282 |
/// Start position of the current line. |
| 283 |
cur_line_start: usize, |
| 284 |
/// Start and end byte offset of every line of the format string. Excludes |
| 285 |
/// newline characters and leading whitespace. |
| 286 |
pub line_spans: Vec<InnerSpan>, |
| 287 |
} |
| 288 |
|
| 289 |
impl<'a> Iterator for Parser<'a> { |
| 290 |
type Item = Piece<'a>; |
| 291 |
|
| 292 |
fn next(&mut self) -> Option<Piece<'a>> { |
| 293 |
if let Some(&(pos, c)) = self.cur.peek() { |
| 294 |
match c { |
| 295 |
'{' => { |
| 296 |
let curr_last_brace = self.last_opening_brace; |
| 297 |
let byte_pos = self.to_span_index(pos); |
| 298 |
let lbrace_end = InnerOffset(byte_pos.0 + self.to_span_width(pos)); |
| 299 |
self.last_opening_brace = Some(byte_pos.to(lbrace_end)); |
| 300 |
self.cur.next(); |
| 301 |
if self.consume('{') { |
| 302 |
self.last_opening_brace = curr_last_brace; |
| 303 |
|
| 304 |
Some(String(self.string(pos + 1))) |
| 305 |
} else { |
| 306 |
let arg = self.argument(lbrace_end); |
| 307 |
if let Some(rbrace_pos) = self.consume_closing_brace(&arg) { |
| 308 |
if self.is_source_literal { |
| 309 |
let lbrace_byte_pos = self.to_span_index(pos); |
| 310 |
let rbrace_byte_pos = self.to_span_index(rbrace_pos); |
| 311 |
|
| 312 |
let width = self.to_span_width(rbrace_pos); |
| 313 |
|
| 314 |
self.arg_places.push( |
| 315 |
lbrace_byte_pos.to(InnerOffset(rbrace_byte_pos.0 + width)), |
| 316 |
); |
| 317 |
} |
| 318 |
} else { |
| 319 |
if let Some(&(_, maybe)) = self.cur.peek() { |
| 320 |
if maybe == '?' { |
| 321 |
self.suggest_format(); |
| 322 |
} else { |
| 323 |
self.suggest_positional_arg_instead_of_captured_arg(arg); |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
Some(NextArgument(Box::new(arg))) |
| 328 |
} |
| 329 |
} |
| 330 |
'}' => { |
| 331 |
self.cur.next(); |
| 332 |
if self.consume('}') { |
| 333 |
Some(String(self.string(pos + 1))) |
| 334 |
} else { |
| 335 |
let err_pos = self.to_span_index(pos); |
| 336 |
self.err_with_note( |
| 337 |
"unmatched `}` found", |
| 338 |
"unmatched `}`", |
| 339 |
"if you intended to print `}`, you can escape it using `}}`", |
| 340 |
err_pos.to(err_pos), |
| 341 |
); |
| 342 |
None |
| 343 |
} |
| 344 |
} |
| 345 |
_ => Some(String(self.string(pos))), |
| 346 |
} |
| 347 |
} else { |
| 348 |
if self.is_source_literal { |
| 349 |
let span = self.span(self.cur_line_start, self.input.len()); |
| 350 |
if self.line_spans.last() != Some(&span) { |
| 351 |
self.line_spans.push(span); |
| 352 |
} |
| 353 |
} |
| 354 |
None |
| 355 |
} |
| 356 |
} |
| 357 |
} |
| 358 |
|
| 359 |
impl<'a> Parser<'a> { |
| 360 |
/// Creates a new parser for the given format string |
| 361 |
pub fn new( |
| 362 |
s: &'a str, |
| 363 |
style: Option<usize>, |
| 364 |
snippet: Option<string::String>, |
| 365 |
append_newline: bool, |
| 366 |
mode: ParseMode, |
| 367 |
) -> Parser<'a> { |
| 368 |
let input_string_kind = find_width_map_from_snippet(s, snippet, style); |
| 369 |
let (width_map, is_source_literal) = match input_string_kind { |
| 370 |
InputStringKind::Literal { width_mappings } => (width_mappings, true), |
| 371 |
InputStringKind::NotALiteral => (Vec::new(), false), |
| 372 |
}; |
| 373 |
|
| 374 |
Parser { |
| 375 |
mode, |
| 376 |
input: s, |
| 377 |
cur: s.char_indices().peekable(), |
| 378 |
errors: vec![], |
| 379 |
curarg: 0, |
| 380 |
style, |
| 381 |
arg_places: vec![], |
| 382 |
width_map, |
| 383 |
last_opening_brace: None, |
| 384 |
append_newline, |
| 385 |
is_source_literal, |
| 386 |
cur_line_start: 0, |
| 387 |
line_spans: vec![], |
| 388 |
} |
| 389 |
} |
| 390 |
|
| 391 |
/// Notifies of an error. The message doesn't actually need to be of type |
| 392 |
/// String, but I think it does when this eventually uses conditions so it |
| 393 |
/// might as well start using it now. |
| 394 |
fn err<S1: Into<string::String>, S2: Into<string::String>>( |
| 395 |
&mut self, |
| 396 |
description: S1, |
| 397 |
label: S2, |
| 398 |
span: InnerSpan, |
| 399 |
) { |
| 400 |
self.errors.push(ParseError { |
| 401 |
description: description.into(), |
| 402 |
note: None, |
| 403 |
label: label.into(), |
| 404 |
span, |
| 405 |
secondary_label: None, |
| 406 |
suggestion: Suggestion::None, |
| 407 |
}); |
| 408 |
} |
| 409 |
|
| 410 |
/// Notifies of an error. The message doesn't actually need to be of type |
| 411 |
/// String, but I think it does when this eventually uses conditions so it |
| 412 |
/// might as well start using it now. |
| 413 |
fn err_with_note< |
| 414 |
S1: Into<string::String>, |
| 415 |
S2: Into<string::String>, |
| 416 |
S3: Into<string::String>, |
| 417 |
>( |
| 418 |
&mut self, |
| 419 |
description: S1, |
| 420 |
label: S2, |
| 421 |
note: S3, |
| 422 |
span: InnerSpan, |
| 423 |
) { |
| 424 |
self.errors.push(ParseError { |
| 425 |
description: description.into(), |
| 426 |
note: Some(note.into()), |
| 427 |
label: label.into(), |
| 428 |
span, |
| 429 |
secondary_label: None, |
| 430 |
suggestion: Suggestion::None, |
| 431 |
}); |
| 432 |
} |
| 433 |
|
| 434 |
/// Optionally consumes the specified character. If the character is not at |
| 435 |
/// the current position, then the current iterator isn't moved and `false` is |
| 436 |
/// returned, otherwise the character is consumed and `true` is returned. |
| 437 |
fn consume(&mut self, c: char) -> bool { |
| 438 |
self.consume_pos(c).is_some() |
| 439 |
} |
| 440 |
|
| 441 |
/// Optionally consumes the specified character. If the character is not at |
| 442 |
/// the current position, then the current iterator isn't moved and `None` is |
| 443 |
/// returned, otherwise the character is consumed and the current position is |
| 444 |
/// returned. |
| 445 |
fn consume_pos(&mut self, c: char) -> Option<usize> { |
| 446 |
if let Some(&(pos, maybe)) = self.cur.peek() { |
| 447 |
if c == maybe { |
| 448 |
self.cur.next(); |
| 449 |
return Some(pos); |
| 450 |
} |
| 451 |
} |
| 452 |
None |
| 453 |
} |
| 454 |
|
| 455 |
fn remap_pos(&self, mut pos: usize) -> InnerOffset { |
| 456 |
for width in &self.width_map { |
| 457 |
if pos > width.position { |
| 458 |
pos += width.before - width.after; |
| 459 |
} else if pos == width.position && width.after == 0 { |
| 460 |
pos += width.before; |
| 461 |
} else { |
| 462 |
break; |
| 463 |
} |
| 464 |
} |
| 465 |
|
| 466 |
InnerOffset(pos) |
| 467 |
} |
| 468 |
|
| 469 |
fn to_span_index(&self, pos: usize) -> InnerOffset { |
| 470 |
// This handles the raw string case, the raw argument is the number of # |
| 471 |
// in r###"..."### (we need to add one because of the `r`). |
| 472 |
let raw = self.style.map_or(0, |raw| raw + 1); |
| 473 |
let pos = self.remap_pos(pos); |
| 474 |
InnerOffset(raw + pos.0 + 1) |
| 475 |
} |
| 476 |
|
| 477 |
fn to_span_width(&self, pos: usize) -> usize { |
| 478 |
let pos = self.remap_pos(pos); |
| 479 |
match self.width_map.iter().find(|w| w.position == pos.0) { |
| 480 |
Some(w) => w.before, |
| 481 |
None => 1, |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
fn span(&self, start_pos: usize, end_pos: usize) -> InnerSpan { |
| 486 |
let start = self.to_span_index(start_pos); |
| 487 |
let end = self.to_span_index(end_pos); |
| 488 |
start.to(end) |
| 489 |
} |
| 490 |
|
| 491 |
/// Forces consumption of the specified character. If the character is not |
| 492 |
/// found, an error is emitted. |
| 493 |
fn consume_closing_brace(&mut self, arg: &Argument<'_>) -> Option<usize> { |
| 494 |
self.ws(); |
| 495 |
|
| 496 |
let pos; |
| 497 |
let description; |
| 498 |
|
| 499 |
if let Some(&(peek_pos, maybe)) = self.cur.peek() { |
| 500 |
if maybe == '}' { |
| 501 |
self.cur.next(); |
| 502 |
return Some(peek_pos); |
| 503 |
} |
| 504 |
|
| 505 |
pos = peek_pos; |
| 506 |
description = format!("expected `'}}'`, found `{:?}`", maybe); |
| 507 |
} else { |
| 508 |
description = "expected `'}'` but string was terminated".to_owned(); |
| 509 |
// point at closing `"` |
| 510 |
pos = self.input.len() - if self.append_newline { 1 } else { 0 }; |
| 511 |
} |
| 512 |
|
| 513 |
let pos = self.to_span_index(pos); |
| 514 |
|
| 515 |
let label = "expected `'}'`".to_owned(); |
| 516 |
let (note, secondary_label) = if arg.format.fill == Some('}') { |
| 517 |
( |
| 518 |
Some("the character `'}'` is interpreted as a fill character because of the `:` that precedes it".to_owned()), |
| 519 |
arg.format.fill_span.map(|sp| ("this is not interpreted as a formatting closing brace".to_owned(), sp)), |
| 520 |
) |
| 521 |
} else { |
| 522 |
( |
| 523 |
Some("if you intended to print `{`, you can escape it using `{{`".to_owned()), |
| 524 |
self.last_opening_brace |
| 525 |
.map(|sp| ("because of this opening brace".to_owned(), sp)), |
| 526 |
) |
| 527 |
}; |
| 528 |
|
| 529 |
self.errors.push(ParseError { |
| 530 |
description, |
| 531 |
note, |
| 532 |
label, |
| 533 |
span: pos.to(pos), |
| 534 |
secondary_label, |
| 535 |
suggestion: Suggestion::None, |
| 536 |
}); |
| 537 |
|
| 538 |
None |
| 539 |
} |
| 540 |
|
| 541 |
/// Consumes all whitespace characters until the first non-whitespace character |
| 542 |
fn ws(&mut self) { |
| 543 |
while let Some(&(_, c)) = self.cur.peek() { |
| 544 |
if c.is_whitespace() { |
| 545 |
self.cur.next(); |
| 546 |
} else { |
| 547 |
break; |
| 548 |
} |
| 549 |
} |
| 550 |
} |
| 551 |
|
| 552 |
/// Parses all of a string which is to be considered a "raw literal" in a |
| 553 |
/// format string. This is everything outside of the braces. |
| 554 |
fn string(&mut self, start: usize) -> &'a str { |
| 555 |
// we may not consume the character, peek the iterator |
| 556 |
while let Some(&(pos, c)) = self.cur.peek() { |
| 557 |
match c { |
| 558 |
'{' | '}' => { |
| 559 |
return &self.input[start..pos]; |
| 560 |
} |
| 561 |
'\n' if self.is_source_literal => { |
| 562 |
self.line_spans.push(self.span(self.cur_line_start, pos)); |
| 563 |
self.cur_line_start = pos + 1; |
| 564 |
self.cur.next(); |
| 565 |
} |
| 566 |
_ => { |
| 567 |
if self.is_source_literal && pos == self.cur_line_start && c.is_whitespace() { |
| 568 |
self.cur_line_start = pos + c.len_utf8(); |
| 569 |
} |
| 570 |
self.cur.next(); |
| 571 |
} |
| 572 |
} |
| 573 |
} |
| 574 |
&self.input[start..self.input.len()] |
| 575 |
} |
| 576 |
|
| 577 |
/// Parses an `Argument` structure, or what's contained within braces inside the format string. |
| 578 |
fn argument(&mut self, start: InnerOffset) -> Argument<'a> { |
| 579 |
let pos = self.position(); |
| 580 |
|
| 581 |
let end = self |
| 582 |
.cur |
| 583 |
.clone() |
| 584 |
.find(|(_, ch)| !ch.is_whitespace()) |
| 585 |
.map_or(start, |(end, _)| self.to_span_index(end)); |
| 586 |
let position_span = start.to(end); |
| 587 |
|
| 588 |
let format = match self.mode { |
| 589 |
ParseMode::Format => self.format(), |
| 590 |
ParseMode::InlineAsm => self.inline_asm(), |
| 591 |
}; |
| 592 |
|
| 593 |
// Resolve position after parsing format spec. |
| 594 |
let pos = match pos { |
| 595 |
Some(position) => position, |
| 596 |
None => { |
| 597 |
let i = self.curarg; |
| 598 |
self.curarg += 1; |
| 599 |
ArgumentImplicitlyIs(i) |
| 600 |
} |
| 601 |
}; |
| 602 |
|
| 603 |
Argument { |
| 604 |
position: pos, |
| 605 |
position_span, |
| 606 |
format, |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
/// Parses a positional argument for a format. This could either be an |
| 611 |
/// integer index of an argument, a named argument, or a blank string. |
| 612 |
/// Returns `Some(parsed_position)` if the position is not implicitly |
| 613 |
/// consuming a macro argument, `None` if it's the case. |
| 614 |
fn position(&mut self) -> Option<Position<'a>> { |
| 615 |
if let Some(i) = self.integer() { |
| 616 |
Some(ArgumentIs(i)) |
| 617 |
} else { |
| 618 |
match self.cur.peek() { |
| 619 |
Some(&(lo, c)) if is_id_start(c) => { |
| 620 |
let word = self.word(); |
| 621 |
|
| 622 |
// Recover from `r#ident` in format strings. |
| 623 |
// FIXME: use a let chain |
| 624 |
if word == "r" { |
| 625 |
if let Some((pos, '#')) = self.cur.peek() { |
| 626 |
if self.input[pos + 1..] |
| 627 |
.chars() |
| 628 |
.next() |
| 629 |
.is_some_and(is_id_start) |
| 630 |
{ |
| 631 |
self.cur.next(); |
| 632 |
let word = self.word(); |
| 633 |
let prefix_span = self.span(lo, lo + 2); |
| 634 |
let full_span = self.span(lo, lo + 2 + word.len()); |
| 635 |
self.errors.insert(0, ParseError { |
| 636 |
description: "raw identifiers are not supported".to_owned(), |
| 637 |
note: Some("identifiers in format strings can be keywords and don't need to be prefixed with `r#`".to_string()), |
| 638 |
label: "raw identifier used here".to_owned(), |
| 639 |
span: full_span, |
| 640 |
secondary_label: None, |
| 641 |
suggestion: Suggestion::RemoveRawIdent(prefix_span), |
| 642 |
}); |
| 643 |
return Some(ArgumentNamed(word)); |
| 644 |
} |
| 645 |
} |
| 646 |
} |
| 647 |
|
| 648 |
Some(ArgumentNamed(word)) |
| 649 |
} |
| 650 |
|
| 651 |
// This is an `ArgumentNext`. |
| 652 |
// Record the fact and do the resolution after parsing the |
| 653 |
// format spec, to make things like `{:.*}` work. |
| 654 |
_ => None, |
| 655 |
} |
| 656 |
} |
| 657 |
} |
| 658 |
|
| 659 |
fn current_pos(&mut self) -> usize { |
| 660 |
if let Some(&(pos, _)) = self.cur.peek() { |
| 661 |
pos |
| 662 |
} else { |
| 663 |
self.input.len() |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
/// Parses a format specifier at the current position, returning all of the |
| 668 |
/// relevant information in the `FormatSpec` struct. |
| 669 |
fn format(&mut self) -> FormatSpec<'a> { |
| 670 |
let mut spec = FormatSpec { |
| 671 |
fill: None, |
| 672 |
fill_span: None, |
| 673 |
align: AlignUnknown, |
| 674 |
sign: None, |
| 675 |
alternate: false, |
| 676 |
zero_pad: false, |
| 677 |
debug_hex: None, |
| 678 |
precision: CountImplied, |
| 679 |
precision_span: None, |
| 680 |
width: CountImplied, |
| 681 |
width_span: None, |
| 682 |
ty: &self.input[..0], |
| 683 |
ty_span: None, |
| 684 |
}; |
| 685 |
if !self.consume(':') { |
| 686 |
return spec; |
| 687 |
} |
| 688 |
|
| 689 |
// fill character |
| 690 |
if let Some(&(idx, c)) = self.cur.peek() { |
| 691 |
match self.cur.clone().nth(1) { |
| 692 |
Some((_, '>')) | Some((_, '<')) | Some((_, '^')) => { |
| 693 |
spec.fill = Some(c); |
| 694 |
spec.fill_span = Some(self.span(idx, idx + 1)); |
| 695 |
self.cur.next(); |
| 696 |
} |
| 697 |
_ => {} |
| 698 |
} |
| 699 |
} |
| 700 |
|
| 701 |
// Alignment |
| 702 |
if self.consume('<') { |
| 703 |
spec.align = AlignLeft; |
| 704 |
} else if self.consume('>') { |
| 705 |
spec.align = AlignRight; |
| 706 |
} else if self.consume('^') { |
| 707 |
spec.align = AlignCenter; |
| 708 |
} |
| 709 |
// Sign flags |
| 710 |
if self.consume('+') { |
| 711 |
spec.sign = Some(Sign::Plus); |
| 712 |
} else if self.consume('-') { |
| 713 |
spec.sign = Some(Sign::Minus); |
| 714 |
} |
| 715 |
// Alternate marker |
| 716 |
if self.consume('#') { |
| 717 |
spec.alternate = true; |
| 718 |
} |
| 719 |
// Width and precision |
| 720 |
let mut havewidth = false; |
| 721 |
|
| 722 |
if self.consume('0') { |
| 723 |
// small ambiguity with '0$' as a format string. In theory this is a |
| 724 |
// '0' flag and then an ill-formatted format string with just a '$' |
| 725 |
// and no count, but this is better if we instead interpret this as |
| 726 |
// no '0' flag and '0$' as the width instead. |
| 727 |
if let Some(end) = self.consume_pos('$') { |
| 728 |
spec.width = CountIsParam(0); |
| 729 |
spec.width_span = Some(self.span(end - 1, end + 1)); |
| 730 |
havewidth = true; |
| 731 |
} else { |
| 732 |
spec.zero_pad = true; |
| 733 |
} |
| 734 |
} |
| 735 |
|
| 736 |
if !havewidth { |
| 737 |
let start = self.current_pos(); |
| 738 |
spec.width = self.count(start); |
| 739 |
if spec.width != CountImplied { |
| 740 |
let end = self.current_pos(); |
| 741 |
spec.width_span = Some(self.span(start, end)); |
| 742 |
} |
| 743 |
} |
| 744 |
|
| 745 |
if let Some(start) = self.consume_pos('.') { |
| 746 |
if self.consume('*') { |
| 747 |
// Resolve `CountIsNextParam`. |
| 748 |
// We can do this immediately as `position` is resolved later. |
| 749 |
let i = self.curarg; |
| 750 |
self.curarg += 1; |
| 751 |
spec.precision = CountIsStar(i); |
| 752 |
} else { |
| 753 |
spec.precision = self.count(start + 1); |
| 754 |
} |
| 755 |
let end = self.current_pos(); |
| 756 |
spec.precision_span = Some(self.span(start, end)); |
| 757 |
} |
| 758 |
|
| 759 |
let ty_span_start = self.current_pos(); |
| 760 |
// Optional radix followed by the actual format specifier |
| 761 |
if self.consume('x') { |
| 762 |
if self.consume('?') { |
| 763 |
spec.debug_hex = Some(DebugHex::Lower); |
| 764 |
spec.ty = "?"; |
| 765 |
} else { |
| 766 |
spec.ty = "x"; |
| 767 |
} |
| 768 |
} else if self.consume('X') { |
| 769 |
if self.consume('?') { |
| 770 |
spec.debug_hex = Some(DebugHex::Upper); |
| 771 |
spec.ty = "?"; |
| 772 |
} else { |
| 773 |
spec.ty = "X"; |
| 774 |
} |
| 775 |
} else if self.consume('?') { |
| 776 |
spec.ty = "?"; |
| 777 |
} else { |
| 778 |
spec.ty = self.word(); |
| 779 |
if !spec.ty.is_empty() { |
| 780 |
let ty_span_end = self.current_pos(); |
| 781 |
spec.ty_span = Some(self.span(ty_span_start, ty_span_end)); |
| 782 |
} |
| 783 |
} |
| 784 |
spec |
| 785 |
} |
| 786 |
|
| 787 |
/// Parses an inline assembly template modifier at the current position, returning the modifier |
| 788 |
/// in the `ty` field of the `FormatSpec` struct. |
| 789 |
fn inline_asm(&mut self) -> FormatSpec<'a> { |
| 790 |
let mut spec = FormatSpec { |
| 791 |
fill: None, |
| 792 |
fill_span: None, |
| 793 |
align: AlignUnknown, |
| 794 |
sign: None, |
| 795 |
alternate: false, |
| 796 |
zero_pad: false, |
| 797 |
debug_hex: None, |
| 798 |
precision: CountImplied, |
| 799 |
precision_span: None, |
| 800 |
width: CountImplied, |
| 801 |
width_span: None, |
| 802 |
ty: &self.input[..0], |
| 803 |
ty_span: None, |
| 804 |
}; |
| 805 |
if !self.consume(':') { |
| 806 |
return spec; |
| 807 |
} |
| 808 |
|
| 809 |
let ty_span_start = self.current_pos(); |
| 810 |
spec.ty = self.word(); |
| 811 |
if !spec.ty.is_empty() { |
| 812 |
let ty_span_end = self.current_pos(); |
| 813 |
spec.ty_span = Some(self.span(ty_span_start, ty_span_end)); |
| 814 |
} |
| 815 |
|
| 816 |
spec |
| 817 |
} |
| 818 |
|
| 819 |
/// Parses a `Count` parameter at the current position. This does not check |
| 820 |
/// for 'CountIsNextParam' because that is only used in precision, not |
| 821 |
/// width. |
| 822 |
fn count(&mut self, start: usize) -> Count<'a> { |
| 823 |
if let Some(i) = self.integer() { |
| 824 |
if self.consume('$') { |
| 825 |
CountIsParam(i) |
| 826 |
} else { |
| 827 |
CountIs(i) |
| 828 |
} |
| 829 |
} else { |
| 830 |
let tmp = self.cur.clone(); |
| 831 |
let word = self.word(); |
| 832 |
if word.is_empty() { |
| 833 |
self.cur = tmp; |
| 834 |
CountImplied |
| 835 |
} else if let Some(end) = self.consume_pos('$') { |
| 836 |
let name_span = self.span(start, end); |
| 837 |
CountIsName(word, name_span) |
| 838 |
} else { |
| 839 |
self.cur = tmp; |
| 840 |
CountImplied |
| 841 |
} |
| 842 |
} |
| 843 |
} |
| 844 |
|
| 845 |
/// Parses a word starting at the current position. A word is the same as |
| 846 |
/// Rust identifier, except that it can't start with `_` character. |
| 847 |
fn word(&mut self) -> &'a str { |
| 848 |
let start = match self.cur.peek() { |
| 849 |
Some(&(pos, c)) if is_id_start(c) => { |
| 850 |
self.cur.next(); |
| 851 |
pos |
| 852 |
} |
| 853 |
_ => { |
| 854 |
return ""; |
| 855 |
} |
| 856 |
}; |
| 857 |
let mut end = None; |
| 858 |
while let Some(&(pos, c)) = self.cur.peek() { |
| 859 |
if is_id_continue(c) { |
| 860 |
self.cur.next(); |
| 861 |
} else { |
| 862 |
end = Some(pos); |
| 863 |
break; |
| 864 |
} |
| 865 |
} |
| 866 |
let end = end.unwrap_or(self.input.len()); |
| 867 |
let word = &self.input[start..end]; |
| 868 |
if word == "_" { |
| 869 |
self.err_with_note( |
| 870 |
"invalid argument name `_`", |
| 871 |
"invalid argument name", |
| 872 |
"argument name cannot be a single underscore", |
| 873 |
self.span(start, end), |
| 874 |
); |
| 875 |
} |
| 876 |
word |
| 877 |
} |
| 878 |
|
| 879 |
fn integer(&mut self) -> Option<usize> { |
| 880 |
let mut cur: usize = 0; |
| 881 |
let mut found = false; |
| 882 |
let mut overflow = false; |
| 883 |
let start = self.current_pos(); |
| 884 |
while let Some(&(_, c)) = self.cur.peek() { |
| 885 |
if let Some(i) = c.to_digit(10) { |
| 886 |
let (tmp, mul_overflow) = cur.overflowing_mul(10); |
| 887 |
let (tmp, add_overflow) = tmp.overflowing_add(i as usize); |
| 888 |
if mul_overflow || add_overflow { |
| 889 |
overflow = true; |
| 890 |
} |
| 891 |
cur = tmp; |
| 892 |
found = true; |
| 893 |
self.cur.next(); |
| 894 |
} else { |
| 895 |
break; |
| 896 |
} |
| 897 |
} |
| 898 |
|
| 899 |
if overflow { |
| 900 |
let end = self.current_pos(); |
| 901 |
let overflowed_int = &self.input[start..end]; |
| 902 |
self.err( |
| 903 |
format!( |
| 904 |
"integer `{}` does not fit into the type `usize` whose range is `0..={}`", |
| 905 |
overflowed_int, |
| 906 |
usize::MAX |
| 907 |
), |
| 908 |
"integer out of range for `usize`", |
| 909 |
self.span(start, end), |
| 910 |
); |
| 911 |
} |
| 912 |
|
| 913 |
if found { |
| 914 |
Some(cur) |
| 915 |
} else { |
| 916 |
None |
| 917 |
} |
| 918 |
} |
| 919 |
|
| 920 |
fn suggest_format(&mut self) { |
| 921 |
if let (Some(pos), Some(_)) = (self.consume_pos('?'), self.consume_pos(':')) { |
| 922 |
let word = self.word(); |
| 923 |
let _end = self.current_pos(); |
| 924 |
let pos = self.to_span_index(pos); |
| 925 |
self.errors.insert( |
| 926 |
0, |
| 927 |
ParseError { |
| 928 |
description: "expected format parameter to occur after `:`".to_owned(), |
| 929 |
note: Some(format!( |
| 930 |
"`?` comes after `:`, try `{}:{}` instead", |
| 931 |
word, "?" |
| 932 |
)), |
| 933 |
label: "expected `?` to occur after `:`".to_owned(), |
| 934 |
span: pos.to(pos), |
| 935 |
secondary_label: None, |
| 936 |
suggestion: Suggestion::None, |
| 937 |
}, |
| 938 |
); |
| 939 |
} |
| 940 |
} |
| 941 |
|
| 942 |
fn suggest_positional_arg_instead_of_captured_arg(&mut self, arg: Argument<'a>) { |
| 943 |
if let Some(end) = self.consume_pos('.') { |
| 944 |
let byte_pos = self.to_span_index(end); |
| 945 |
let start = InnerOffset(byte_pos.0 + 1); |
| 946 |
let field = self.argument(start); |
| 947 |
// We can only parse `foo.bar` field access, any deeper nesting, |
| 948 |
// or another type of expression, like method calls, are not supported |
| 949 |
if !self.consume('}') { |
| 950 |
return; |
| 951 |
} |
| 952 |
if let ArgumentNamed(_) = arg.position { |
| 953 |
if let ArgumentNamed(_) = field.position { |
| 954 |
self.errors.insert( |
| 955 |
0, |
| 956 |
ParseError { |
| 957 |
description: "field access isn't supported".to_string(), |
| 958 |
note: None, |
| 959 |
label: "not supported".to_string(), |
| 960 |
span: InnerSpan::new(arg.position_span.start, field.position_span.end), |
| 961 |
secondary_label: None, |
| 962 |
suggestion: Suggestion::UsePositional, |
| 963 |
}, |
| 964 |
); |
| 965 |
} |
| 966 |
} |
| 967 |
} |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
/// Finds the indices of all characters that have been processed and differ between the actual |
| 972 |
/// written code (code snippet) and the `InternedString` that gets processed in the `Parser` |
| 973 |
/// in order to properly synthesise the intra-string `Span`s for error diagnostics. |
| 974 |
// TODO: Can we give an escaped string here? probably yes - and a valid one too |
| 975 |
fn find_width_map_from_snippet( |
| 976 |
input: &str, |
| 977 |
snippet: Option<string::String>, |
| 978 |
str_style: Option<usize>, |
| 979 |
) -> InputStringKind { |
| 980 |
let snippet = match snippet { |
| 981 |
Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s, |
| 982 |
_ => return InputStringKind::NotALiteral, |
| 983 |
}; |
| 984 |
|
| 985 |
if str_style.is_some() { |
| 986 |
return InputStringKind::Literal { |
| 987 |
width_mappings: Vec::new(), |
| 988 |
}; |
| 989 |
} |
| 990 |
|
| 991 |
// Strip quotes. |
| 992 |
let snippet = &snippet[1..snippet.len() - 1]; |
| 993 |
|
| 994 |
// Macros like `println` add a newline at the end. That technically doesn't make them "literals" anymore, but it's fine |
| 995 |
// since we will never need to point our spans there, so we lie about it here by ignoring it. |
| 996 |
// Since there might actually be newlines in the source code, we need to normalize away all trailing newlines. |
| 997 |
// If we only trimmed it off the input, `format!("\n")` would cause a mismatch as here we they actually match up. |
| 998 |
// Alternatively, we could just count the trailing newlines and only trim one from the input if they don't match up. |
| 999 |
let input_no_nl = input.trim_end_matches('\n'); |
| 1000 |
let unescaped = match unescape_string(snippet) { |
| 1001 |
Some(u) => u, |
| 1002 |
None => return InputStringKind::NotALiteral, |
| 1003 |
}; |
| 1004 |
|
| 1005 |
let unescaped_no_nl = unescaped.trim_end_matches('\n'); |
| 1006 |
|
| 1007 |
if unescaped_no_nl != input_no_nl { |
| 1008 |
// The source string that we're pointing at isn't our input, so spans pointing at it will be incorrect. |
| 1009 |
// This can for example happen with proc macros that respan generated literals. |
| 1010 |
return InputStringKind::NotALiteral; |
| 1011 |
} |
| 1012 |
|
| 1013 |
let mut s = snippet.char_indices(); |
| 1014 |
let mut width_mappings = vec![]; |
| 1015 |
while let Some((pos, c)) = s.next() { |
| 1016 |
match (c, s.clone().next()) { |
| 1017 |
// skip whitespace and empty lines ending in '\\' |
| 1018 |
('\\', Some((_, '\n'))) => { |
| 1019 |
let _ = s.next(); |
| 1020 |
let mut width = 2; |
| 1021 |
|
| 1022 |
while let Some((_, c)) = s.clone().next() { |
| 1023 |
if matches!(c, ' ' | '\n' | '\t') { |
| 1024 |
width += 1; |
| 1025 |
let _ = s.next(); |
| 1026 |
} else { |
| 1027 |
break; |
| 1028 |
} |
| 1029 |
} |
| 1030 |
|
| 1031 |
width_mappings.push(InnerWidthMapping::new(pos, width, 0)); |
| 1032 |
} |
| 1033 |
('\\', Some((_, 'n'))) |
| 1034 |
| ('\\', Some((_, 't'))) |
| 1035 |
| ('\\', Some((_, 'r'))) |
| 1036 |
| ('\\', Some((_, '0'))) |
| 1037 |
| ('\\', Some((_, '\\'))) |
| 1038 |
| ('\\', Some((_, '\''))) |
| 1039 |
| ('\\', Some((_, '\"'))) => { |
| 1040 |
width_mappings.push(InnerWidthMapping::new(pos, 2, 1)); |
| 1041 |
let _ = s.next(); |
| 1042 |
} |
| 1043 |
('\\', Some((_, 'x'))) => { |
| 1044 |
// consume `\xAB` literal |
| 1045 |
s.nth(2); |
| 1046 |
width_mappings.push(InnerWidthMapping::new(pos, 4, 1)); |
| 1047 |
} |
| 1048 |
('\\', Some((_, 'u'))) => { |
| 1049 |
let mut width = 2; |
| 1050 |
let _ = s.next(); |
| 1051 |
|
| 1052 |
if let Some((_, next_c)) = s.next() { |
| 1053 |
if next_c == '{' { |
| 1054 |
// consume up to 6 hexanumeric chars |
| 1055 |
let digits_len = s |
| 1056 |
.clone() |
| 1057 |
.take(6) |
| 1058 |
.take_while(|(_, c)| c.is_digit(16)) |
| 1059 |
.count(); |
| 1060 |
|
| 1061 |
let len_utf8 = s |
| 1062 |
.as_str() |
| 1063 |
.get(..digits_len) |
| 1064 |
.and_then(|digits| u32::from_str_radix(digits, 16).ok()) |
| 1065 |
.and_then(std::char::from_u32) |
| 1066 |
.map_or(1, char::len_utf8); |
| 1067 |
|
| 1068 |
// Skip the digits, for chars that encode to more than 1 utf-8 byte |
| 1069 |
// exclude as many digits as it is greater than 1 byte |
| 1070 |
// |
| 1071 |
// So for a 3 byte character, exclude 2 digits |
| 1072 |
let required_skips = digits_len.saturating_sub(len_utf8.saturating_sub(1)); |
| 1073 |
|
| 1074 |
// skip '{' and '}' also |
| 1075 |
width += required_skips + 2; |
| 1076 |
|
| 1077 |
s.nth(digits_len); |
| 1078 |
} else if next_c.is_digit(16) { |
| 1079 |
width += 1; |
| 1080 |
|
| 1081 |
// We suggest adding `{` and `}` when appropriate, accept it here as if |
| 1082 |
// it were correct |
| 1083 |
let mut i = 0; // consume up to 6 hexanumeric chars |
| 1084 |
while let (Some((_, c)), _) = (s.next(), i < 6) { |
| 1085 |
if c.is_digit(16) { |
| 1086 |
width += 1; |
| 1087 |
} else { |
| 1088 |
break; |
| 1089 |
} |
| 1090 |
i += 1; |
| 1091 |
} |
| 1092 |
} |
| 1093 |
} |
| 1094 |
|
| 1095 |
width_mappings.push(InnerWidthMapping::new(pos, width, 1)); |
| 1096 |
} |
| 1097 |
_ => {} |
| 1098 |
} |
| 1099 |
} |
| 1100 |
|
| 1101 |
InputStringKind::Literal { width_mappings } |
| 1102 |
} |
| 1103 |
|
| 1104 |
// TODO: I guess we can provide an `unescape_string` function to the parser... but how do we do that |
| 1105 |
// Store it in the parser struct? we need to make it FFI-aware |
| 1106 |
// SO this is not possible because we need `unescape_string` *before* we have a parser |
| 1107 |
|
| 1108 |
fn unescape_string(string: &str) -> Option<string::String> { |
| 1109 |
// let mut buf = string::String::new(); |
| 1110 |
// let mut ok = true; |
| 1111 |
// unescape::unescape_literal(string, unescape::Mode::Str, &mut |_, unescaped_char| { |
| 1112 |
// match unescaped_char { |
| 1113 |
// Ok(c) => buf.push(c), |
| 1114 |
// Err(_) => ok = false, |
| 1115 |
// } |
| 1116 |
// }); |
| 1117 |
|
| 1118 |
let buf = string::String::from(string); |
| 1119 |
let ok = true; |
| 1120 |
|
| 1121 |
if ok { |
| 1122 |
Some(buf) |
| 1123 |
} else { |
| 1124 |
None |
| 1125 |
} |
| 1126 |
} |
| 1127 |
|
| 1128 |
// Assert a reasonable size for `Piece` |
| 1129 |
// #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] |
| 1130 |
// rustc_index::static_assert_size!(Piece<'_>, 16); |
| 1131 |
|
| 1132 |
// #[cfg(test)] |
| 1133 |
// mod tests; |