1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
use combine::{
    choice, eof,
    error::ParseError,
    optional,
    parser::{char::string, repeat::take_until},
    attempt, Parser, Stream,
};
use strings;
use tokens::Token;

#[derive(Debug, PartialEq, Clone)]
pub struct Comment {
    pub kind: Kind,
    pub content: String,
    pub tail_content: Option<String>,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Kind {
    Single,
    Multi,
    Html,
    Arrow,
}

impl Comment {
    pub fn from_parts(content: String, kind: Kind, tail_content: Option<String>) -> Self {
        Comment {
            content,
            kind,
            tail_content,
        }
    }

    pub fn new_single_line(content: &str) -> Self {
        Comment::from_parts(content.to_owned(), Kind::Single, None)
    }

    pub fn new_multi_line(content: &str) -> Self {
        Comment::from_parts(content.to_owned(), Kind::Multi, None)
    }

    pub fn new_html(content: &str, tail_content: Option<String>) -> Self {
        Comment::from_parts(content.to_owned(), Kind::Html, tail_content)
    }

    pub fn new_html_no_tail(content: &str) -> Self {
        Comment::new_html(content, None)
    }

    pub fn new_html_with_tail(content: &str, tail: &str) -> Self {
        Comment::new_html(content, Some(tail.to_owned()))
    }

    pub fn new_arrow(content: &str) -> Self {
        Self::from_parts(content.to_owned(), Kind::Arrow, None)
    }

    pub fn is_multi_line(&self) -> bool {
        self.kind == Kind::Multi
    }

    pub fn is_single_line(&self) -> bool {
        self.kind == Kind::Single
    }

    pub fn is_html(&self) -> bool {
        self.kind == Kind::Multi
    }

    pub fn is_arrow(&self) -> bool {
        self.kind == Kind::Arrow
    }
}

impl ToString for Comment {
    fn to_string(&self) -> String {
        match self.kind {
            Kind::Single => format!("//{}", self.content),
            Kind::Multi => format!("/*{}*/", self.content),
            Kind::Html => format!("<!--{}-->", self.content),
            Kind::Arrow => format!("-->{}", self.content),
        }
    }
}

pub(crate) fn comment<I>() -> impl Parser<Input = I, Output = Token>
where
    I: Stream<Item = char>,
    I::Error: ParseError<I::Item, I::Range, I::Position>,
{
    choice((
        attempt(multi_comment()),
        attempt(single_comment()),
        attempt(html_comment()),
        attempt(arrow_comment()),
    )).map(Token::Comment)
}

pub(crate) fn single_comment<I>() -> impl Parser<Input = I, Output = Comment>
where
    I: Stream<Item = char>,
    I::Error: ParseError<I::Item, I::Range, I::Position>,
{
    (
        string("//"),
        take_until(choice((
            attempt(strings::line_terminator_sequence()),
            attempt(eof().map(|_| String::new())),
        ))),
    )
        .map(|(_, content): (_, String)| Comment::new_single_line(&content))
}

pub(crate) fn arrow_comment<I>() -> impl Parser<Input = I, Output = Comment>
where
    I: Stream<Item = char>,
    I::Error: ParseError<I::Item, I::Range, I::Position>,
{
    (
        string("-->"),
        take_until(choice((
            attempt(strings::line_terminator_sequence()),
            attempt(eof().map(|_| String::new())),
        ))),
    )
        .map(|(_, content): (_, String)| Comment::new_arrow(&content))
}

pub(crate) fn multi_comment<I>() -> impl Parser<Input = I, Output = Comment>
where
    I: Stream<Item = char>,
    I::Error: ParseError<I::Item, I::Range, I::Position>,
{
    (
        multi_line_comment_start(),
        take_until(attempt(string("*/"))),
        multi_line_comment_end(),
    )
        .map(|(_s, c, _e): (String, String, String)| Comment::new_multi_line(&c))
}

fn multi_line_comment_start<I>() -> impl Parser<Input = I, Output = String>
where
    I: Stream<Item = char>,
    I::Error: ParseError<I::Item, I::Range, I::Position>,
{
    (string("/*")).map(|s| s.to_string())
}

fn multi_line_comment_end<I>() -> impl Parser<Input = I, Output = String>
where
    I: Stream<Item = char>,
    I::Error: ParseError<I::Item, I::Range, I::Position>,
{
    (string("*/")).map(|s| s.to_string())
}

fn html_comment<I>() -> impl Parser<Input = I, Output = Comment>
where
    I: Stream<Item = char>,
    I::Error: ParseError<I::Item, I::Range, I::Position>,
{
    (
        string("<!--"),
        take_until(attempt(string("-->"))),
        string("-->"),
        optional(take_until(attempt(strings::line_terminator_sequence()))),
    )
        .map(|(_, content, _, tail): (_, String, _, Option<String>)| {
            Comment::new_html(&content, tail)
        })
}

#[cfg(test)]
mod test {
    use super::*;
    use tokens::token;
    #[test]
    fn comments_test() {
        let tests = vec![
            "//single line comments",
            "// another one with a space",
            "/*inline multi comments*/",
            "/*multi line comments
* that have extra decoration
* to help with readability
*/",
        ];
        for test in tests {
            let is_multi = test.starts_with("/*");
            let p = token().parse(test.clone()).unwrap();
            let comment_contents = test
                .lines()
                .map(|l| {
                    l.trim()
                        .replace("//", "")
                        .replace("/*", "")
                        .replace("*/", "")
                }).collect::<Vec<String>>()
                .join("\n");
            assert_eq!(p, (Token::comment(&comment_contents, is_multi), ""));
        }
    }

    fn format_test_comment(s: &str, kind: Kind) -> String {
        let (left_matches, right_matches) = match kind {
            Kind::Single => ("//", ""),
            Kind::Multi => ("/*", "*/"),
            Kind::Html => ("<!--", "-->"),
            Kind::Arrow => ("-->", ""),
        };
        s.lines()
            .map(|l| {
                l.trim()
                    .trim_left_matches(left_matches)
                    .trim_right_matches(right_matches)
            }).collect::<Vec<&str>>()
            .join("\n")
    }
    proptest!{
        #[test]
        fn multi_line_comments_prop(s in r#"(/\*(.+[\n\r*])+\*/)"#) {
            let r = token().easy_parse(s.as_str()).unwrap();
            assert!(r.0.is_comment(), r.0.matches_comment_str(&format_test_comment(&s, Kind::Multi)));
        }
    }

    proptest!{
        #[test]
        fn single_line_comments_prop(s in r#"(//.*)+"#) {
            let r = token().easy_parse(s.as_str()).unwrap();
            assert!(r.0.is_comment(), r.0.matches_comment_str(&format_test_comment(&s, Kind::Single)));
        }
    }

    proptest!{
        #[test]
        fn html_comments_prop(s in r#"<!--.*-->"#) {
            eprintln!("testing {:?}", s);
            let r = token().easy_parse(s.as_str()).unwrap();
            assert!(r.0.is_comment(), r.0.matches_comment_str(&format_test_comment(&s, Kind::Html)));
        }
    }
    proptest!{
        #[test]
        fn arrow_comments_prop(s in r#"-->.*"#) {
            eprintln!("testing {:?}", s);
            let r = token().easy_parse(s.as_str()).unwrap();
            assert!(r.0.is_comment(), r.0.matches_comment_str(&format_test_comment(&s, Kind::Arrow)));
        }
    }

}