Add enum for find_width_map_from_snippet

This makes the relationship between the vec and the boolean clearer.
This commit is contained in:
Nilstrieb 2022-12-27 23:00:03 +01:00
parent e6c02aad93
commit 31b490d8ba

View file

@ -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 {
@ -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,
@ -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.
@ -868,7 +879,7 @@ 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');
@ -876,7 +887,7 @@ fn find_width_map_from_snippet(
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();
@ -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> {