Debian Codegraph @

src/parser/attributes.rs

raw
1 use std::mem;
2
3 use crate::nodes::Attributes;
4
5 #[derive(Default)]
6 enum Kind {
7 #[default]
8 Id,
9 Class,
10 Pair(String),
11 }
12
13 pub fn parse(input: &str) -> Option<(Attributes, usize)> {
14 let mut ci = input.char_indices();
15 if ci.next()?.1 != '{' {
16 return None;
17 }
18
19 enum State {
20 Betwixt,
21 Value(Kind, String, Quote),
22 Key(String),
23 PostQuote,
24 }
25
26 enum Quote {
27 Bare,
28 Quoted,
29 QuotedEscaped,
30 }
31
32 let mut state = State::Betwixt;
33 let mut attrs = Attributes::default();
34
35 // We permit ' ' | '\t' | '\r' | '\n' between/around attributes in the braces.
36 // Is ASCII whitespace also '\v' | '\f'? Does anyone mind?
37
38 loop {
39 let (i, c) = ci.next()?;
40
41 loop {
42 match state {
43 State::Betwixt => match c {
44 '#' => {
45 state = State::Value(Kind::Id, String::new(), Quote::Bare);
46 break;
47 }
48 '.' => {
49 state = State::Value(Kind::Class, String::new(), Quote::Bare);
50 break;
51 }
52 'a'..='z' | 'A'..='Z' => {
53 state = State::Key(c.to_string());
54 break;
55 }
56 '}' => return Some((attrs, i + 1)),
57 ' ' | '\t' | '\r' | '\n' => break,
58 _ => return None,
59 },
60 State::Value(ref mut kind, ref mut value, Quote::Bare) => match c {
61 '"' if value.is_empty() => {
62 state = State::Value(mem::take(kind), mem::take(value), Quote::Quoted);
63 break;
64 }
65 // An id can contain [literally anything] in HTML5, just so long as it's non-empty.
66 // Consider looking at how Pandoc parses this part.
67 // Per above, classes are also literally anything, *except* ASCII whitespace.
68 //
69 // [literally anything]: https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute
70 //
71 // The below range of characters selected is arbitrary. Add to it if you like.
72 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | ':' | '.' | '%' => {
73 value.push(c);
74 break;
75 }
76 ' ' | '\t' | '\r' | '\n' | '}' => {
77 if value.is_empty() {
78 return None;
79 }
80 parse_attribute_value(kind, value, &mut attrs);
81 state = State::Betwixt;
82 // handle in loop
83 }
84 _ => return None,
85 },
86 State::Value(ref mut kind, ref mut value, Quote::Quoted) => match c {
87 '"' => {
88 parse_attribute_value(kind, value, &mut attrs);
89 state = State::PostQuote;
90 break;
91 }
92 '\\' => {
93 state =
94 State::Value(mem::take(kind), mem::take(value), Quote::QuotedEscaped);
95 break;
96 }
97 _ => {
98 value.push(c);
99 break;
100 }
101 },
102 State::Value(ref mut kind, ref mut value, Quote::QuotedEscaped) => {
103 value.push(c);
104 state = State::Value(mem::take(kind), mem::take(value), Quote::Quoted);
105 break;
106 }
107 State::Key(ref mut key) => match c {
108 // "Except where otherwise specified, attribute values on HTML elements may be any string value,
109 // including the empty string, and there is no restriction on what text can be specified in such
110 // attribute values."
111 // ¯\_(ツ)_/¯ I'm not driving
112 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | ':' | '.' => {
113 key.push(c);
114 break;
115 }
116 '=' => {
117 state =
118 State::Value(Kind::Pair(mem::take(key)), String::new(), Quote::Bare);
119 break;
120 }
121 _ => return None,
122 },
123 State::PostQuote => match c {
124 // Require a space after quote before anything else.
125 ' ' | '\t' | '\r' | '\n' | '}' => {
126 state = State::Betwixt;
127 // handle in loop
128 }
129 _ => return None,
130 },
131 }
132 }
133 }
134 }
135
136 fn parse_attribute_value(kind: &mut Kind, value: &mut String, attrs: &mut Attributes) {
137 match kind {
138 Kind::Id => attrs.id = Some(mem::take(value)),
139 Kind::Class => attrs.classes.push(mem::take(value)),
140 Kind::Pair(key) => attrs.pairs.push((mem::take(key), mem::take(value))),
141 };
142 }
143
144 /// Use this only in contexts where there can *not* be any following text
145 /// and the attribute set still valid; i.e. blocks are OK, inlines are not.
146 pub fn parse_off(content: &mut String) -> Option<Attributes> {
147 let mut ci = content.char_indices().rev();
148
149 enum State {
150 Pre,
151 Within,
152 Quoted,
153 /// We've hit an opening quote, but there could be a backslash behind it;
154 /// if there is, return to Quoted, otherwise go to Within and reparse.
155 MaybeQuoteEnd,
156 }
157
158 let mut state = State::Pre;
159 let mut end = None;
160
161 loop {
162 let (i, c) = ci.next()?;
163
164 loop {
165 match state {
166 State::Pre => match c {
167 '}' => {
168 end = Some(i + 1);
169 state = State::Within;
170 break;
171 }
172 _ if c.is_whitespace() => break,
173 _ => return None,
174 },
175 State::Within => match c {
176 '"' => {
177 state = State::Quoted;
178 break;
179 }
180 '{' => {
181 let (attrs, j) = parse(&content[i..])?;
182
183 // We can't transition into Within without setting `end`.
184 // If these don't match up, something is Bad.
185 if i + j != end.unwrap() {
186 return None;
187 }
188
189 // Either there's nothing left (fine!) ORRRRR there's *at least*
190 // one (but possibly multiple) whitespace, which we truncate.
191 let Some((mut i, c)) = ci.next() else {
192 content.truncate(i);
193 return Some(attrs);
194 };
195
196 if !c.is_whitespace() {
197 return None;
198 }
199
200 for (i2, c) in ci {
201 if !c.is_whitespace() {
202 break;
203 }
204 i = i2;
205 }
206
207 content.truncate(i);
208 return Some(attrs);
209 }
210 _ => break,
211 },
212 State::Quoted => match c {
213 '"' => {
214 state = State::MaybeQuoteEnd;
215 break;
216 }
217 _ => break,
218 },
219 State::MaybeQuoteEnd => match c {
220 '\\' => {
221 state = State::Quoted;
222 break;
223 }
224 _ => {
225 state = State::Within;
226 // handle in loop
227 }
228 },
229 }
230 }
231 }
232 }
233
234 #[cfg(test)]
235 mod tests {
236 use super::*;
237
238 #[test]
239 fn fundamentals() {
240 assert_eq!(parse(""), None);
241
242 assert_eq!(
243 parse("{#henlo} there"),
244 Some((
245 Attributes {
246 id: Some("henlo".to_string()),
247 ..Default::default()
248 },
249 8
250 ))
251 );
252
253 assert_eq!(
254 parse("{.oken}"),
255 Some((
256 Attributes {
257 classes: vec!["oken".to_string()],
258 ..Default::default()
259 },
260 7
261 ))
262 );
263
264 assert_eq!(
265 parse("{data-thingy=ya}"),
266 Some((
267 Attributes {
268 pairs: vec![("data-thingy".to_string(), "ya".to_string())],
269 ..Default::default()
270 },
271 16
272 ))
273 );
274
275 assert_eq!(
276 parse("{.oken #yip m=26 .sure x=3% #yap} oh!"),
277 Some((
278 Attributes {
279 id: Some("yap".to_string()),
280 classes: vec!["oken".to_string(), "sure".to_string()],
281 pairs: vec![
282 ("m".to_string(), "26".to_string()),
283 ("x".to_string(), "3%".to_string())
284 ]
285 },
286 33
287 ))
288 );
289
290 assert_eq!(
291 parse("{#\"has space, will travel\" .\"ok\\\"en\" title=\"是非 \\\"not\\\"\"}"),
292 Some((
293 Attributes {
294 id: Some("has space, will travel".to_string()),
295 classes: vec!["ok\"en".to_string(),],
296 pairs: vec![("title".to_string(), "是非 \"not\"".to_string())],
297 },
298 60
299 ))
300 );
301
302 assert_eq!(parse("{#}"), None);
303 assert_eq!(parse("{}"), Some((Attributes::default(), 2)));
304 assert_eq!(parse("{.}"), None);
305 assert_eq!(parse("{uh"), None);
306
307 assert_eq!(
308 parse("{.why\n.not}"),
309 Some((
310 Attributes {
311 classes: vec!["why".to_string(), "not".to_string()],
312 ..Default::default()
313 },
314 11
315 ))
316 );
317
318 // Consistent with Pandoc's commonmark+attributes.
319 assert_eq!(parse("{hi}"), None);
320 assert_eq!(parse("{hi=}"), None);
321 assert_eq!(
322 parse("{hi=\"\"}"),
323 Some((
324 Attributes {
325 pairs: vec![("hi".to_string(), String::new())],
326 ..Default::default()
327 },
328 7
329 ))
330 );
331 }
332
333 fn assert_parse_off(input: &str, expected_str: &str, expected_attrs: Option<Attributes>) {
334 let mut s = input.to_string();
335 let attrs = parse_off(&mut s);
336 assert_eq!(s, expected_str);
337 assert_eq!(attrs, expected_attrs);
338 }
339
340 #[test]
341 fn parses_off() {
342 assert_parse_off("hi", "hi", None);
343 assert_parse_off(
344 "hi {#yay}",
345 "hi",
346 Some(Attributes {
347 id: Some("yay".to_string()),
348 ..Default::default()
349 }),
350 );
351
352 assert_parse_off("Well!{#yay}", "Well!{#yay}", None);
353
354 assert_parse_off(
355 "Well! {#okay} {Not really.}",
356 "Well! {#okay} {Not really.}",
357 None,
358 );
359
360 assert_parse_off(
361 "Well!! {cool=\"Lest \\\"{#confusion}\\\" sets in.\" } \t",
362 "Well!!",
363 Some(Attributes {
364 pairs: vec![(
365 "cool".to_string(),
366 "Lest \"{#confusion}\" sets in.".to_string(),
367 )],
368 ..Default::default()
369 }),
370 );
371 }
372 }