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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
|
use core::fmt;
pub use tag::{Tag, TagIterator, TagIteratorMut};
//mod query;
mod tag;
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,
}
}
}
pub fn child_tags(&self) -> TagIterator {
TagIterator {
inner: self.nodes.iter(),
}
}
pub fn child_tags_mut(&mut self) -> TagIteratorMut {
TagIteratorMut {
inner: self.nodes.iter_mut(),
}
}
pub fn get_by_tag_name_mut(&mut self, looking: &str) -> Option<&mut Tag> {
// depth first
fn find_node<'a>(tag: &'a mut Tag, looking: &str) -> Option<&'a mut Tag> {
if tag.name.as_str() == looking {
return Some(tag);
}
for child in tag.child_tags_mut() {
if let Some(tag) = find_node(child, looking) {
return Some(tag);
}
}
None
}
for child in self.child_tags_mut() {
if let Some(tag) = find_node(child, looking) {
return Some(tag);
}
}
None
}
pub fn get_parent_that_contains_tag_name_mut(&mut self, looking: &str) -> Option<&mut Tag> {
// depth first
fn find_node<'a>(tag: &'a mut Tag, looking: &str) -> Option<&'a mut Tag> {
if tag.has_tag(looking) {
return Some(tag);
}
for child_tag in tag.child_tags_mut() {
if let Some(tag) = find_node(child_tag, looking) {
return Some(tag);
}
}
None
}
for child_tag in self.child_tags_mut() {
if let Some(tag) = find_node(child_tag, looking) {
return Some(tag);
}
}
None
}
pub fn get_by_id(&self, id: &str) -> Option<&Tag> {
// depth first
fn find_node<'a>(tag: &'a Tag, id: &str) -> Option<&'a Tag> {
if tag.id().unwrap_or_default() == id {
return Some(tag);
}
for child in tag.child_tags() {
if let Some(tag) = find_node(child, id) {
return Some(tag);
}
}
None
}
for child in self.child_tags() {
if let Some(tag) = find_node(child, id) {
return Some(tag);
}
}
None
}
fn parse_node(raw: &str) -> Consumed {
match Self::is_tag(raw) {
Some(_) => {
if let Some(cmt) = Self::parse_comment(raw) {
cmt
} else {
Self::parse_tag(raw)
}
}
None => {
let cons = Self::parse_text(raw);
cons
}
}
}
fn parse_tag(raw: &str) -> Consumed {
let (root_tag, mut rest) = Self::is_tag(raw).unwrap();
let mut tag = if root_tag.body.is_empty() {
Tag {
name: root_tag.name.to_owned(),
body: None,
self_closing: root_tag.self_closing,
children: vec![],
}
} else {
Tag {
name: root_tag.name.into(),
body: Some(root_tag.body.to_owned()),
self_closing: root_tag.self_closing,
children: vec![],
}
};
if root_tag.closing {
panic!(
"found closing tag when not expected! {:?}\n{raw}",
root_tag.name
)
} else if root_tag.self_closing {
return Consumed {
node: Node::Tag(tag),
remaining: rest,
};
}
loop {
// Special case <script> and <style>
if root_tag.name == "script" && tag.get_attribute("src").is_none()
|| root_tag.name == "style"
{
let special = Self::special_parse(rest.unwrap(), root_tag.name);
match special {
None => {
panic!("found tag '{}' with no end", root_tag.name);
}
Some((text, remaining)) => {
let remaining = if remaining.is_empty() {
None
} else {
Some(remaining)
};
tag.children.push(text!(text));
return Consumed {
node: Node::Tag(tag),
remaining,
};
}
}
}
// Find the closing end of out root_tag
if let Some((parsed, remaining)) = Self::is_tag(rest.unwrap()) {
if parsed.closing && parsed.name == root_tag.name {
break Consumed {
node: Node::Tag(tag),
remaining,
};
}
}
// Not our closing root? parse and push
let cons = Self::parse_node(rest.unwrap());
rest = cons.remaining;
tag.children.push(cons.node);
}
}
fn special_parse<'a>(raw: &'a str, looking_for_name: &str) -> Option<(&'a str, &'a str)> {
let close = format!("</{looking_for_name}>");
let mut offset = 0;
loop {
match raw[offset..].find('\n') {
None => return None,
Some(nl_idx) => {
offset += nl_idx + 1;
match raw[offset..].find(|c: char| !c.is_ascii_whitespace()) {
None => return None,
Some(whole_idx) => {
let whole_start = &raw[offset + whole_idx..];
if let Some(stripped) = whole_start.strip_prefix(&close) {
return Some((&raw[..offset + whole_idx], stripped));
}
}
}
}
}
}
}
fn parse_comment(raw: &str) -> Option<Consumed> {
if let Some(after_start) = raw.strip_prefix("<!--") {
after_start.find("-->").map(|end| Consumed {
node: Node::Comment(after_start[..end].into()),
remaining: after_start.get(end + 3..),
})
} 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];
// Tag is closing. Don't check for self-close
// as they cannot be on the same tag
if let Some(closing) = tag_innards.strip_prefix('/') {
match closing.find(' ') {
None => return Some((ParsedTag {
closing: true,
self_closing: false,
name: closing,
body: ""
}, rest)),
Some(idx) => {
let name = &closing[..idx];
let body = &closing[idx..];
return Some((ParsedTag{
closing: true,
self_closing: false,
name,
body
}, rest))
}
}
}
if let Some(closing) = tag_innards.strip_suffix('/') {
match closing.find(' ') {
None => return Some((ParsedTag {
closing: false,
self_closing: true,
name: closing,
body: ""
}, rest)),
Some(idx) => {
let name = &closing[..idx];
let body = &closing[idx+1..];
return Some((ParsedTag{
closing: false,
self_closing: true,
name,
body
}, rest))
}
}
}
let (name, body) = match tag_innards.find(' '){
None => {
(tag_innards, "")
},
Some(idx) => {
(&tag_innards[..idx], &tag_innards[idx+1..])
}
};
Some((ParsedTag{
closing: false,
self_closing: false,
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..];
}
}
}
}
}
}
impl fmt::Display for Html {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for node in &self.nodes {
write!(f, "{node}")?;
}
Ok(())
}
}
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,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Node {
Text(String),
Tag(Tag),
Comment(String),
}
impl fmt::Display for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Text(txt) => write!(f, "{txt}"),
Self::Tag(tag) => write!(f, "{tag}"),
Self::Comment(cmt) => write!(f, "<!--{cmt}-->"),
}
}
}
#[macro_export]
macro_rules! tag {
($name:expr) => {
$crate::Node::Tag($crate::Tag {
name: String::from($name),
body: None,
self_closing: false,
children: vec![],
})
};
($name:expr, [$($children:expr),+]) => {
$crate::Node::Tag($crate::Tag {
name: String::from($name),
body: None,
self_closing: false,
children: vec![$($children),+],
})
};
($name:expr, $body:expr) => {
$crate::Node::Tag($crate::Tag {
name: String::from($name),
body: Some(String::from($body)),
self_closing: false,
children: vec![],
})
};
($name:expr, $body:expr, [$($children:expr),+]) => {
$crate::Node::Tag($crate::Tag {
name: String::from($name),
body: Some(String::from($body)),
self_closing: false,
children: vec![$($children),+],
})
};
}
#[macro_export]
macro_rules! text {
($text:expr) => {
$crate::Node::Text(String::from($text))
};
}
#[macro_export]
macro_rules! comment {
($text:expr) => {
$crate::Node::Comment(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 special_parse_find_tag_end() {
let basic = "words words\n</script>";
let special = Html::special_parse(basic, "script");
assert_eq!(special.unwrap().0, "words words\n");
assert!(special.unwrap().1.is_empty());
}
#[test]
fn special_parse_correctly_ignore_non_start() {
let nonstart = "first_line\nlet end = '</script>';\n";
let special = Html::special_parse(nonstart, "script");
assert!(special.is_none());
}
#[test]
fn special_parse_correctly_handles_leading_whitespace() {
let white = "words words\n \t\t</script>";
let special = Html::special_parse(white, "script");
assert_eq!(special.unwrap().0, "words words\n \t\t");
}
#[test]
fn parse_node_parses_comment() {
let cmt = "<!-- Comment! -->";
let node = Html::parse_node(cmt);
assert_eq!(node.node, comment!(" Comment! "));
}
#[test]
fn parse_node_parses_tag() {
let basic = "<p>Hello!</p>";
let hh = Html::parse_node(basic);
assert_eq!(hh.node, tag!("p", [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, tag!("p", [tag!("p", [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![tag!("p", [text!("Hello ")]), tag!("p", [text!("World!")])]
)
}
#[test]
fn parse_script() {
let raw = "<head>\n\t<script>let k=\"v\";\n\t</script>\n</head>";
let hh = Html::parse(raw);
assert_eq!(
hh.nodes,
vec![tag!(
"head",
[
text!("\n\t"),
tag!("script", [text!("let k=\"v\";\n\t")]),
text!("\n")
]
)]
)
}
#[test]
fn parse_external_script() {
let raw = "<head>\n\t<script src=\"script.js\"></script>\n</head>";
let hh = Html::parse(raw);
assert_eq!(
hh.nodes,
vec![tag!(
"head",
[
text!("\n\t"),
tag!("script", "src=\"script.js\""),
text!("\n")
]
)]
)
}
fn test_roundtrip(raw: &str) {
let html = Html::parse(raw);
let string = html.to_string();
for (raw, html) in raw.lines().zip(string.lines()) {
assert_eq!(raw, html)
}
}
#[test]
fn round_trip_simple() {
test_roundtrip("<p>Hello!</p>")
}
#[test]
fn round_trip_complex() {
test_roundtrip(
r#"
<html>
<head>
<link rel="style.css"/>
<title>Title!</title>
<script>
alert("hello!");
</script>
</head>
<body>
<p>Hello, <i>World!</i></p>
</body>
</html>"#,
)
}
}
|