Skip to content

Commit

Permalink
Add enum for find_width_map_from_snippet
Browse files Browse the repository at this point in the history
This makes the relationship between the vec and the boolean clearer.
  • Loading branch information
Noratrieb committed Dec 28, 2022
1 parent e6c02aa commit 31b490d
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions compiler/rustc_parse_format/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,13 @@ impl InnerWidthMapping {
}
}

/// Whether the input string is a literal. If yes, it contains the inner width mappings.
#[derive(Clone, PartialEq, Eq)]
enum InputStringKind {
NotALiteral,
Literal { width_mappings: Vec<InnerWidthMapping> },
}

/// The type of format string that we are parsing.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ParseMode {
Expand Down Expand Up @@ -307,7 +314,11 @@ impl<'a> Parser<'a> {
append_newline: bool,
mode: ParseMode,
) -> Parser<'a> {
let (width_map, is_literal) = find_width_map_from_snippet(s, snippet, style);
let input_string_kind = find_width_map_from_snippet(s, snippet, style);
let (width_map, is_literal) = match input_string_kind {
InputStringKind::Literal { width_mappings } => (width_mappings, true),
InputStringKind::NotALiteral => (Vec::new(), false),
};
Parser {
mode,
input: s,
Expand Down Expand Up @@ -848,14 +859,14 @@ fn find_width_map_from_snippet(
input: &str,
snippet: Option<string::String>,
str_style: Option<usize>,
) -> (Vec<InnerWidthMapping>, bool) {
) -> InputStringKind {
let snippet = match snippet {
Some(ref s) if s.starts_with('"') || s.starts_with("r\"") || s.starts_with("r#") => s,
_ => return (vec![], false),
_ => return InputStringKind::NotALiteral,
};

if str_style.is_some() {
return (vec![], true);
return InputStringKind::Literal { width_mappings: Vec::new() };
}

// Strip quotes.
Expand All @@ -868,15 +879,15 @@ fn find_width_map_from_snippet(
// Alternatively, we could just count the trailing newlines and only trim one from the input if they don't match up.
let input_no_nl = input.trim_end_matches('\n');
let Ok(unescaped) = unescape_string(snippet) else {
return (vec![], false);
return InputStringKind::NotALiteral;
};

let unescaped_no_nl = unescaped.trim_end_matches('\n');

if unescaped_no_nl != input_no_nl {
// The source string that we're pointing at isn't our input, so spans pointing at it will be incorrect.
// This can for example happen with proc macros that respan generated literals.
return (vec![], false);
return InputStringKind::NotALiteral;
}

let mut s = snippet.char_indices();
Expand Down Expand Up @@ -958,7 +969,7 @@ fn find_width_map_from_snippet(
}
}

(width_mappings, true)
InputStringKind::Literal { width_mappings }
}

fn unescape_string(string: &str) -> Result<string::String, unescape::EscapeError> {
Expand Down

0 comments on commit 31b490d

Please sign in to comment.