about summary refs log tree commit diff
path: root/src/lib.rs
blob: e0c8c5bd722e68aaee1ba74c6f63f20f52033e13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
pub struct Html {
	pub nodes: Vec<Node>,
}

impl Html {
	pub fn parse<S: AsRef<str>>(raw: S) -> Self {
		let mut raw = raw.as_ref();

		let mut nodes = vec![];

		loop {
			let Consumed { node, remaining } = Self::parse_node(raw);

			nodes.push(node);

			match remaining {
				None => break Self { nodes },
				Some(rem) => raw = rem,
			}
		}
	}

	fn parse_node(raw: &str) -> Consumed {
		match Self::is_tag(raw) {
			Some(_) => match Self::parse_comment(raw) {
				None => {
					print!("Node ");
					Self::parse_tag(raw)
				}
				Some(cmt) => cmt,
			},
			None => {
				print!("Text ");
				let cons = Self::parse_text(raw);
				println!("## {:?}", cons.node);
				cons
			}
		}
	}

	fn parse_tag(raw: &str) -> Consumed {
		let (root_tag, mut rest) = Self::is_tag(raw).unwrap();

		//println!("- {raw}");
		if root_tag.closing {
			panic!(
				"found closing tag when not expected! {:?}\n{raw}",
				root_tag.name
			)
		} else if root_tag.self_closing {
			println!("self close return early");
			return Consumed {
				node: Node::Tag {
					self_closing: true,
					name: root_tag.name.into(),
					children: vec![],
				},
				remaining: rest,
			};
		}

		let mut children = vec![];

		loop {
			match Self::is_tag(rest.unwrap()) {
				Some((
					ParsedTag {
						closing: true,
						name,
						self_closing: false,
						..
					},
					remaining,
				)) if name == root_tag.name => {
					println!("ret closed - {name}");
					break Consumed {
						node: Node::Tag {
							self_closing: false,
							name: root_tag.name.to_owned(),
							children,
						},
						remaining,
					};
				}
				_ => {
					println!("recur. ends on {}", root_tag.name,);
					let cons = Self::parse_node(rest.unwrap());
					rest = cons.remaining;
					children.push(cons.node);
				}
			}
		}
	}

	fn parse_comment(raw: &str) -> Option<Consumed> {
		if raw.starts_with("<!--") {
			let after_start = &raw[4..];
			match after_start.find("-->") {
				None => None,
				Some(end) => {
					let comment = &after_start[..end];
					let rest = after_start.get(end + 3..);

					Some(Consumed {
						node: Node::Comment {
							body: comment.into(),
						},
						remaining: rest,
					})
				}
			}
		} else {
			None
		}
	}

	/// check if the start of the string is a valid tag
	#[rustfmt::skip]
	fn is_tag(raw: &str) -> Option<(ParsedTag,  Option<&str>)> {
		// Starts '<' and any non-whitespace character
		let starts_right = raw.starts_with('<')
			&& raw.chars().nth(1).map(|c| !c.is_ascii_whitespace()).unwrap_or(false);

		if !starts_right {
			return None;
		}

		match raw.find('>') {
			// not a tag if there's no close
			None => None,
			Some(idx) => {
				let rest = match raw.get(idx+1..) {
					None => None,
					Some("") => None,
					Some(txt) => Some(txt)
				};
				let tag_innards = &raw[1..idx];

				let close = tag_innards.starts_with('/');
				let self_close_idx = {
					let possible = &tag_innards[1..];
					let last_whole_char = possible.rfind(|c: char| !c.is_ascii_whitespace()).map(|n| n + 1);
					let last_slash = possible.rfind('/').map(|n| n + 1);
					match (last_slash, last_whole_char) {
						(Some(slash), Some(whole)) if slash == whole => {
							Some(slash)
						},
						_ => None
					}
				};
				let self_close = self_close_idx.is_some();
				// can't close and self_close
				if close && self_close { return None; }

				// clean the close from the raw string
				let name_raw = if let Some(close_idx) = self_close_idx {
					&tag_innards[..close_idx]
				} else if close {
					&tag_innards[1..]
				} else {
					tag_innards
				};

				let (name, body) = match name_raw.find(|c: char| c.is_ascii_whitespace()){
					None => {
						(name_raw, "")
					},
					Some(idx) => {
						(&name_raw[..idx], &name_raw[idx+1..])
					}
				};

				Some((ParsedTag{
					closing: close,
					self_closing: self_close,
					name,
					body
				}, rest))
			}
		}
	}

