1use std::fmt;
2
3use crate::tokens::{ControlWord, Property, Token};
4
5#[derive(Debug, Clone)]
6#[non_exhaustive]
7pub enum LexerError {
8 Error(String),
9 InvalidUnicode(String),
10 InvalidLastChar,
11}
12
13impl std::error::Error for LexerError {}
14
15impl fmt::Display for LexerError {
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 write!(f, "[RTF Lexer] : ")?;
18 match self {
19 LexerError::InvalidLastChar => write!(f, "Invalid last char, should be '}}'"),
20 LexerError::InvalidUnicode(uc) => write!(f, "Invalid unicode : {uc}"),
21 LexerError::Error(msg) => write!(f, "{}", msg),
22 }
23 }
24}
25
26impl From<std::str::Utf8Error> for LexerError {
27 fn from(value: std::str::Utf8Error) -> Self {
28 LexerError::Error(value.to_string())
29 }
30}
31
32impl From<std::num::ParseIntError> for LexerError {
33 fn from(value: std::num::ParseIntError) -> Self {
34 LexerError::Error(value.to_string())
35 }
36}
37
38const fn special_bytes() -> [bool; 256] {
39 let mut table = [false; 256];
40 table[b'{' as usize] = true;
41 table[b'}' as usize] = true;
42 table[b'\\' as usize] = true;
43 table[b'\r' as usize] = true;
44 table[b'\n' as usize] = true;
45 table
46}
47
48static SPECIAL: [bool; 256] = special_bytes();
49
50pub struct Lexer;
51
52impl Lexer {
53 pub fn scan(src: &str) -> Result<Vec<Token<'_>>, LexerError> {
54 let src = src.trim_matches(|c: char| c.is_whitespace() || c == '\0');
55 let bytes = src.as_bytes();
56 let len = bytes.len();
57 let mut tokens = Vec::with_capacity(len / 32 + 1);
58 let mut text_start = 0;
59 let mut i = 0;
60 while let Some(offset) = bytes[i..].iter().position(|&b| SPECIAL[usize::from(b)]) {
61 i += offset;
62 if text_start < i {
63 tokens.push(Token::PlainText(&src[text_start..i]));
64 }
65 i = match bytes[i] {
66 b'{' => {
67 tokens.push(Token::OpeningBracket);
68 i + 1
69 }
70 b'}' => {
71 tokens.push(Token::ClosingBracket);
72 i + 1
73 }
74 b'\\' => Self::escape(src, i, &mut tokens)?,
75 _ => i + 1,
76 };
77 text_start = i;
78 }
79 if text_start < len {
80 tokens.push(Token::PlainText(&src[text_start..len]));
81 }
82 Ok(tokens)
83 }
84
85 fn escape<'a>(src: &'a str, start: usize, tokens: &mut Vec<Token<'a>>) -> Result<usize, LexerError> {
86 let bytes = src.as_bytes();
87 let Some(&next) = bytes.get(start + 1) else {
88 return Ok(start + 1);
89 };
90 let symbol = |word| Token::ControlSymbol((word, Property::None));
91 match next {
92 b'a'..=b'z' | b'A'..=b'Z' => Self::control_word(src, start, tokens),
93 b'\'' => {
94 let hex = src.get(start + 2..start + 4).filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()));
95 let Some(hex) = hex else {
96 let found: String = src[start + 1..].chars().take(3).collect();
97 return Err(LexerError::InvalidUnicode(found));
98 };
99 let byte = u8::from_str_radix(hex, 16)?;
100 tokens.push(Token::ControlSymbol((ControlWord::HexChar, Property::Value(byte as i32))));
101 Ok(start + 4)
102 }
103 b'{' | b'}' | b'\\' => {
104 tokens.push(Token::PlainText(&src[start + 1..start + 2]));
105 Ok(start + 2)
106 }
107 b'\n' => {
108 tokens.push(Token::CRLF);
109 Ok(start + 2)
110 }
111 b'\r' => {
112 tokens.push(Token::CRLF);
113 Ok(if bytes.get(start + 2) == Some(&b'\n') { start + 3 } else { start + 2 })
114 }
115 b'*' => {
116 tokens.push(Token::IgnorableDestination);
117 Ok(start + 2)
118 }
119 b'~' | b'-' | b'_' | b'|' | b':' | b'\t' => {
120 tokens.push(symbol(match next {
121 b'~' => ControlWord::NonBreakingSpace,
122 b'-' => ControlWord::OptionalHyphen,
123 b'_' => ControlWord::NonBreakingHyphen,
124 b'|' => ControlWord::FormulaCharacter,
125 b':' => ControlWord::IndexSubentry,
126 _ => ControlWord::Tab,
127 }));
128 Ok(start + 2)
129 }
130 _ => Ok(start + 1 + src[start + 1..].chars().next().map_or(1, char::len_utf8)),
131 }
132 }
133
134 fn control_word<'a>(src: &'a str, start: usize, tokens: &mut Vec<Token<'a>>) -> Result<usize, LexerError> {
135 let bytes = src.as_bytes();
136 let len = bytes.len();
137 let mut end = start + 1;
138 while end < len && bytes[end].is_ascii_alphabetic() {
139 end += 1;
140 }
141 let digits = if end + 1 < len && bytes[end] == b'-' && bytes[end + 1].is_ascii_digit() { end + 1 } else { end };
142 let mut param_end = digits;
143 while param_end < len && bytes[param_end].is_ascii_digit() {
144 param_end += 1;
145 }
146 if param_end > digits {
147 end = param_end;
148 }
149 let symbol = ControlWord::from(&src[start..end])?;
150 tokens.push(Token::ControlSymbol(symbol));
151 let mut next = if bytes.get(end) == Some(&b' ') { end + 1 } else { end };
152 if let (ControlWord::Bin, Property::Value(count)) = symbol {
153 if count > 0 {
154 next = next.saturating_add(count as usize).min(len);
155 while !src.is_char_boundary(next) {
156 next += 1;
157 }
158 }
159 }
160 Ok(next)
161 }
162}
163
164#[cfg(test)]
165pub(crate) mod tests {
166 use crate::lexer::Lexer;
167 use crate::tokens::ControlWord::{
168 Ansi, Bold, ColorBlue, ColorNumber, ColorRed, FontNumber, FontSize, FontTable, HexChar, Italic, NonBreakingHyphen, NonBreakingSpace,
169 OptionalHyphen, Par, Pard, Rtf, Underline, Unknown,
170 };
171 use crate::tokens::Property::*;
172 use crate::tokens::Token::*;
173
174 #[test]
175 fn scan_entire_file_test() {
176 let tokens = Lexer::scan(r#"{ \rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard Voici du texte en {\b gras}.\par }"#);
177 assert_eq!(
178 tokens.unwrap(),
179 vec![
180 OpeningBracket,
181 PlainText(" "),
182 ControlSymbol((Rtf, Value(1))),
183 ControlSymbol((Ansi, None)),
184 OpeningBracket,
185 ControlSymbol((FontTable, None)),
186 ControlSymbol((FontNumber, Value(0))),
187 ControlSymbol((Unknown("\\fswiss"), None)),
188 PlainText("Helvetica;"),
189 ClosingBracket,
190 ControlSymbol((FontNumber, Value(0))),
191 ControlSymbol((Pard, None)),
192 PlainText("Voici du texte en "),
193 OpeningBracket,
194 ControlSymbol((Bold, None)),
195 PlainText("gras"),
196 ClosingBracket,
197 PlainText("."),
198 ControlSymbol((Par, None)),
199 ClosingBracket,
200 ]
201 );
202 }
203
204 #[test]
205 fn scan_escaped_text() {
206 let tokens = Lexer::scan(
207 r#"\f0\fs24 \cf0 test de code \
208if (a == b) \{\
209 test();\
210\} else \{\
211 return;\
212\}}"#,
213 );
214 assert_eq!(
215 tokens.unwrap(),
216 vec![
217 ControlSymbol((FontNumber, Value(0))),
218 ControlSymbol((FontSize, Value(24))),
219 ControlSymbol((ColorNumber, Value(0))),
220 PlainText("test de code "),
221 CRLF,
222 PlainText("if (a == b) "),
223 PlainText("{"),
224 CRLF,
225 PlainText(" test();"),
226 CRLF,
227 PlainText("}"),
228 PlainText(" else "),
229 PlainText("{"),
230 CRLF,
231 PlainText(" return;"),
232 CRLF,
233 PlainText("}"),
234 ClosingBracket
235 ],
236 );
237 }
238
239 #[test]
240 fn scan_ignorable_destination() {
241 let tokens = Lexer::scan(r"{\*\expandedcolortbl;;}");
242 assert_eq!(
243 tokens.unwrap(),
244 vec![OpeningBracket, IgnorableDestination, ControlSymbol((Unknown(r"\expandedcolortbl"), None)), PlainText(";;"), ClosingBracket]
245 )
246 }
247
248 #[test]
249 fn semicolon_after_control_word_is_text() {
250 let tokens = Lexer::scan(r"{\red255\blue255;}");
251 assert_eq!(
252 tokens.unwrap(),
253 vec![OpeningBracket, ControlSymbol((ColorRed, Value(255))), ControlSymbol((ColorBlue, Value(255))), PlainText(";"), ClosingBracket]
254 );
255 }
256
257 #[test]
258 fn lex_with_leading_whitespaces() {
259 let tokens = Lexer::scan("\t {\\rtf1 }\n ").unwrap();
260 assert_eq!(tokens, vec![OpeningBracket, ControlSymbol((Rtf, Value(1))), ClosingBracket]);
261 }
262
263 #[test]
264 fn unescaped_line_breaks_are_ignored() {
265 let text = r#"{\partightenfactor0
266
267\fs24 \cf0 Font size 12,
268\f0\b bold text. \ul Underline,bold text.\
269 }"#;
270 let tokens = Lexer::scan(text).unwrap();
271 assert_eq!(
272 tokens,
273 [
274 OpeningBracket,
275 ControlSymbol((Unknown("\\partightenfactor"), Value(0))),
276 ControlSymbol((FontSize, Value(24))),
277 ControlSymbol((ColorNumber, Value(0))),
278 PlainText("Font size 12,"),
279 ControlSymbol((FontNumber, Value(0))),
280 ControlSymbol((Bold, None)),
281 PlainText("bold text. "),
282 ControlSymbol((Underline, None)),
283 PlainText("Underline,bold text."),
284 CRLF,
285 PlainText(" "),
286 ClosingBracket
287 ]
288 );
289 }
290
291 #[test]
292 fn space_after_control_word() {
293 let tokens = Lexer::scan(r"{in{\i cred}ible}").unwrap();
294 assert_eq!(
295 tokens,
296 [OpeningBracket, PlainText("in"), OpeningBracket, ControlSymbol((Italic, None)), PlainText("cred"), ClosingBracket, PlainText("ible"), ClosingBracket,]
297 )
298 }
299
300 #[test]
301 fn hex_escape_is_its_own_token() {
302 let tokens = Lexer::scan(r"{je suis une b\'eate}").unwrap();
303 assert_eq!(tokens, [OpeningBracket, PlainText("je suis une b"), ControlSymbol((HexChar, Value(234))), PlainText("te"), ClosingBracket]);
304 }
305
306 #[test]
307 fn punctuation_ends_a_control_word() {
308 let tokens = Lexer::scan(r"{\b Bold\b0, then}").unwrap();
309 assert_eq!(
310 tokens,
311 [OpeningBracket, ControlSymbol((Bold, None)), PlainText("Bold"), ControlSymbol((Bold, Value(0))), PlainText(", then"), ClosingBracket]
312 );
313 }
314
315 #[test]
316 fn only_one_space_is_a_delimiter() {
317 let tokens = Lexer::scan(r"{\b two}").unwrap();
318 assert_eq!(tokens, [OpeningBracket, ControlSymbol((Bold, None)), PlainText(" two"), ClosingBracket]);
319 }
320
321 #[test]
322 fn non_ascii_ends_a_control_word() {
323 let tokens = Lexer::scan("{\\i\u{420}\u{438}\u{43C}}").unwrap();
324 assert_eq!(tokens, [OpeningBracket, ControlSymbol((Italic, None)), PlainText("\u{420}\u{438}\u{43C}"), ClosingBracket]);
325 }
326
327 #[test]
328 fn control_symbols() {
329 let tokens = Lexer::scan(r"{A\~B\-C\_D}").unwrap();
330 assert_eq!(
331 tokens,
332 [
333 OpeningBracket,
334 PlainText("A"),
335 ControlSymbol((NonBreakingSpace, None)),
336 PlainText("B"),
337 ControlSymbol((OptionalHyphen, None)),
338 PlainText("C"),
339 ControlSymbol((NonBreakingHyphen, None)),
340 PlainText("D"),
341 ClosingBracket
342 ]
343 );
344 }
345
346 #[test]
347 fn negative_parameter_needs_a_digit() {
348 let tokens = Lexer::scan(r"{\fi-180 x\b- y}").unwrap();
349 assert_eq!(
350 tokens,
351 [
352 OpeningBracket,
353 ControlSymbol((crate::tokens::ControlWord::FirstLineIdent, Value(-180))),
354 PlainText("x"),
355 ControlSymbol((Bold, None)),
356 PlainText("- y"),
357 ClosingBracket
358 ]
359 );
360 }
361
362 #[test]
363 fn bin_data_is_skipped() {
364 let tokens = Lexer::scan("{a\\bin5 }{\\x}b}").unwrap();
365 assert_eq!(tokens, [OpeningBracket, PlainText("a"), ControlSymbol((crate::tokens::ControlWord::Bin, Value(5))), PlainText("b"), ClosingBracket]);
366 }
367
368 #[test]
369 fn bin_data_stops_at_the_end() {
370 let tokens = Lexer::scan("{a\\bin99 xy").unwrap();
371 assert_eq!(tokens, [OpeningBracket, PlainText("a"), ControlSymbol((crate::tokens::ControlWord::Bin, Value(99)))]);
372 }
373
374 #[test]
375 fn unknown_control_symbol_is_dropped_whole() {
376 let tokens = Lexer::scan("{a\\\u{420}b}").unwrap();
377 assert_eq!(tokens, [OpeningBracket, PlainText("a"), PlainText("b"), ClosingBracket]);
378 }
379
380 #[test]
381 fn truncated_hex_escape_is_an_error() {
382 assert!(Lexer::scan(r"{\'5}").is_err());
383 assert!(Lexer::scan(r"{\'zz}").is_err());
384 assert!(Lexer::scan("{\\'").is_err());
385 }
386}