Debian Codegraph @

third_party/rust/wast/tests/comments.rs

raw
1 use wast::parser::{self, Parse, ParseBuffer, Parser, Result};
2
3 pub struct Comments<'a> {
4 comments: Vec<&'a str>,
5 }
6
7 impl<'a> Parse<'a> for Comments<'a> {
8 fn parse(parser: Parser<'a>) -> Result<Comments<'a>> {
9 let comments = parser.step(|mut cursor| {
10 let mut comments = Vec::new();
11 loop {
12 let (comment, c) = match cursor.comment()? {
13 Some(pair) => pair,
14 None => break,
15 };
16 cursor = c;
17 comments.push(match comment.strip_prefix(";;") {
18 Some(rest) => rest,
19 None => &comment[2..comment.len() - 2],
20 });
21 }
22 Ok((comments, cursor))
23 })?;
24 Ok(Comments { comments })
25 }
26 }
27
28 pub struct Documented<'a, T> {
29 comments: Comments<'a>,
30 item: T,
31 }
32
33 impl<'a, T: Parse<'a>> Parse<'a> for Documented<'a, T> {
34 fn parse(parser: Parser<'a>) -> Result<Self> {
35 let comments = parser.parse()?;
36 let item = parser.parens(T::parse)?;
37 Ok(Documented { comments, item })
38 }
39 }
40
41 #[test]
42 fn parse_comments() -> anyhow::Result<()> {
43 let buf = ParseBuffer::new(
44 r#"
45 ;; hello
46 (; again ;)
47 (module)
48 "#,
49 )?;
50
51 let d: Documented<wast::core::Module> = parser::parse(&buf)?;
52 assert_eq!(d.comments.comments, vec![" hello", " again "]);
53 drop(d.item);
54
55 let buf = ParseBuffer::new(
56 r#"
57 ;; this
58 (; is
59 on
60 multiple;)
61
62
63 ;; lines
64 (func)
65 "#,
66 )?;
67
68 let d: Documented<wast::core::Func> = parser::parse(&buf)?;
69 assert_eq!(
70 d.comments.comments,
71 vec![" this", " is\non\nmultiple", " lines"]
72 );
73 drop(d.item);
74 Ok(())
75 }