	fn parse_text(raw: &str) -> Consumed {
		let mut end_idx = 0;
		let mut search_from = raw;

		loop {
			match search_from.find('<') {
				// if we ever run out of <'s, the entire string was text
				None => {
					break Consumed {
						node: Node::Text(raw.to_owned()),
						remaining: None,
					}
				}
				Some(idx) => {
					end_idx += idx;

					if Self::is_tag(&search_from[idx..]).is_some() {
						// we've found a new tag, this text node is done
						break Consumed {
							node: Node::Text(raw[..end_idx].to_owned()),
							remaining: Some(&raw[end_idx..]),
						};
					} else {
						// step over the <
						end_idx += 1;
						search_from = &raw[end_idx..];
					}
				}
			}
		}
	}
}

struct Consumed<'a> {
	node: Node,
	remaining: Option<&'a str>,
}

struct ParsedTag<'a> {
	closing: bool,
	name: &'a str,
	// a tag's body is what exists between the end of the name and the end of
	// the tag (including a self-close that may be there and any whitespace)
	body: &'a str,
	self_closing: bool,
}

impl<'a> ParsedTag<'a> {
	/// Whether or not this tag closes or self-closes
	pub fn closes(&self) -> bool {
		self.closing || self.self_closing
	}
}

#[derive(Debug, PartialEq)]
pub enum Node {
	Text(String),
	Tag {
		// for roundtripping
		self_closing: bool,
		name: String,
		children: Vec<Node>,
	},
	Comment {
		body: String,
	},
}

#[macro_export]
macro_rules! text {
	($text:expr) => {
		Node::Text(String::from($text))
	};
}

#[cfg(test)]
mod test {
	use crate::{Html, Node};

	macro_rules! text {
		($text:expr) => {
			Node::Text(String::from($text))
		};
	}

	#[test]
	fn parse_text_finds_start_of_tag() {
		let no_tag = "Hello, World!";
		let starts_tag = "<p>Hello, World!";
		let ends_tag = "Hello, World!</p>";

		let no_tag_res = Html::parse_text(no_tag);
		assert_eq!(no_tag_res.node, text!("Hello, World!"));
		assert!(no_tag_res.remaining.is_none());

		let starts_tag_res = Html::parse_text(starts_tag);
		assert_eq!(starts_tag_res.node, text!(""));
		assert_eq!(starts_tag_res.remaining, Some(starts_tag));

		let ends_tag_res = Html::parse_text(ends_tag);
		assert_eq!(ends_tag_res.node, text!("Hello, World!"));
		assert_eq!(ends_tag_res.remaining, Some("</p>"));
	}

	#[test]
	fn parse_text_correctly_ignores_nontags() {
		let sentence = "The condition 2 < 1 should be 1 > 2";
		let weird = "Hello, < p>";
		let no_close = "Hello <p my name is ";

		let sentence_res = Html::parse_text(sentence);
		assert_eq!(sentence_res.node, text!(sentence));
		assert!(sentence_res.remaining.is_none());

		let weird_res = Html::parse_text(weird);
		assert_eq!(weird_res.node, text!(weird));
		assert!(weird_res.remaining.is_none());

		let no_close_res = Html::parse_text(no_close);
		assert_eq!(no_close_res.node, text!(no_close));
		assert!(no_close_res.remaining.is_none());
	}

	#[test]
	fn parse_node_parses_tag() {
		let basic = "<p>Hello!</p>";

		let hh = Html::parse_node(basic);
		assert_eq!(
			hh.node,
			Node::Tag {
				self_closing: false,
				name: "p".into(),
				children: vec![text!("Hello!")]
			}
		)
	}

	#[test]
	fn parse_node_parses_nested_tags() {
		let nested = "<p><p>Hello!</p></p>";

		let hh = Html::parse_node(nested);
		assert_eq!(
			hh.node,
			Node::Tag {
				self_closing: false,
				name: "p".into(),
				children: vec![Node::Tag {
					self_closing: false,
					name: "p".into(),
					children: vec![text!("Hello!")]
				}]
			}
		)
	}

	#[test]
	fn parse_multiple_toplevel() {
		let nested = "<p>Hello </p><p>World!</p>";

		let hh = Html::parse(nested);
		assert_eq!(
			hh.nodes,
			vec![
				Node::Tag {
					self_closing: false,
					name: "p".into(),
					children: vec![text!("Hello ")]
				},
				Node::Tag {
					self_closing: false,
					name: "p".into(),
					children: vec![text!("World!")]
				}
			]
		)
	}
}