From a3c2e79e7b47007ac3b82cbbd36600c1be92c4d1 Mon Sep 17 00:00:00 2001 From: dalance Date: Fri, 28 Jun 2019 12:29:06 +0900 Subject: [PATCH] Add comment --- src/comment.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 2 files changed, 52 insertions(+) create mode 100644 src/comment.rs diff --git a/src/comment.rs b/src/comment.rs new file mode 100644 index 0000000..99223d0 --- /dev/null +++ b/src/comment.rs @@ -0,0 +1,51 @@ +use nom::branch::*; +use nom::bytes::complete::*; +use nom::IResult; + +// ----------------------------------------------------------------------------- + +#[derive(Debug)] +pub struct Comment<'a> { + pub raw: Vec<&'a str>, +} + +// ----------------------------------------------------------------------------- + +pub fn comment(s: &str) -> IResult<&str, Comment> { + alt((one_line_comment, block_comment))(s) +} + +pub fn one_line_comment(s: &str) -> IResult<&str, Comment> { + let (s, x) = tag("//")(s)?; + let (s, y) = is_not("\n")(s)?; + let raw = vec![x, y]; + Ok((s, Comment { raw })) +} + +pub fn block_comment(s: &str) -> IResult<&str, Comment> { + let (s, x) = tag("/*")(s)?; + let (s, y) = is_not("*/")(s)?; + let (s, z) = tag("*/")(s)?; + let raw = vec![x, y, z]; + Ok((s, Comment { raw })) +} + +// ----------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use nom::combinator::*; + + #[test] + fn test() { + assert_eq!( + format!("{:?}", all_consuming(comment)("// comment")), + "Ok((\"\", Comment { raw: [\"//\", \" comment\"] }))" + ); + assert_eq!( + format!("{:?}", all_consuming(comment)("/* comment\n\n */")), + "Ok((\"\", Comment { raw: [\"/*\", \" comment\\n\\n \", \"*/\"] }))" + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index eb6d296..dd690be 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +pub mod comment; pub mod identifier; pub mod number; pub mod util;