| 1 |
use std::{borrow::Cow, str::Split}; |
| 2 |
|
| 3 |
use crate::parser::{ParserError, ParserErrorKind}; |
| 4 |
|
| 5 |
/// An iterator over parsed string "parts". |
| 6 |
pub enum StringPartsIter<'a> { |
| 7 |
Normal(StringParts<'a>), |
| 8 |
Multiline(MultilineStringParts<'a>), |
| 9 |
} |
| 10 |
|
| 11 |
impl<'a> StringPartsIter<'a> { |
| 12 |
/// Returns an iterator over string parts for the given substring containing |
| 13 |
/// only the _inner_ contents (between quotes) of a single-line string. |
| 14 |
/// The given pos is the source position of this substring for error reporting. |
| 15 |
pub fn new(src: &'a str, pos: usize) -> Self { |
| 16 |
Self::Normal(StringParts { src, pos }) |
| 17 |
} |
| 18 |
|
| 19 |
/// Returns an iterator over string parts for the given substring containing |
| 20 |
/// only the _inner_ contents (between quotes) of a multiline string. |
| 21 |
/// The given pos is the source position of this substring for error reporting. |
| 22 |
pub fn new_multiline(src: &'a str, pos: usize) -> Result<Self, ParserError> { |
| 23 |
Ok(Self::Multiline(MultilineStringParts::new(src, pos)?)) |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
impl<'a> Iterator for StringPartsIter<'a> { |
| 28 |
type Item = Result<Cow<'a, str>, ParserError>; |
| 29 |
|
| 30 |
fn next(&mut self) -> Option<Self::Item> { |
| 31 |
match self { |
| 32 |
StringPartsIter::Normal(parts) => parts.next(), |
| 33 |
StringPartsIter::Multiline(parts) => parts.next(), |
| 34 |
} |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
pub struct StringParts<'a> { |
| 39 |
src: &'a str, |
| 40 |
pos: usize, |
| 41 |
} |
| 42 |
|
| 43 |
impl<'a> StringParts<'a> { |
| 44 |
fn next_part(&mut self) -> Result<Cow<'a, str>, ParserError> { |
| 45 |
let (part, consumed) = match self.src.find('\\') { |
| 46 |
Some(0) => { |
| 47 |
let (esc_char, esc_len) = unescape(self.src).ok_or_else(|| { |
| 48 |
ParserError::new(ParserErrorKind::InvalidEscape, self.pos..self.pos + 1) |
| 49 |
})?; |
| 50 |
(Cow::Owned(esc_char.to_string()), esc_len) |
| 51 |
} |
| 52 |
Some(next_esc) => { |
| 53 |
let esc_prefix = &self.src[..next_esc]; |
| 54 |
(Cow::Borrowed(esc_prefix), esc_prefix.len()) |
| 55 |
} |
| 56 |
None => (Cow::Borrowed(self.src), self.src.len()), |
| 57 |
}; |
| 58 |
self.src = &self.src[consumed..]; |
| 59 |
self.pos += consumed; |
| 60 |
Ok(part) |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
impl<'a> Iterator for StringParts<'a> { |
| 65 |
type Item = Result<Cow<'a, str>, ParserError>; |
| 66 |
|
| 67 |
fn next(&mut self) -> Option<Self::Item> { |
| 68 |
if self.src.is_empty() { |
| 69 |
return None; |
| 70 |
} |
| 71 |
Some(self.next_part()) |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
/// An iterator over parsed string "parts", each of which is either a literal |
| 76 |
/// substring of the source or a decoded escape sequence. |
| 77 |
pub struct MultilineStringParts<'a> { |
| 78 |
curr: StringParts<'a>, |
| 79 |
lines: Split<'a, char>, |
| 80 |
next_pos: usize, |
| 81 |
indent: &'a str, |
| 82 |
} |
| 83 |
|
| 84 |
impl<'a> MultilineStringParts<'a> { |
| 85 |
fn new(src: &'a str, pos: usize) -> Result<Self, ParserError> { |
| 86 |
let end = pos + src.len(); |
| 87 |
|
| 88 |
// Strip leading carriage return as part of first newline |
| 89 |
let (src, next_pos) = match src.strip_prefix('\r') { |
| 90 |
Some(src) => (src, pos + 2), |
| 91 |
None => (src, pos + 1), |
| 92 |
}; |
| 93 |
|
| 94 |
let mut lines = src.split('\n'); |
| 95 |
|
| 96 |
// Remove mandatory final line, using trailing spaces as indent |
| 97 |
let indent = lines.next_back().unwrap(); |
| 98 |
if indent.contains(|ch| ch != ' ') { |
| 99 |
return Err(ParserError::with_detail( |
| 100 |
ParserErrorKind::InvalidMultilineString, |
| 101 |
end - 3..end, |
| 102 |
r#"closing """ must be on a line preceded only by spaces"#, |
| 103 |
)); |
| 104 |
} |
| 105 |
|
| 106 |
// Validate mandatory initial empty line |
| 107 |
if lines.next() != Some("") { |
| 108 |
return Err(ParserError::with_detail( |
| 109 |
ParserErrorKind::InvalidMultilineString, |
| 110 |
pos..pos + 1, |
| 111 |
r#"opening """ must be followed immediately by newline"#, |
| 112 |
)); |
| 113 |
} |
| 114 |
|
| 115 |
let mut parts = Self { |
| 116 |
curr: StringParts { src: "", pos: 0 }, |
| 117 |
lines, |
| 118 |
next_pos, |
| 119 |
indent, |
| 120 |
}; |
| 121 |
|
| 122 |
// Skip first newline |
| 123 |
if let Some(nl) = parts.next().transpose()? { |
| 124 |
debug_assert_eq!(nl, "\n"); |
| 125 |
} |
| 126 |
|
| 127 |
Ok(parts) |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
impl<'a> Iterator for MultilineStringParts<'a> { |
| 132 |
type Item = Result<Cow<'a, str>, ParserError>; |
| 133 |
|
| 134 |
fn next(&mut self) -> Option<Self::Item> { |
| 135 |
if self.curr.src.is_empty() { |
| 136 |
let next = self.lines.next()?; |
| 137 |
|
| 138 |
// Update next line position |
| 139 |
let pos = self.next_pos; |
| 140 |
self.next_pos += next.len() + 1; |
| 141 |
|
| 142 |
// Strip indent |
| 143 |
let Some(src) = next.strip_prefix(self.indent) else { |
| 144 |
return Some(Err(ParserError::with_detail( |
| 145 |
ParserErrorKind::InvalidMultilineString, |
| 146 |
pos..pos + 1, |
| 147 |
r#"lines must be indented at least as much as closing """"#, |
| 148 |
))); |
| 149 |
}; |
| 150 |
let pos = pos + self.indent.len(); |
| 151 |
|
| 152 |
// Strip trailing carriage return for `\r\n` newlines |
| 153 |
let src = src.strip_suffix('\r').unwrap_or(src); |
| 154 |
|
| 155 |
self.curr = StringParts { src, pos }; |
| 156 |
|
| 157 |
Some(Ok("\n".into())) |
| 158 |
} else { |
| 159 |
Some(self.curr.next_part()) |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
// Given a substring starting with an escape sequence, returns the decoded char |
| 165 |
// and length of the sequence, or None if the sequence is invalid. |
| 166 |
pub fn unescape(src: &str) -> Option<(char, usize)> { |
| 167 |
let mut chars = src.chars(); |
| 168 |
if chars.next() != Some('\\') { |
| 169 |
return None; |
| 170 |
} |
| 171 |
Some(match chars.next()? { |
| 172 |
'\\' => ('\\', 2), |
| 173 |
'\'' => ('\'', 2), |
| 174 |
'"' => ('"', 2), |
| 175 |
't' => ('\t', 2), |
| 176 |
'n' => ('\n', 2), |
| 177 |
'r' => ('\r', 2), |
| 178 |
'u' => { |
| 179 |
if chars.next()? != '{' { |
| 180 |
return None; |
| 181 |
} |
| 182 |
let mut val = 0; |
| 183 |
let mut digits = 0; |
| 184 |
loop { |
| 185 |
let ch = chars.next()?; |
| 186 |
if ch == '}' { |
| 187 |
if digits == 0 { |
| 188 |
return None; |
| 189 |
} |
| 190 |
break; |
| 191 |
} |
| 192 |
val = (val << 4) | ch.to_digit(16)?; |
| 193 |
digits += 1; |
| 194 |
if digits > 6 { |
| 195 |
return None; |
| 196 |
} |
| 197 |
} |
| 198 |
(char::from_u32(val)?, digits + 4) |
| 199 |
} |
| 200 |
_ => return None, |
| 201 |
}) |
| 202 |
} |