-
-
Save mbrubeck/5af489f19917e8c5e96a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// XML parsing adventure | |
#![license = "MIT"] | |
#![feature(phase)] | |
// extern crate simhash; | |
#[phase(plugin)] | |
extern crate peg_syntax_ext; | |
use html::{name, start_tag, end_tag, element, text}; | |
enum Node { | |
Text(String), | |
Element(String, Vec<Node>) | |
} | |
peg! html(r#" | |
#[pub] | |
name -> String | |
= [a-zA-Z0-9_]+ { match_str.to_string() } | |
#[pub] | |
start_tag -> String | |
= "<" n:name ">" { n } | |
#[pub] | |
end_tag -> String | |
= "</" n:name ">" { n } | |
#[pub] | |
element -> super::Node | |
= s:start_tag c:content e:end_tag { super::Element(s, c) } | |
#[pub] | |
content -> Vec<super::Node> | |
= (element / text)* | |
#[pub] | |
text -> super::Node | |
= (!start_tag !end_tag .)+ { super::Text(match_str.to_string()) } | |
"#) | |
#[test] | |
fn test_parser() { | |
/* | |
assert!(name("div").is_ok()); | |
assert!(name("di'v").is_err()); | |
assert_eq!(start_tag("<div>"), Ok("div")); | |
assert!(start_tag("</div>").is_err()); | |
assert_eq!(end_tag("</div>"), Ok("div")); | |
assert!(end_tag("<div>").is_err()); | |
assert_eq!( | |
element("<div>A</div>"), | |
Ok( "<div>A</div>")); | |
assert!(element("<divA</").is_err()); | |
assert_eq!( | |
element("<a>A<b>B</b></a>"), | |
Ok( "<a>A<b>B</b></a>")); | |
assert!(text("lorem ipsum").is_ok()); | |
assert!(text("lorem ipsum<div>").is_err()); | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment