doc-chunks 0.2.2

Clusters of doc comments and dev comments as coherent view.
Documentation
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
use std::fmt;
use std::fmt::{Display, Formatter};

use ra_ap_syntax::{ast, AstToken};

use regex::Regex;

use super::*;

/// Prefix string for a developer block comment
const BLOCK_COMMENT_PREFIX: &str = "/*";

/// Prefix string for a developer line comment
const LINE_COMMENT_PREFIX: &str = "//";

/// Prefix string for any other token type (i.e. we don't care)
const OTHER_PREFIX: &str = "";

/// Postfix string for a developer block comment
const BLOCK_COMMENT_POSTFIX: &str = "*/";

/// Postfix string for a developer line comment
const LINE_COMMENT_POSTFIX: &str = "";

/// Postfix string for any other token type (i.e. we don't care)
const OTHER_POSTFIX: &str = "";

lazy_static::lazy_static! {
  static ref BLOCK_COMMENT: Regex = Regex::new(r"^/\*(?s)(?P<content>.*)\*/$")
      .expect("Failed to create regular expression to identify (closed) developer block comments. \
          Please check this regex!");
  static ref LINE_COMMENT: Regex = Regex::new(r"^//([^[/|!]].*)?$")
      .expect("Failed to create regular expression to identify developer line comments. \
          Please check this regex!");
}

/// A string token from a source string with the location at which it occurs in
/// the source string as line on which it occurs (1 indexed) and the column of
/// its first character (0 indexed)
#[derive(Debug)]
struct TokenWithLineColumn {
    /// The full contents of this token, including pre/post characters (like
    /// '//')
    content: String,
    /// The first line on which the token appears in the source file (1 indexed)
    line: usize,
    /// The column where the first character of this token appears in the source
    /// file (0 indexed)
    column: usize,
}

/// Is a token of type (developer) block comment, (developer) line comment or
/// something else
#[derive(Debug, Eq, PartialEq)]
enum TokenType {
    BlockComment,
    LineComment,
    Other,
}

impl Display for TokenType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let kind = match self {
            TokenType::BlockComment => "developer block comment",
            TokenType::LineComment => "developer line comment",
            TokenType::Other => "not a developer comment",
        };
        write!(f, "{kind}")
    }
}

impl TokenType {
    /// The prefix string for this type of token
    fn pre(&self) -> &str {
        match self {
            TokenType::BlockComment => BLOCK_COMMENT_PREFIX,
            TokenType::LineComment => LINE_COMMENT_PREFIX,
            TokenType::Other => OTHER_PREFIX,
        }
    }
    /// The postfix string for this type of token
    fn post(&self) -> &str {
        match self {
            TokenType::BlockComment => BLOCK_COMMENT_POSTFIX,
            TokenType::LineComment => LINE_COMMENT_POSTFIX,
            TokenType::Other => OTHER_POSTFIX,
        }
    }
    /// The length of the prefix for the token in characters
    fn pre_in_chars(&self) -> usize {
        self.pre().chars().count()
    }
    /// The length of the postfix for the token in characters
    fn post_in_chars(&self) -> usize {
        self.post().chars().count()
    }
}

/// A token from a source string with its variant (`TokenType`) and the line and
/// column on which it occurs according to the description for
/// `TokenWithLineColumn`
#[derive(Debug)]
struct TokenWithType {
    /// Is the token a block developer comment, line developer comment or
    /// something else
    kind: TokenType,
    /// The full contents of this token, including pre/post characters (like
    /// '//')
    pub content: String,
    /// The first line on which the token appears in the source file (1 indexed)
    /// pub line: `usize`,
    pub line: usize,
    /// The column where the first character of this token appears in the source
    /// file (0 indexed)
    pub column: usize,
}

impl TokenWithType {
    /// Convert a `TokenWithLineColumn` to a `TokenWithType`. The kind is worked
    /// out from the content by checking against the developer block comment &
    /// line comment regexps.
    fn from(token: TokenWithLineColumn) -> Self {
        let kind = if BLOCK_COMMENT.is_match(&token.content) {
            TokenType::BlockComment
        } else if LINE_COMMENT.is_match(&token.content) {
            TokenType::LineComment
        } else {
            TokenType::Other
        };
        Self {
            kind,
            content: token.content,
            line: token.line,
            column: token.column,
        }
    }
}

