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
use gramatika::{DebugLisp, Parse, ParseStreamer, Span, Spanned, SpannedError, Substr, Token as _};

use crate::{token::comment_start, ParseStream, Text, Token, TokenKind};

#[derive(DebugLisp)]
pub enum Comment {
	Line(LineComment),
	Block(BlockComment),
}

#[derive(DebugLisp)]
pub struct LineComment {
	pub start: Token,
	pub text: Text,
}

#[derive(DebugLisp)]
pub struct BlockComment {
	pub start: Token,
	pub children: Vec<BlockCommentChild>,
	pub end: Token,
}

#[derive(DebugLisp)]
pub enum BlockCommentChild {
	Text(Text),
	Comment(BlockComment),
}

impl Parse for Comment {
	type Stream = ParseStream;

	fn parse(input: &mut Self::Stream) -> gramatika::Result<Self> {
		use TokenKind::*;

		match input.peek() {
			Some(token) => match token.as_matchable() {
				(CommentStart, "//", _) => Ok(Comment::Line(input.parse()?)),
				(CommentStart, "/*", _) => Ok(Comment::Block(input.parse()?)),
				(_, _, span) => Err(SpannedError {
					message: "Expected `//` or `/*`".into(),
					source: input.source(),
					span: Some(span),
				}),
			},
			None => Err(SpannedError {
				message: "Unexpected end of input".into(),
				source: input.source(),
				span: input.prev().map(|token| token.span()),
			}),
		}
	}
}

impl Parse for LineComment {
	type Stream = ParseStream;

	fn parse(input: &mut Self::Stream) -> gramatika::Result<Self> {
		let start = input.consume(comment_start!["//"])?;
		let start_span = start.span();
		let text = match text_until(input, |peeked| {
			peeked.span().start.line > start_span.start.line
		}) {
			Some(text) => text,
			None => {
				let content = Substr::new();
				let span = Span {
					start: start_span.end,
					end: start_span.end,
				};
				Text(content, span)
			}
		};

		Ok(Self { start, text })
	}
}

impl Parse for BlockComment {
	type Stream = ParseStream;

	fn parse(input: &mut Self::Stream) -> gramatika::Result<Self> {
		let start = input.consume(comment_start!["/*"])?;
		let start_span = start.span();
		let mut children: Vec<BlockCommentChild> = vec![];
		loop {
			use TokenKind::*;
			match input.peek().map(|peeked| peeked.as_matchable()) {
				Some((CommentStart, "/*", _)) => {
					children.push(BlockCommentChild::Comment(input.parse()?));
				}
				Some((CommentEnd, "*/", _)) => {
					let end = input.next().unwrap();
					break Ok(Self {
						start,
						children,
						end,
					});
				}
				Some(_) => {
					let text = match text_until(input, |peeked| {
						matches!(
							peeked.as_matchable(),
							(CommentStart, "/*", _) | (CommentEnd, _, _)
						)
					}) {
						Some(text) => text,
						None => {
							let content = Substr::new();
							let span = Span {
								start: start_span.end,
								end: start_span.end,
							};
							Text(content, span)
						}
					};
					children.push(BlockCommentChild::Text(text));
				}
				None => {
					return Err(SpannedError {
						message: "Unexpected end of input".into(),
						source: input.source(),
						span: input.prev().map(|token| token.span()),
					});
				}
			}
		}
	}
}

impl Spanned for Comment {
	fn span(&self) -> Span {
		match self {
			Comment::Line(inner) => inner.span(),
			Comment::Block(inner) => inner.span(),
		}
	}
}

impl Spanned for BlockComment {
	fn span(&self) -> Span {
		self.start.span().through(self.end.span())
	}
}

impl Spanned for LineComment {
	fn span(&self) -> Span {
		self.start.span().through(self.text.span())
	}
}

fn text_until<F>(input: &mut ParseStream, end_condition: F) -> Option<Text>
where F: Fn(&Token) -> bool {
	let mut result: Option<Text> = None;
	loop {
		match input.peek() {
			Some(token) if !end_condition(token) => {
				let kind = token.kind();
				let token = input.consume_as(kind, Token::plain).unwrap();
				result = match result.take() {
					Some(text) => Some(text.concat(token)),
					None => Some(Text::from(token)),
				}
			}
			_ => {
				break result;
			}
		}
	}
}