jsonc_parser/
string.rs

1use std::borrow::Cow;
2
3pub struct ParseStringError {
4  pub byte_index: usize,
5  pub kind: ParseStringErrorKind,
6}
7
8#[derive(Debug, Clone, PartialEq, Eq, Hash)]
9pub enum ParseStringErrorKind {
10  InvalidEscapeInSingleQuoteString,
11  InvalidEscapeInDoubleQuoteString,
12  ExpectedFourHexDigits,
13  InvalidUnicodeEscapeSequence(String),
14  InvalidEscape,
15  UnterminatedStringLiteral,
16}
17
18impl std::error::Error for ParseStringErrorKind {}
19
20impl std::fmt::Display for ParseStringErrorKind {
21  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22    match self {
23      ParseStringErrorKind::InvalidEscapeInSingleQuoteString => {
24        write!(f, "Invalid escape in single quote string")
25      }
26      ParseStringErrorKind::InvalidEscapeInDoubleQuoteString => {
27        write!(f, "Invalid escape in double quote string")
28      }
29      ParseStringErrorKind::ExpectedFourHexDigits => {
30        write!(f, "Expected four hex digits")
31      }
32      ParseStringErrorKind::InvalidUnicodeEscapeSequence(value) => {
33        write!(
34          f,
35          "Invalid unicode escape sequence. '{}' is not a valid UTF8 character",
36          value
37        )
38      }
39      ParseStringErrorKind::InvalidEscape => {
40        write!(f, "Invalid escape")
41      }
42      ParseStringErrorKind::UnterminatedStringLiteral => {
43        write!(f, "Unterminated string literal")
44      }
45    }
46  }
47}
48
49pub trait CharProvider<'a> {
50  fn current_char(&mut self) -> Option<char>;
51  fn byte_index(&self) -> usize;
52  fn move_next_char(&mut self) -> Option<char>;
53  fn text(&self) -> &'a str;
54}
55
56#[cfg(feature = "cst")]
57pub fn parse_string(text: &str) -> Result<Cow<str>, ParseStringError> {
58  struct StringCharProvider<'a> {
59    text: &'a str,
60    byte_index: usize,
61    current_char: Option<char>,
62    chars: std::str::Chars<'a>,
63  }
64
65  impl<'a> CharProvider<'a> for StringCharProvider<'a> {
66    fn current_char(&mut self) -> Option<char> {
67      self.current_char
68    }
69
70    fn byte_index(&self) -> usize {
71      self.byte_index
72    }
73
74    fn move_next_char(&mut self) -> Option<char> {
75      if let Some(current_char) = self.current_char {
76        self.byte_index += current_char.len_utf8();
77      }
78      self.current_char = self.chars.next();
79      self.current_char
80    }
81
82    fn text(&self) -> &'a str {
83      self.text
84    }
85  }
86
87  let mut chars = text.chars();
88  let mut provider = StringCharProvider {
89    text,
90    byte_index: 0,
91    current_char: chars.next(),
92    chars,
93  };
94
95  parse_string_with_char_provider(&mut provider)
96}
97
98pub fn parse_string_with_char_provider<'a, T: CharProvider<'a>>(
99  chars: &mut T,
100) -> Result<Cow<'a, str>, ParseStringError> {
101  debug_assert!(
102    chars.current_char() == Some('\'') || chars.current_char() == Some('"'),
103    "Expected \", was {:?}",
104    chars.current_char()
105  );
106  let is_double_quote = chars.current_char() == Some('"');
107  let mut last_start_byte_index = chars.byte_index() + 1;
108  let mut text: Option<String> = None;
109  let mut last_was_backslash = false;
110  let mut found_end_string = false;
111  let token_start = chars.byte_index();
112
113  while let Some(current_char) = chars.move_next_char() {
114    if last_was_backslash {
115      let escape_start = chars.byte_index() - 1; // -1 for backslash
116      match current_char {
117        '"' | '\'' | '\\' | '/' | 'b' | 'f' | 'u' | 'r' | 'n' | 't' => {
118          if current_char == '"' {
119            if !is_double_quote {
120              return Err(ParseStringError {
121                byte_index: escape_start,
122                kind: ParseStringErrorKind::InvalidEscapeInSingleQuoteString,
123              });
124            }
125          } else if current_char == '\'' && is_double_quote {
126            return Err(ParseStringError {
127              byte_index: escape_start,
128              kind: ParseStringErrorKind::InvalidEscapeInDoubleQuoteString,
129            });
130          }
131
132          let previous_text = &chars.text()[last_start_byte_index..escape_start];
133          if text.is_none() {
134            text = Some(String::new());
135          }
136          let text = text.as_mut().unwrap();
137          text.push_str(previous_text);
138          if current_char == 'u' {
139            let mut hex_text = String::new();
140            // expect four hex values
141            for _ in 0..4 {
142              let current_char = chars.move_next_char();
143              if !is_hex(current_char) {
144                return Err(ParseStringError {
145                  byte_index: escape_start,
146                  kind: ParseStringErrorKind::ExpectedFourHexDigits,
147                });
148              }
149              if let Some(current_char) = current_char {
150                hex_text.push(current_char);
151              }
152            }
153
154            let hex_u32 = u32::from_str_radix(&hex_text, 16);
155            let hex_char = match hex_u32.ok().and_then(std::char::from_u32) {
156              Some(hex_char) => hex_char,
157              None => {
158                return Err(ParseStringError {
159                  byte_index: escape_start,
160                  kind: ParseStringErrorKind::InvalidUnicodeEscapeSequence(hex_text),
161                });
162              }
163            };
164            text.push(hex_char);
165            last_start_byte_index = chars.byte_index() + chars.current_char().map(|c| c.len_utf8()).unwrap_or(0);
166          } else {
167            text.push(match current_char {
168              'b' => '\u{08}',
169              'f' => '\u{0C}',
170              't' => '\t',
171              'r' => '\r',
172              'n' => '\n',
173              _ => current_char,
174            });
175            last_start_byte_index = chars.byte_index() + current_char.len_utf8();
176          }
177        }
178        _ => {
179          return Err(ParseStringError {
180            byte_index: escape_start,
181            kind: ParseStringErrorKind::InvalidEscape,
182          });
183        }
184      }
185      last_was_backslash = false;
186    } else if is_double_quote && current_char == '"' || !is_double_quote && current_char == '\'' {
187      found_end_string = true;
188      break;
189    } else {
190      last_was_backslash = current_char == '\\';
191    }
192  }
193
194  if found_end_string {
195    chars.move_next_char();
196    let final_segment = &chars.text()[last_start_byte_index..chars.byte_index() - 1];
197    Ok(match text {
198      Some(mut text) => {
199        text.push_str(final_segment);
200        Cow::Owned(text)
201      }
202      None => Cow::Borrowed(final_segment),
203    })
204  } else {
205    Err(ParseStringError {
206      byte_index: token_start,
207      kind: ParseStringErrorKind::UnterminatedStringLiteral,
208    })
209  }
210}
211
212fn is_hex(c: Option<char>) -> bool {
213  let Some(c) = c else {
214    return false;
215  };
216  is_digit(c) || ('a'..='f').contains(&c) || ('A'..='F').contains(&c)
217}
218
219fn is_digit(c: char) -> bool {
220  c.is_ascii_digit()
221}