/// A convenience method that runs the complete 'pipeline' from string `source`
/// file to all `LiteralSet`s that can be created from developer comments in the
/// source
pub fn extract_developer_comments(source: &str) -> Vec<LiteralSet> {
    let tokens = source_to_iter(source).collect::<Vec<_>>();

    construct_literal_sets(tokens)
}

/// Creates a series of `TokenWithType`s from a source string
fn source_to_iter(source: &str) -> impl Iterator<Item = TokenWithType> + '_ {
    // TODO: handle source
    let parse = ast::SourceFile::parse(source, ra_ap_syntax::Edition::Edition2021);
    let node = parse.syntax_node();
    node.descendants_with_tokens()
        .filter_map(|nort| {
            nort.into_token()
                .and_then(ast::Comment::cast)
                .filter(|comment| !comment.is_doc())
            // for now until it's clear whether #[doc=foo!()]
            // is possible with `ra_ap_syntax`
        })
        .map(move |comment| {
            let location = usize::from(comment.syntax().text_range().start());
            TokenWithType::from(TokenWithLineColumn {
                content: comment.text().to_owned(),
                line: count_lines(&source[..location]),
                column: calculate_column(&source[..location]),
            })
        })
}

/// Given a string, calculates the 1 indexed line number of the line on which
/// the final character of the string appears
fn count_lines(fragment: &str) -> usize {
    fragment.chars().filter(|c| *c == '\n').count() + 1
}

/// Given a string, calculates the 0 indexed column number of the character
/// *just after* the final character in the string
fn calculate_column(fragment: &str) -> usize {
    match fragment.rfind('\n') {
        Some(p) => fragment.chars().count() - fragment[..p].chars().count() - 1,
        None => fragment.chars().count(),
    }
}

/// Attempts to create a `LiteralSet` from a token assuming it is block comment.
/// Returns `None` if the token kind is not `TokenKind::BlockComment`, if the
/// token content does not match the block comment regex, or if any line cannot
/// be added by `LiteralSet::add_adjacent`
fn literal_set_from_block_comment(
    token: &TokenWithType,
) -> std::result::Result<LiteralSet, String> {
    let number_of_lines = token.content.split("\n").count();
    let mut lines = token.content.split("\n");
    if number_of_lines == 1 {
        let literal = match TrimmedLiteral::from(
        CommentVariant::SlashStar, &token.content, token.kind.pre_in_chars(),
        token.kind.post_in_chars(), token.line, token.column) {
      Err(s) => return Err(format!(
          "Failed to create literal from single line block comment, content \"{}\" - caused by \"{}\"",
          token.content, s)),
      Ok(l) => l
    };
        Ok(LiteralSet::from(literal))
    } else {
        let next_line = match lines.next() {
            None => {
                return Err(format!(
                    "BUG! Expected block comment \"{}\" to have at least two lines",
                    token.content
                ))
            }
            Some(l) => l,
        };
        let literal = match TrimmedLiteral::from(
            CommentVariant::SlashStar,
            next_line,
            token.kind.pre_in_chars(),
            0,
            token.line,
            token.column,
        ) {
            Err(s) => {
                return Err(format!(
                    "Failed to create literal from block comment with content \"{next_line}\" due to error \"{s}\"",
                ))
            }
            Ok(l) => l,
        };
        let mut literal_set = LiteralSet::from(literal);
        let mut line_number = token.line;
        for next_line in lines {
            line_number += 1;
            let post = if next_line.ends_with(BLOCK_COMMENT_POSTFIX) {
                TokenType::BlockComment.post_in_chars()
            } else {
                0
            };
            let literal = match TrimmedLiteral::from(
                CommentVariant::SlashStar,
                next_line,
                0,
                post,
                line_number,
                0,
            ) {
                Err(s) => {
                    return Err(format!(
                    "Failed to create literal from content \"{next_line}\" due to error \"{s}\"",
                ))
                }
                Ok(l) => l,
            };
            match literal_set.add_adjacent(literal) {
                Ok(_) => (),
                Err(_) => {
                    return Err(format!(
                        "Failed to add line with content {next_line} to literal set",
                    ))
                }
            }
        }
        Ok(literal_set)
    }
}

/// Attempt to create a literal from a developer line comment token. Returns
/// `None` if the token's kind is not `TokenType::LineComment` or if the call to
/// `TrimmedLiteral::from` fails.
fn literal_from_line_comment(token: &TokenWithType) -> std::result::Result<TrimmedLiteral, String> {
    match token.kind {
        TokenType::LineComment => TrimmedLiteral::from(
            CommentVariant::DoubleSlash,
            &token.content,
            token.kind.pre_in_chars(),
            token.kind.post_in_chars(),
            token.line,
            token.column,
        ),
        _ => Err(format!(
            "Expected a token of type {}, got {}",
            TokenType::LineComment,
            token.kind
        )),
    }
}

