From cd672d033386d4f575f31b49bebb81f20e808d7f Mon Sep 17 00:00:00 2001 From: gennyble Date: Wed, 27 Dec 2023 14:09:58 -0600 Subject: parses comments --- src/lib.rs | 58 ++++++++++++++++++++++++++++------------------------------ 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index e0c8c5b..31e8a17 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +use core::fmt; + pub struct Html { pub nodes: Vec, } @@ -10,7 +12,6 @@ impl Html { loop { let Consumed { node, remaining } = Self::parse_node(raw); - nodes.push(node); match remaining { @@ -22,17 +23,15 @@ impl Html { fn parse_node(raw: &str) -> Consumed { match Self::is_tag(raw) { - Some(_) => match Self::parse_comment(raw) { - None => { - print!("Node "); + Some(_) => { + if let Some(cmt) = Self::parse_comment(raw) { + cmt + } else { Self::parse_tag(raw) } - Some(cmt) => cmt, - }, + } None => { - print!("Text "); let cons = Self::parse_text(raw); - println!("## {:?}", cons.node); cons } } @@ -48,7 +47,6 @@ impl Html { root_tag.name ) } else if root_tag.self_closing { - println!("self close return early"); return Consumed { node: Node::Tag { self_closing: true, @@ -72,7 +70,6 @@ impl Html { }, remaining, )) if name == root_tag.name => { - println!("ret closed - {name}"); break Consumed { node: Node::Tag { self_closing: false, @@ -83,7 +80,6 @@ impl Html { }; } _ => { - println!("recur. ends on {}", root_tag.name,); let cons = Self::parse_node(rest.unwrap()); rest = cons.remaining; children.push(cons.node); @@ -93,22 +89,11 @@ impl Html { } fn parse_comment(raw: &str) -> Option { - if raw.starts_with("") { - 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, - }) - } - } + if let Some(after_start) = raw.strip_prefix("").map(|end| Consumed { + node: Node::Comment(after_start[..end].into()), + remaining: after_start.get(end + 3..), + }) } else { None } @@ -243,9 +228,7 @@ pub enum Node { name: String, children: Vec, }, - Comment { - body: String, - }, + Comment(String), } #[macro_export] @@ -255,6 +238,13 @@ macro_rules! text { }; } +#[macro_export] +macro_rules! comment { + ($text:expr) => { + Node::Comment(String::from($text)) + }; +} + #[cfg(test)] mod test { use crate::{Html, Node}; @@ -303,6 +293,14 @@ mod test { assert!(no_close_res.remaining.is_none()); } + #[test] + fn parse_node_parses_comment() { + let cmt = ""; + + let node = Html::parse_node(cmt); + assert_eq!(node.node, comment!(" Comment! ")); + } + #[test] fn parse_node_parses_tag() { let basic = "

Hello!

"; -- cgit 1.4.1-3-g733a5