1#[cfg(not(feature = "std"))]
18use alloc::{string::String, vec::Vec};
19
20use core::{
21 ops::{Bound, Deref, RangeBounds},
22 slice,
23};
24
25use crate::tokenizer::{Location, Span};
26
27#[derive(Default, Debug, Clone)]
29pub struct Comments(Vec<CommentWithSpan>);
30
31impl Comments {
32 pub fn offer(&mut self, comment: CommentWithSpan) {
37 if self
38 .0
39 .last()
40 .map(|last| last.span < comment.span)
41 .unwrap_or(true)
42 {
43 self.0.push(comment);
44 }
45 }
46
47 pub fn find<R: RangeBounds<Location>>(&self, range: R) -> Iter<'_> {
90 let (start, end) = (
91 self.start_index(range.start_bound()),
92 self.end_index(range.end_bound()),
93 );
94 debug_assert!((0..=self.0.len()).contains(&start));
95 debug_assert!((0..=self.0.len()).contains(&end));
96 Iter(if start <= end {
98 self.0[start..end].iter()
99 } else {
100 self.0[0..0].iter()
101 })
102 }
103
104 pub fn find_before(&self, location: Location) -> Iter<'_> {
121 let end = self.end_index(Bound::Excluded(&location));
122 let start = self.0[..end].partition_point(|c| c.next_token_start != Some(location));
123 Iter(self.0[start..end].iter())
124 }
125
126 pub(crate) fn set_next_token_start(&mut self, next_token_start: Location) {
127 for comment in self
128 .0
129 .iter_mut()
130 .rev()
131 .take_while(|c| c.next_token_start.is_none())
132 {
133 comment.next_token_start = Some(next_token_start);
134 }
135 }
136
137 fn start_index(&self, location: Bound<&Location>) -> usize {
141 match location {
142 Bound::Included(location) => {
143 match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
144 Ok(i) => i,
145 Err(i) => i,
146 }
147 }
148 Bound::Excluded(location) => {
149 match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
150 Ok(i) => i + 1,
151 Err(i) => i,
152 }
153 }
154 Bound::Unbounded => 0,
155 }
156 }
157
158 fn end_index(&self, location: Bound<&Location>) -> usize {
162 match location {
163 Bound::Included(location) => {
164 match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
165 Ok(i) => i + 1,
166 Err(i) => i,
167 }
168 }
169 Bound::Excluded(location) => {
170 match self.0.binary_search_by(|c| c.span.start.cmp(location)) {
171 Ok(i) => i,
172 Err(i) => i,
173 }
174 }
175 Bound::Unbounded => self.0.len(),
176 }
177 }
178}
179
180impl From<Comments> for Vec<CommentWithSpan> {
181 fn from(comments: Comments) -> Self {
182 comments.0
183 }
184}
185
186#[derive(Debug, Clone, PartialEq, Eq, Hash)]
188pub struct CommentWithSpan {
189 pub comment: Comment,
191 pub span: Span,
193 pub prev_token_end: Option<Location>,
195 pub next_token_start: Option<Location>,
197}
198
199impl Deref for CommentWithSpan {
200 type Target = Comment;
201
202 fn deref(&self) -> &Self::Target {
203 &self.comment
204 }
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, Hash)]
209pub enum Comment {
210 SingleLine {
219 content: String,
221 prefix: String,
223 },
224
225 MultiLine(String),
228}
229
230impl Comment {
231 pub fn as_str(&self) -> &str {
233 match self {
234 Comment::SingleLine { content, prefix: _ } => content.as_str(),
235 Comment::MultiLine(content) => content.as_str(),
236 }
237 }
238}
239
240impl Deref for Comment {
241 type Target = str;
242
243 fn deref(&self) -> &Self::Target {
244 self.as_str()
245 }
246}
247
248pub struct Iter<'a>(slice::Iter<'a, CommentWithSpan>);
250
251impl<'a> Iterator for Iter<'a> {
252 type Item = &'a CommentWithSpan;
253
254 fn next(&mut self) -> Option<Self::Item> {
255 self.0.next()
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262
263 #[test]
264 fn test_find() {
265 let comments = {
266 let mut c = Comments(Vec::new());
275 c.offer(CommentWithSpan {
276 comment: Comment::SingleLine {
277 content: " abc".into(),
278 prefix: "--".into(),
279 },
280 span: Span::new((1, 1).into(), (1, 7).into()),
281 prev_token_end: None,
282 next_token_start: None,
283 });
284 c.offer(CommentWithSpan {
285 comment: Comment::MultiLine(" hello ".into()),
286 span: Span::new((2, 3).into(), (2, 14).into()),
287 prev_token_end: None,
288 next_token_start: None,
289 });
290 c.offer(CommentWithSpan {
291 comment: Comment::SingleLine {
292 content: ", world".into(),
293 prefix: "--".into(),
294 },
295 span: Span::new((2, 14).into(), (2, 21).into()),
296 prev_token_end: None,
297 next_token_start: None,
298 });
299 c.offer(CommentWithSpan {
300 comment: Comment::MultiLine(" def\n ghi\n jkl\n".into()),
301 span: Span::new((3, 3).into(), (7, 1).into()),
302 prev_token_end: None,
303 next_token_start: None,
304 });
305 c
306 };
307
308 fn find<R: RangeBounds<Location>>(comments: &Comments, range: R) -> Vec<&str> {
309 comments.find(range).map(|c| c.as_str()).collect::<Vec<_>>()
310 }
311
312 assert_eq!(find(&comments, ..Location::new(0, 0)), Vec::<&str>::new());
314 assert_eq!(find(&comments, ..Location::new(2, 1)), vec![" abc"]);
315 assert_eq!(find(&comments, ..Location::new(2, 3)), vec![" abc"]);
316 assert_eq!(
317 find(&comments, ..=Location::new(2, 3)),
318 vec![" abc", " hello "]
319 );
320 assert_eq!(
321 find(&comments, ..=Location::new(2, 3)),
322 vec![" abc", " hello "]
323 );
324 assert_eq!(
325 find(&comments, ..Location::new(2, 15)),
326 vec![" abc", " hello ", ", world"]
327 );
328
329 assert_eq!(
331 find(&comments, Location::new(1000, 1000)..),
332 Vec::<&str>::new()
333 );
334 assert_eq!(
335 find(&comments, Location::new(2, 14)..),
336 vec![", world", " def\n ghi\n jkl\n"]
337 );
338 assert_eq!(
339 find(&comments, Location::new(2, 15)..),
340 vec![" def\n ghi\n jkl\n"]
341 );
342 assert_eq!(
343 find(&comments, Location::new(0, 0)..),
344 vec![" abc", " hello ", ", world", " def\n ghi\n jkl\n"]
345 );
346 assert_eq!(
347 find(&comments, Location::new(1, 1)..),
348 vec![" abc", " hello ", ", world", " def\n ghi\n jkl\n"]
349 );
350
351 assert_eq!(
353 find(&comments, Location::new(2, 1)..Location::new(1, 1)),
354 Vec::<&str>::new()
355 );
356 assert_eq!(
357 find(&comments, Location::new(1, 1)..Location::new(2, 3)),
358 vec![" abc"]
359 );
360 assert_eq!(
361 find(&comments, Location::new(1, 1)..=Location::new(2, 3)),
362 vec![" abc", " hello "]
363 );
364 assert_eq!(
365 find(&comments, Location::new(1, 1)..=Location::new(2, 10)),
366 vec![" abc", " hello "]
367 );
368 assert_eq!(
369 find(&comments, Location::new(1, 1)..=Location::new(2, 14)),
370 vec![" abc", " hello ", ", world"]
371 );
372 assert_eq!(
373 find(&comments, Location::new(1, 1)..Location::new(2, 15)),
374 vec![" abc", " hello ", ", world"]
375 );
376
377 assert_eq!(
379 find(&comments, ..),
380 vec![" abc", " hello ", ", world", " def\n ghi\n jkl\n"]
381 );
382 }
383
384 #[test]
385 fn test_find_before() {
386 let first_token = Location::new(2, 1);
387 let second_token = Location::new(4, 1);
388 let mut comments = Comments::default();
389 for comment in [
390 CommentWithSpan {
391 comment: Comment::SingleLine {
392 content: " first".into(),
393 prefix: "--".into(),
394 },
395 span: Span::new((1, 1).into(), (1, 9).into()),
396 prev_token_end: None,
397 next_token_start: Some(first_token),
398 },
399 CommentWithSpan {
400 comment: Comment::SingleLine {
401 content: " second".into(),
402 prefix: "--".into(),
403 },
404 span: Span::new((2, 11).into(), (2, 20).into()),
405 prev_token_end: Some(Location::new(2, 10)),
406 next_token_start: Some(second_token),
407 },
408 CommentWithSpan {
409 comment: Comment::SingleLine {
410 content: " third".into(),
411 prefix: "--".into(),
412 },
413 span: Span::new((3, 1).into(), (3, 9).into()),
414 prev_token_end: Some(Location::new(2, 10)),
415 next_token_start: Some(second_token),
416 },
417 CommentWithSpan {
418 comment: Comment::SingleLine {
419 content: " tail".into(),
420 prefix: "--".into(),
421 },
422 span: Span::new((4, 11).into(), (4, 18).into()),
423 prev_token_end: Some(Location::new(4, 10)),
424 next_token_start: None,
425 },
426 ] {
427 comments.offer(comment);
428 }
429
430 fn find_before(comments: &Comments, location: Location) -> Vec<&str> {
431 comments.find_before(location).map(|c| c.as_str()).collect()
432 }
433
434 assert_eq!(find_before(&comments, first_token), vec![" first"]);
435 assert_eq!(
436 find_before(&comments, second_token),
437 vec![" second", " third"]
438 );
439 for location in [
440 Location::new(0, 0),
441 Location::new(1, 3),
442 Location::new(2, 8),
443 Location::new(3, 12),
444 Location::new(4, 3),
445 Location::new(5, 1),
446 ] {
447 assert_eq!(
448 find_before(&comments, location),
449 Vec::<&str>::new(),
450 "{location:?}"
451 );
452 }
453 assert_eq!(
454 find_before(&Comments::default(), first_token),
455 Vec::<&str>::new()
456 );
457 }
458}