/// Converts a vector of tokens into a vector of `LiteralSet`s based on the
/// developer line comments in the input, ignoring all other tokens in the
/// input.
fn construct_literal_sets(tokens: impl IntoIterator<Item = TokenWithType>) -> Vec<LiteralSet> {
    let mut sets = vec![];
    'loopy: for token in tokens {
        let res = match token.kind {
            TokenType::LineComment => literal_from_line_comment(&token),
            TokenType::BlockComment => {
                if let Ok(set) = literal_set_from_block_comment(&token) {
                    sets.push(set)
                }
                continue 'loopy;
            }
            _ => continue 'loopy,
        };
        let literal = match res {
            Err(err) => {
                log::trace!(
                    "Failed to create literal from comment with content \"{}\" due to \"{}\"",
                    token.content,
                    err
                );
                continue 'loopy;
            }
            Ok(l) => l,
        };
        match sets.pop() {
            None => sets.push(LiteralSet::from(literal)),
            Some(mut s) => match s.add_adjacent(literal) {
                Err(literal) => {
                    sets.push(s);
                    sets.push(LiteralSet::from(literal))
                }
                Ok(_) => sets.push(s),
            },
        }
    }
    sets
}

#[cfg(test)]
mod tests {
    use super::*;
    use assert_matches::assert_matches;

    #[test]
    fn test_count_lines_correctly_counts_lines() {
        // Note: lines are 1 indexed
        assert_eq!(count_lines(""), 1);
        assert_eq!(count_lines("test"), 1);
        assert_eq!(count_lines("test\ntest"), 2);
        assert_eq!(count_lines("test\ntest\n something else \n"), 4);
        assert_eq!(count_lines("\n test\ntest\n something else \n"), 5);
    }

    #[test]
    fn test_calculate_column_correctly_calculates_final_column_of_last_line() {
        // Note: next column after last, in chars, zero indexed
        assert_eq!(calculate_column(""), 0);
        assert_eq!(calculate_column("test中"), 5);
        assert_eq!(calculate_column("test\n"), 0);
        assert_eq!(calculate_column("test\ntest2"), 5);
        assert_eq!(calculate_column("test\ntest中2"), 6);
        assert_eq!(calculate_column("test\ntest中2\n中3"), 2);
    }

