Skip to content

Instantly share code, notes, and snippets.

@mbrubeck
Forked from bartolsthoorn/lib.rs
Last active August 29, 2015 14:05
Show Gist options
  • Save mbrubeck/5af489f19917e8c5e96a to your computer and use it in GitHub Desktop.
Save mbrubeck/5af489f19917e8c5e96a to your computer and use it in GitHub Desktop.
// 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