blob: 59a2b0f36c7382cf634abfc01aa0edf5d869ea09 [file] [log] [blame]
David Tolnay14cbdeb2016-10-01 12:13:59 -07001use nom::IResult;
2use unicode_xid::UnicodeXID;
3
4pub fn whitespace(input: &str) -> IResult<&str, ()> {
5 if input.is_empty() {
6 return IResult::Error;
7 }
8
9 let mut start = 0;
10 let mut chars = input.char_indices();
11 while let Some((i, ch)) = chars.next() {
12 let s = &input[start + i..];
13 if ch == '/' {
David Tolnaydaaf7742016-10-03 11:11:43 -070014 if s.starts_with("//") && (!s.starts_with("///") || s.starts_with("////")) &&
15 !s.starts_with("//!") {
David Tolnay14cbdeb2016-10-01 12:13:59 -070016 if let Some(len) = s.find('\n') {
17 start += i + len + 1;
18 chars = input[start..].char_indices();
19 continue;
20 }
21 break;
David Tolnaydaaf7742016-10-03 11:11:43 -070022 } else if s.starts_with("/*") && !s.starts_with("/**") && !s.starts_with("/*!") {
David Tolnay14cbdeb2016-10-01 12:13:59 -070023 match block_comment(s) {
24 IResult::Done(_, com) => {
25 start += i + com.len();
26 chars = input[start..].char_indices();
27 continue;
28 }
29 IResult::Error => {
30 return IResult::Error;
31 }
32 }
33 }
34 }
35 if !ch.is_whitespace() {
36 return if start + i > 0 {
37 IResult::Done(s, ())
38 } else {
39 IResult::Error
40 };
41 }
42 }
43 IResult::Done("", ())
44}
45
46pub fn block_comment(input: &str) -> IResult<&str, &str> {
47 if !input.starts_with("/*") {
48 return IResult::Error;
49 }
50
51 let mut depth = 0;
52 let mut chars = input.char_indices();
53 while let Some((i, _)) = chars.next() {
54 let s = &input[i..];
55 if s.starts_with("/*") {
56 depth += 1;
57 chars.next(); // eat '*'
58 } else if s.starts_with("*/") {
59 depth -= 1;
60 if depth == 0 {
61 return IResult::Done(&input[i + 2..], &input[..i + 2]);
62 }
63 chars.next(); // eat '/'
64 }
65 }
66 IResult::Error
67}
68
69pub fn word_break(input: &str) -> IResult<&str, ()> {
70 match input.chars().next() {
David Tolnaydaaf7742016-10-03 11:11:43 -070071 Some(ch) if UnicodeXID::is_xid_continue(ch) => IResult::Error,
72 Some(_) | None => IResult::Done(input, ()),
David Tolnay14cbdeb2016-10-01 12:13:59 -070073 }
74}