    #[test]
    fn test_tokens_from_source_basic() {
        let source = "/* test */\n// test";
        let mut tokens = dbg!(Vec::from_iter(source_to_iter(source))).into_iter();
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 1,
                column: 0,
                ..
            })
        ); // Block comment
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 2,
                column: 0,
                ..
            })
        ); // Line comment
    }

    #[test]
    fn test_tokens_with_line_column_values_set_correctly_more_unicode() {
        let source = "/* te中st */\n// test";
        let mut tokens = source_to_iter(source);
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 1,
                column: 0,
                ..
            })
        ); // Block comment
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 2,
                column: 0,
                ..
            })
        ); // Line comment
    }

    #[test]
    fn test_tokens_with_line_column_values_set_correctly_another() {
        let source = "/* te中st */\n// test\nfn 中(){\t}";
        let mut tokens = source_to_iter(source);
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 1,
                column: 0,
                ..
            })
        ); // Block comment
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 2,
                column: 0,
                ..
            })
        ); // Block comment
    }

    #[test]
    fn test_tokens_retain_empty_lines_for_clustering() {
        let source = r###"// ```c
// space:
//
// end
// ```
"###;
        let mut tokens = source_to_iter(source);
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 1,
                column: 0,
                ..
            })
        );
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 2,
                column: 0,
                ..
            })
        );
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 3,
                column: 0,
                ..
            })
        );
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 4,
                column: 0,
                ..
            })
        );
        assert_matches!(
            tokens.next(),
            Some(TokenWithType {
                line: 5,
                column: 0,
                ..
            })
        );
    }

    #[test]
    fn test_identify_token_type_assigns_block_comment_type_to_block_comments() {
        let block_comments = vec![
            TokenWithLineColumn {
                content: "/* Block Comment */".to_string(),
                line: 0,
                column: 0,
            },
            TokenWithLineColumn {
                content: "/* Multiple Line\nBlock Comment */".to_string(),
                line: 0,
                column: 0,
            },
        ];
        for token in block_comments {
            assert_eq!(TokenWithType::from(token).kind, TokenType::BlockComment);
        }
    }

    #[test]
    fn test_identify_token_type_assigns_line_comment_type_to_line_comments() {
        let line_comments = vec![TokenWithLineColumn {
            content: "// Line Comment ".to_string(),
            line: 0,
            column: 0,
        }];
        for token in line_comments {
            assert_eq!(TokenWithType::from(token).kind, TokenType::LineComment);
        }
    }

    /// Convenience function to create a single `TokenWithLineColumn` with given
    /// string content at line 0 and column 0
    fn token_with_line_column_at_start(content: &str) -> TokenWithLineColumn {
        TokenWithLineColumn {
            content: content.to_string(),
            line: 0,
            column: 0,
        }
    }

    #[test]
    fn test_identify_token_type_assigns_other_type_to_non_developer_comments() {
        let not_developer_comments = vec![
            token_with_line_column_at_start("/// Outer documentation comment"),
            token_with_line_column_at_start("//! Inner documentation comment"),
        ];
        for token in not_developer_comments {
            assert_eq!(TokenWithType::from(token).kind, TokenType::Other);
        }
    }

    fn concatenate_with_line_breaks(includes: &[&str], excludes: &[&str]) -> String {
        let mut building = String::new();
        for piece in includes {
            building = building + piece + "\n";
        }
        for piece in excludes {
            building = building + piece + "\n"
        }
        building
    }

    #[test]
    fn retain_only_developer_comments_removes_non_comment_tokens() {
        let includes = vec!["/* A block comment */", "// A line comment"];
        let excludes = vec![
            "fn", "func中", "(", ")", "{", "1", "+", "2", ";", "}", "\n", " ",
        ];
        let source = concatenate_with_line_breaks(&includes, &excludes);
        let tokens = source_to_iter(&source);
        for token in tokens {
            for content in &excludes {
                assert_ne!(&token.content, content);
            }
        }
    }

    #[test]
    fn retain_only_developer_comments_removes_documentation_comment_tokens() {
        let includes = vec!["/* A block comment */", "// A line comment"];
        let excludes = vec![
            "//! An inner documentation comment",
            "/// An outer documentation comment",
        ];
        let source = concatenate_with_line_breaks(&includes, &excludes);
        let tokens = source_to_iter(&source);
        for token in tokens {
            for content in &excludes {
                assert_ne!(&token.content, content);
            }
        }
    }

    #[test]
    fn retain_only_developer_comments_keeps_developer_comment_tokens() {
        let includes = vec!["/* A block comment */", "// A line comment"];
        let excludes = vec![
            "fn", "func中", "(", ")", "{", "1", "+", "2", ";", "}", "\n", " ",
        ];
        let source = concatenate_with_line_breaks(&includes, &excludes);
        let tokens = source_to_iter(&source).collect::<Vec<_>>();
        for content in includes {
            let tokens = tokens
                .iter()
                .filter(|t| t.content == content)
                .collect::<Vec<_>>();
            assert!(!tokens.is_empty());
        }
    }

    #[test]
    fn test_block_comments_to_literal_sets_converter_keeps_block_comment_tokens() {
        let source = "/* block comment */\n/*\n * multi line block comment\n */\n";
        let tokens = source_to_iter(source);
        let literal_sets = construct_literal_sets(tokens);
        assert_eq!(literal_sets.len(), 2);
    }

    #[test]
    fn test_block_comments_to_literal_sets_converter_ignores_other_token_types() {
        let source = "/// line comment\n/// outer documentation\npub fn test() -> i32 \
        {\n  //! inner documentation\n  1 + 2\n}";
        let tokens = source_to_iter(source);
        let literal_sets = construct_literal_sets(tokens);
        assert_eq!(literal_sets.len(), 0);
    }

    #[test]
    fn test_single_line_block_comment_literal_correctly_created() {
        let source = "/* block 种 comment */";
        let tokens = source_to_iter(source).collect::<Vec<_>>();
        assert_eq!(tokens.len(), 1);
        let token = tokens.last().unwrap();
        let literal_set = literal_set_from_block_comment(token);
        assert!(literal_set.is_ok());
        let literal_set = literal_set.unwrap();
        assert_eq!(literal_set.len(), 1);
        let literal = literal_set.literals().into_iter().last().unwrap();
        assert_eq!(literal.pre(), TokenType::BlockComment.pre_in_chars());
        assert_eq!(literal.post(), TokenType::BlockComment.post_in_chars());
        assert_eq!(literal.len_in_chars(), source.chars().count() - 4);
        assert_eq!(literal.len(), source.len() - 4);
        let span = &literal.span();
        assert_eq!(span.start.line, 1);
        assert_eq!(span.start.column, 2);
        assert_eq!(span.end.line, 1);
        assert_eq!(span.end.column, source.chars().count() - 2 - 1);
    }

    #[test]
    fn test_single_line_indented_block_comment_literal_correctly_created() {
        let source = "    /* block 种 comment */";
        let tokens = source_to_iter(source).collect::<Vec<_>>();
        assert!(tokens.len() > 0);
        let token = tokens.last().unwrap();
        let literal_set = literal_set_from_block_comment(&token);
        assert!(literal_set.is_ok());
        let literal_set = literal_set.unwrap();
        assert_eq!(literal_set.len(), 1);
        let literal = literal_set.literals().into_iter().last().unwrap();
        let indent_size = "    ".len(); // Also chars, because ASCII
        assert_eq!(literal.pre(), TokenType::BlockComment.pre_in_chars());
        assert_eq!(literal.post(), TokenType::BlockComment.post_in_chars());
        assert_eq!(
            literal.len_in_chars(),
            source.chars().count() - indent_size - 4
        );
        assert_eq!(literal.len(), source.len() - indent_size - 4);
        let span = &literal.span();
        assert_eq!(span.start.line, 1);
        assert_eq!(span.start.column, indent_size + 2);
        assert_eq!(span.end.line, 1);
        assert_eq!(span.end.column, source.chars().count() - 2 - 1);
    }

    #[test]
    fn test_multi_line_block_comment_literal_correctly_created() {
        let source = "/* block\n\ncomment */";
        let tokens = source_to_iter(source).collect::<Vec<_>>();
        assert_eq!(tokens.len(), 1);
        let token = tokens.into_iter().last().unwrap();
        let literal_set = literal_set_from_block_comment(&token);
        assert!(literal_set.is_ok());
        let literal_set = literal_set.unwrap();
        assert_eq!(literal_set.len(), 3);
        let literals = literal_set.literals();
        {
            let literal = literals.get(0).unwrap();
            assert_eq!(literal.pre(), TokenType::BlockComment.pre_in_chars());
            assert_eq!(literal.post(), "".chars().count());
            assert_eq!(literal.len_in_chars(), " block".chars().count());
            assert_eq!(literal.len(), " block".len());
            let span = &literal.span();
            assert_eq!(span.start.line, 1);
            assert_eq!(span.start.column, 2);
            assert_eq!(span.end.line, 1);
            assert_eq!(span.end.column, "/* block".chars().count() - 1);
        }
        {
            let literal = literals.get(1).unwrap();
            assert_eq!(literal.pre(), "".chars().count());
            assert_eq!(literal.post(), "".chars().count());
            assert_eq!(literal.len_in_chars(), "".chars().count());
            assert_eq!(literal.len(), "".len());
            let span = &literal.span();
            assert_eq!(span.start.line, 2);
            assert_eq!(span.start.column, 0);
            assert_eq!(span.end.line, 2);
            assert_eq!(span.end.column, "".chars().count() - 1);
        }
        {
            let literal = literals.get(2).unwrap();
            assert_eq!(literal.pre(), "".chars().count());
            assert_eq!(literal.post(), TokenType::BlockComment.post_in_chars());
            assert_eq!(literal.len_in_chars(), "comment ".chars().count());
            assert_eq!(literal.len(), "comment ".len());
            let span = &literal.span();
            assert_eq!(span.start.line, 3);
            assert_eq!(span.start.column, 0);
            assert_eq!(span.end.line, 3);
            assert_eq!(span.end.column, "comment ".chars().count() - 1);
        }
    }

    #[test]
    fn outer_inner_mix() {
        let source = "// line comment\n/// Outer documentation\nfn test(){\n \
        //! Inner documentation\n\tlet i = 1 + 2;\n}";
        let tokens = source_to_iter(source);
        let sets = construct_literal_sets(tokens);
        // we only track dev comments
        assert_eq!(sets.len(), 1);
    }

    #[test]
    fn test_non_line_comment_tokens_line_comment_to_literal_does_not_create_literals() {
        let source = "/* Block comment */\nfn test(i: usize) {\n  let j = 1 + i;\n  j\n}";
        let tokens = source_to_iter(source);
        for token in tokens {
            assert!(literal_from_line_comment(&token).is_err());
        }
    }

    #[test]
    fn test_documentation_line_comment_tokens_line_comment_to_literal_does_not_create_literals() {
        let source = "/// Outer \nfn(){\n//! Inner \n}";
        let tokens = source_to_iter(source);
        for token in tokens {
            assert!(literal_from_line_comment(&token).is_err());
        }
    }

    #[test]
    fn test_developer_line_comment_tokens_line_comment_to_literal_create_literals_with_correct_data(
    ) {
        let source = "// First line comment\nconst ZERO: usize = 0; // A constant ";
        let filtered = source_to_iter(source).collect::<Vec<_>>();
        assert_eq!(filtered.len(), 2);
        let literals: Vec<std::result::Result<TrimmedLiteral, String>> = filtered
            .into_iter()
            .map(|t| literal_from_line_comment(&t))
            .collect();
        {
            let literal = literals.get(0).unwrap();
            assert!(literal.is_ok());
            let literal = literal.as_ref().unwrap();
            assert_eq!(literal.pre(), TokenType::LineComment.pre_in_chars());
            assert_eq!(literal.post(), TokenType::LineComment.post_in_chars());
            assert_eq!(
                literal.len_in_chars(),
                " First line comment".chars().count()
            );
            assert_eq!(literal.len(), " First line comment".len());
            let span = &literal.span();
            assert_eq!(span.start.line, 1);
            assert_eq!(span.start.column, 2);
            assert_eq!(span.end.line, 1);
            assert_eq!(
                span.end.column,
                2 + " First line comment".chars().count() - 1
            );
        }
        {
            let literal = literals.get(1).unwrap();
            assert!(literal.is_ok());
            let literal = literal.as_ref().unwrap();
            assert_eq!(literal.pre(), TokenType::LineComment.pre_in_chars());
            assert_eq!(literal.post(), TokenType::LineComment.post_in_chars());
            assert_eq!(literal.len_in_chars(), " A constant ".chars().count());
            assert_eq!(literal.len(), " A constant ".len());
            let span = &literal.span();
            assert_eq!(span.start.line, 2);
            assert_eq!(span.start.column, 25);
            assert_eq!(span.end.line, 2);
            assert_eq!(span.end.column, 25 + " A constant ".chars().count() - 1);
        }
    }

    #[test]
    fn test_single_line_comment_put_in_one_literal_set() {
        let content = " line comment";
        let source = format!("//{content}");
        let tokens = source_to_iter(&source);
        let literal_sets = construct_literal_sets(tokens);
        assert_eq!(literal_sets.len(), 1);
        let literal_set = literal_sets.get(0).unwrap();
        let all_literals = literal_set.literals();
        let literal = all_literals.get(0);
        assert!(literal.is_some());
        let literal = literal.unwrap();
        assert!(literal.as_str().contains(content));
    }

    #[test]
    fn test_adjacent_line_comments_put_in_same_literal_set() {
        let content_1 = " line comment 1 ";
        let content_2 = " line comment 2 ";
        let source = format!("//{content_1}\n//{content_2}");
        let tokens = source_to_iter(&source);
        let literal_sets = construct_literal_sets(tokens);
        assert_eq!(literal_sets.len(), 1);
        let literal_set = literal_sets.get(0).unwrap();
        let all_literals = literal_set.literals();
        assert_eq!(all_literals.len(), 2);
        {
            let literal = all_literals.get(0).unwrap();
            assert!(literal.as_str().contains(content_1));
        }
        {
            let literal = all_literals.get(1).unwrap();
            assert!(literal.as_str().contains(content_2));
        }
    }

    #[test]
    fn test_non_adjacent_line_comments_put_in_different_literal_sets() {
        let content_1 = " line comment 1 ";
        let content_2 = " line comment 2 ";
        let source = format!("//{content_1}\nfn(){{}}\n//{content_2}");
        let tokens = source_to_iter(&source);
        let literal_sets = construct_literal_sets(tokens);
        assert_eq!(literal_sets.len(), 2);
        {
            let literal_set = literal_sets.get(0).unwrap();
            let all_literals = literal_set.literals();
            assert_eq!(all_literals.len(), 1);
            let literal = all_literals.get(0).unwrap();
            assert!(literal.as_str().contains(content_1));
        }
        {
            let literal_set = literal_sets.get(1).unwrap();
            let all_literals = literal_set.literals();
            assert_eq!(all_literals.len(), 1);
            let literal = all_literals.get(0).unwrap();
            assert!(literal.as_str().contains(content_2));
        }
    }
}