mago-docblock 1.22.0

Analyzes PHP docblocks to extract annotations, tags, and documentation comments, aiding tools that rely on inline documentation.
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
use bumpalo::Bump;

use mago_span::Span;
use mago_syntax::ast::Trivia;
use mago_syntax::ast::TriviaKind;

use crate::document::Document;
use crate::error::ParseError;

mod internal;

pub mod document;
pub mod error;
pub mod tag;

/// Parses a docblock from a trivia token.
///
/// # Errors
///
/// Returns a [`ParseError`] if the trivia is not a docblock comment or parsing fails.
#[inline]
pub fn parse_trivia<'arena>(arena: &'arena Bump, trivia: &Trivia<'arena>) -> Result<Document<'arena>, ParseError> {
    if TriviaKind::DocBlockComment != trivia.kind {
        return Err(ParseError::InvalidTrivia(trivia.span));
    }

    parse_phpdoc_with_span(arena, trivia.value, trivia.span)
}

/// Parses a `PHPDoc` comment string with an associated span.
///
/// # Errors
///
/// Returns a [`ParseError`] if tokenization or parsing fails.
#[inline]
pub fn parse_phpdoc_with_span<'arena>(
    arena: &'arena Bump,
    content: &'arena str,
    span: Span,
) -> Result<Document<'arena>, ParseError> {
    let tokens = internal::lexer::tokenize(content, span)?;

    internal::parser::parse_document(span, tokens.as_slice(), arena)
}

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

    use mago_database::file::FileId;
    use mago_span::Position;
    use mago_span::Span;

    use crate::document::*;

    #[test]
    fn test_parse_all_elements() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * This is a simple description.
            *
            * This text contains an inline code `echo "Hello, World!";`.
            *
            * This text contains an inline tag {@see \Some\Class}.
            *
            * ```php
            * echo "Hello, World!";
            * ```
            *
            *     $foo = "bar";
            *     echo "Hello, World!";
            *
            * @param string $foo
            * @param array{
            *   bar: string,
            *   baz: int
            * } $bar
            * @return void
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");
        assert_eq!(document.elements.len(), 12);

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        assert_eq!(text.segments.len(), 1);

        let TextSegment::Paragraph { span, content } = text.segments[0] else {
            panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
        };

        assert_eq!(content, "This is a simple description.");
        assert_eq!(&phpdoc[span.start.offset as usize..span.end.offset as usize], "This is a simple description.");

        let Element::Line(_) = &document.elements[1] else {
            panic!("Expected Element::Line, got {:?}", document.elements[1]);
        };

        let Element::Text(text) = &document.elements[2] else {
            panic!("Expected Element::Text, got {:?}", document.elements[2]);
        };

        assert_eq!(text.segments.len(), 3);

        let TextSegment::Paragraph { content, .. } = text.segments[0] else {
            panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
        };

        assert_eq!(content, "This text contains an inline code ");

        let TextSegment::InlineCode(code) = &text.segments[1] else {
            panic!("Expected TextSegment::InlineCode, got {:?}", text.segments[1]);
        };

        let content = code.content;
        assert_eq!(content, "echo \"Hello, World!\";");
        assert_eq!(
            &phpdoc[code.span.start.offset as usize..code.span.end.offset as usize],
            "`echo \"Hello, World!\";`"
        );

        let TextSegment::Paragraph { content, .. } = text.segments[2] else {
            panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[2]);
        };

        assert_eq!(content, ".");

        let Element::Line(_) = &document.elements[3] else {
            panic!("Expected Element::Line, got {:?}", document.elements[3]);
        };

        let Element::Text(text) = &document.elements[4] else {
            panic!("Expected Element::Text, got {:?}", document.elements[4]);
        };

        assert_eq!(text.segments.len(), 3);

        let TextSegment::Paragraph { content, .. } = text.segments[0] else {
            panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
        };

        assert_eq!(content, "This text contains an inline tag ");

        let TextSegment::InlineTag(tag) = &text.segments[1] else {
            panic!("Expected TextSegment::InlineTag, got {:?}", text.segments[1]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "see");
        assert_eq!(description, "\\Some\\Class");
        assert_eq!(tag.kind, TagKind::See);
        assert_eq!(&phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize], "{@see \\Some\\Class}");

        let TextSegment::Paragraph { content, .. } = text.segments[2] else {
            panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[2]);
        };

        assert_eq!(content, ".");

        let Element::Line(_) = &document.elements[5] else {
            panic!("Expected Element::Line, got {:?}", document.elements[5]);
        };

        let Element::Code(code) = &document.elements[6] else {
            panic!("Expected Element::CodeBlock, got {:?}", document.elements[6]);
        };

        let content = code.content;
        assert_eq!(code.directives, &["php"]);
        assert_eq!(content, "echo \"Hello, World!\";");
        assert_eq!(
            &phpdoc[code.span.start.offset as usize..code.span.end.offset as usize],
            "```php\n            * echo \"Hello, World!\";\n            * ```"
        );

        let Element::Line(_) = &document.elements[7] else {
            panic!("Expected Element::Line, got {:?}", document.elements[7]);
        };

        let Element::Code(code) = &document.elements[8] else {
            panic!("Expected Element::CodeBlock, got {:?}", document.elements[8]);
        };

        let content = code.content;
        assert!(code.directives.is_empty());
        assert_eq!(content, "$foo = \"bar\";\necho \"Hello, World!\";\n");
        assert_eq!(
            &phpdoc[code.span.start.offset as usize..code.span.end.offset as usize],
            "    $foo = \"bar\";\n            *     echo \"Hello, World!\";\n"
        );

        let Element::Tag(tag) = &document.elements[9] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[9]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "param");
        assert_eq!(tag.kind, TagKind::Param);
        assert_eq!(description, "string $foo");
        assert_eq!(&phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize], "@param string $foo");

        let Element::Tag(tag) = &document.elements[10] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[10]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "param");
        assert_eq!(tag.kind, TagKind::Param);
        assert_eq!(description, "array{\n  bar: string,\n  baz: int\n} $bar");
        assert_eq!(
            &phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize],
            "@param array{\n            *   bar: string,\n            *   baz: int\n            * } $bar"
        );

        let Element::Tag(tag) = &document.elements[11] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[11]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "return");
        assert_eq!(tag.kind, TagKind::Return);
        assert_eq!(description, "void");
        assert_eq!(&phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize], "@return void");
    }

    #[test]
    fn test_unclosed_inline_tag() {
        // Test case for ParseError::UnclosedInlineTag
        let arena = Bump::new();
        let phpdoc = "/** This is a doc block with an unclosed inline tag {@see Class */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Err(ParseError::UnclosedInlineTag(error_span)) => {
                let expected_start = phpdoc.find("{@see").unwrap();
                let expected_span = span.subspan(expected_start as u32, phpdoc.len() as u32 - 3);
                assert_eq!(error_span, expected_span);
            }
            _ => {
                panic!("Expected ParseError::UnclosedInlineTag");
            }
        }
    }

    #[test]
    fn test_unclosed_inline_code() {
        // Test case for ParseError::UnclosedInlineCode
        let arena = Bump::new();
        let phpdoc = "/** This is a doc block with unclosed inline code `code sample */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Err(ParseError::UnclosedInlineCode(error_span)) => {
                let expected_start = phpdoc.find('`').unwrap();
                let expected_span = span.subspan(expected_start as u32, phpdoc.len() as u32 - 3);
                assert_eq!(error_span, expected_span);
            }
            _ => {
                panic!("Expected ParseError::UnclosedInlineCode");
            }
        }
    }

    #[test]
    fn test_unclosed_code_block() {
        let arena = Bump::new();
        let phpdoc = r"/**
            * This is a doc block with unclosed code block
            * ```
            * Some code here
            */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Err(ParseError::UnclosedCodeBlock(error_span)) => {
                let code_block_start = phpdoc.find("```").unwrap();
                let expected_span = span.subspan(code_block_start as u32, 109);
                assert_eq!(error_span, expected_span);
            }
            _ => {
                panic!("Expected ParseError::UnclosedCodeBlock");
            }
        }
    }

    #[test]
    fn test_invalid_tag_name() {
        // Test case for ParseError::InvalidTagName — use a character not valid in identifiers
        let arena = Bump::new();
        let phpdoc = "/** @invalid!tag Description */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        assert!(
            matches!(result, Err(ParseError::InvalidTagName(_))),
            "Expected ParseError::InvalidTagName, got {result:?}"
        );
    }

    #[test]
    fn test_underscore_tag_name_is_valid() {
        let arena = Bump::new();
        let phpdoc = "/** @some_tag Description */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");
        let Element::Tag(tag) = &document.elements[0] else {
            panic!("Expected Element::Tag");
        };
        assert_eq!(tag.name, "some_tag");
    }

    #[test]
    fn test_malformed_code_block() {
        let arena = Bump::new();
        let phpdoc = r"/**
            * ```
            * Some code here
            * Incorrect closing
            */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Ok(document) => {
                panic!("Expected the parser to return an error, got {document:#?}");
            }
            Err(ParseError::UnclosedCodeBlock(error_span)) => {
                let code_block_start = phpdoc.find("```").unwrap();
                let expected_span = span.subspan(code_block_start as u32, 82);
                assert_eq!(error_span, expected_span);
            }
            _ => {
                panic!("Expected ParseError::UnclosedCodeBlock");
            }
        }
    }

    #[test]
    fn test_invalid_comment() {
        // Test case for ParseError::InvalidComment
        let arena = Bump::new();
        let phpdoc = "/* Not a valid doc block */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Err(ParseError::InvalidComment(error_span)) => {
                assert_eq!(error_span, span);
            }
            _ => {
                panic!("Expected ParseError::InvalidComment");
            }
        }
    }

    #[test]
    fn test_inconsistent_indentation() {
        // Test case for ParseError::InconsistentIndentation
        let arena = Bump::new();
        let phpdoc = r"/**
    * This is a doc block
      * With inconsistent indentation
    */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Ok(document) => {
                assert_eq!(document.elements.len(), 1);
                let Element::Text(text) = &document.elements[0] else {
                    panic!("Expected Element::Text, got {:?}", document.elements[0]);
                };

                assert_eq!(text.segments.len(), 1);
                let TextSegment::Paragraph { span, content } = &text.segments[0] else {
                    panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
                };

                assert_eq!(*content, "This is a doc block\nWith inconsistent indentation");
                assert_eq!(
                    &phpdoc[span.start.offset as usize..span.end.offset as usize],
                    "This is a doc block\n      * With inconsistent indentation"
                );
            }
            _ => {
                panic!("Expected ParseError::InconsistentIndentation");
            }
        }
    }

    #[test]
    fn test_missing_asterisk() {
        let arena = Bump::new();
        let phpdoc = r"/**
     This line is missing an asterisk
     * This line is fine
     */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Ok(document) => {
                assert_eq!(document.elements.len(), 1);
                let Element::Text(text) = &document.elements[0] else {
                    panic!("Expected Element::Text, got {:?}", document.elements[0]);
                };

                assert_eq!(text.segments.len(), 1);

                let TextSegment::Paragraph { span, content } = &text.segments[0] else {
                    panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
                };

                assert_eq!(*content, "This line is missing an asterisk\nThis line is fine");
                assert_eq!(
                    &phpdoc[span.start.offset as usize..span.end.offset as usize],
                    "This line is missing an asterisk\n     * This line is fine"
                );
            }
            _ => {
                panic!("Expected ParseError::MissingAsterisk");
            }
        }
    }

    #[test]
    fn test_missing_whitespace_after_asterisk() {
        let arena = Bump::new();
        let phpdoc = r"/**
     *This line is missing a space after asterisk
     */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Ok(document) => {
                assert_eq!(document.elements.len(), 1);
                let Element::Text(text) = &document.elements[0] else {
                    panic!("Expected Element::Text, got {:?}", document.elements[0]);
                };

                assert_eq!(text.segments.len(), 1);
                let TextSegment::Paragraph { span, content } = &text.segments[0] else {
                    panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
                };

                assert_eq!(*content, "This line is missing a space after asterisk");
                assert_eq!(
                    &phpdoc[span.start.offset as usize..span.end.offset as usize],
                    "This line is missing a space after asterisk"
                );
            }
            _ => {
                panic!("Expected ParseError::MissingWhitespaceAfterAsterisk");
            }
        }
    }

    #[test]
    fn test_missing_whitespace_after_opening_asterisk() {
        let arena = Bump::new();
        let phpdoc = "/**This is a doc block without space after /** */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Ok(document) => {
                assert_eq!(document.elements.len(), 1);
                let Element::Text(text) = &document.elements[0] else {
                    panic!("Expected Element::Text, got {:?}", document.elements[0]);
                };

                assert_eq!(text.segments.len(), 1);
                let TextSegment::Paragraph { span, content } = &text.segments[0] else {
                    panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
                };

                assert_eq!(*content, "This is a doc block without space after /**");
                assert_eq!(
                    &phpdoc[span.start.offset as usize..span.end.offset as usize],
                    "This is a doc block without space after /**"
                );
            }
            _ => {
                panic!("Expected ParseError::MissingWhitespaceAfterOpeningAsterisk");
            }
        }
    }

    #[test]
    fn test_missing_whitespace_before_closing_asterisk() {
        let arena = Bump::new();
        let phpdoc = "/** This is a doc block without space before */*/";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);

        match result {
            Ok(document) => {
                assert_eq!(document.elements.len(), 1);
                let Element::Text(text) = &document.elements[0] else {
                    panic!("Expected Element::Text, got {:?}", document.elements[0]);
                };

                assert_eq!(text.segments.len(), 1);
                let TextSegment::Paragraph { span, content } = &text.segments[0] else {
                    panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
                };

                assert_eq!(*content, "This is a doc block without space before */");
                assert_eq!(
                    &phpdoc[span.start.offset as usize..span.end.offset as usize],
                    "This is a doc block without space before */"
                );
            }
            _ => {
                panic!("Expected ParseError::MissingWhitespaceBeforeClosingAsterisk");
            }
        }
    }

    #[test]
    fn test_utf8_characters() {
        let arena = Bump::new();
        let phpdoc = r#"/**
    * هذا نص باللغة العربية.
    * 这是一段中文。
    * Here are some mathematical symbols: ∑, ∆, π, θ.
    *
    * ```php
    * // Arabic comment
    * echo "مرحبا بالعالم";
    * // Chinese comment
    * echo "你好,世界";
    * // Math symbols in code
    * $sum = $a + $b; // ∑
    * ```
    *
    * @param string $مثال A parameter with an Arabic variable name.
    * @return int 返回值是整数类型。
    */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        // Verify the number of elements parsed
        assert_eq!(document.elements.len(), 6);

        // First text element (Arabic text)
        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        assert_eq!(text.segments.len(), 1);

        let TextSegment::Paragraph { span, content } = &text.segments[0] else {
            panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
        };

        assert_eq!(*content, "هذا نص باللغة العربية.\n这是一段中文。\nHere are some mathematical symbols: ∑, ∆, π, θ.");

        assert_eq!(
            &phpdoc[span.start.offset as usize..span.end.offset as usize],
            "هذا نص باللغة العربية.\n    * 这是一段中文。\n    * Here are some mathematical symbols: ∑, ∆, π, θ."
        );

        // Empty line
        let Element::Line(_) = &document.elements[1] else {
            panic!("Expected Element::Line, got {:?}", document.elements[3]);
        };

        // Code block
        let Element::Code(code) = &document.elements[2] else {
            panic!("Expected Element::Code, got {:?}", document.elements[2]);
        };

        let content_str = code.content;
        let expected_code = "// Arabic comment\necho \"مرحبا بالعالم\";\n// Chinese comment\necho \"你好,世界\";\n// Math symbols in code\n$sum = $a + $b; // ∑";
        assert_eq!(content_str, expected_code);
        assert_eq!(
            &phpdoc[code.span.start.offset as usize..code.span.end.offset as usize],
            "```php\n    * // Arabic comment\n    * echo \"مرحبا بالعالم\";\n    * // Chinese comment\n    * echo \"你好,世界\";\n    * // Math symbols in code\n    * $sum = $a + $b; // ∑\n    * ```"
        );

        // Empty line
        let Element::Line(_) = &document.elements[3] else {
            panic!("Expected Element::Line, got {:?}", document.elements[3]);
        };

        // @param tag with Arabic variable name
        let Element::Tag(tag) = &document.elements[4] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[4]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "param");
        assert_eq!(tag.kind, TagKind::Param);
        assert_eq!(description, "string $مثال A parameter with an Arabic variable name.");
        assert_eq!(
            &phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize],
            "@param string $مثال A parameter with an Arabic variable name."
        );

        // @return tag with Chinese description
        let Element::Tag(tag) = &document.elements[5] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[5]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "return");
        assert_eq!(tag.kind, TagKind::Return);
        assert_eq!(description, "int 返回值是整数类型。");
        assert_eq!(
            &phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize],
            "@return int 返回值是整数类型。"
        );
    }

    #[test]
    fn test_annotation_parsing() {
        let arena = Bump::new();
        let phpdoc = r#"/**
         * @Event("Symfony\Component\Workflow\Event\CompletedEvent")
         * @AnotherAnnotation({
         *     "key": "value",
         *     "list": [1, 2, 3]
         * })
         * @SimpleAnnotation
         */"#;
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        let Element::Tag(tag) = &document.elements[0] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[0]);
        };

        assert_eq!(tag.name, "Event");
        assert_eq!(tag.metadata.unwrap(), "(\"Symfony\\Component\\Workflow\\Event\\CompletedEvent\")");

        let Element::Tag(tag) = &document.elements[1] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[1]);
        };
        assert_eq!(tag.name, "AnotherAnnotation");

        let last_idx = document.elements.len() - 1;
        let Element::Tag(tag) = &document.elements[last_idx] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[last_idx]);
        };
        assert_eq!(tag.name, "SimpleAnnotation");
        assert!(tag.metadata.is_none());
    }

    #[test]
    fn test_long_description_with_missing_asterisk() {
        let arena = Bump::new();
        let phpdoc = r"/** @var string[] this is a really long description
            that spans multiple lines, and demonstrates how the parser handles
            docblocks with multiple descriptions, and missing astricks*/";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        assert_eq!(document.elements.len(), 1);
        let Element::Tag(tag) = &document.elements[0] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[0]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "var");
        assert_eq!(tag.kind, TagKind::Var);
        assert_eq!(
            description,
            "string[] this is a really long description\nthat spans multiple lines, and demonstrates how the parser handles\ndocblocks with multiple descriptions, and missing astricks"
        );
        assert_eq!(
            &phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize],
            "@var string[] this is a really long description\n            that spans multiple lines, and demonstrates how the parser handles\n            docblocks with multiple descriptions, and missing astricks"
        );
    }

    #[test]
    fn test_code_indent_using_non_ascii_chars() {
        let arena = Bump::new();
        let phpdoc = r"/**
        *    └─ comment 2
        *       └─ comment 4
        *    └─ comment 3
        */";

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        assert_eq!(document.elements.len(), 1);

        let Element::Code(code) = &document.elements[0] else {
            panic!("Expected Element::Code, got {:?}", document.elements[0]);
        };

        let content_str = code.content;
        // After fix: correctly strips indent_len characters (not bytes) from each line
        assert_eq!(content_str, "└─ comment 2\n\u{a0}\u{a0} └─ comment 4\n└─ comment 3");
        assert_eq!(
            &phpdoc[code.span.start.offset as usize..code.span.end.offset as usize],
            " \u{a0} └─ comment 2\n        *    \u{a0}\u{a0} └─ comment 4\n        *  \u{a0} └─ comment 3"
        );
    }

    #[test]
    fn test_issue_456() {
        let arena = Bump::new();
        let phpdoc = "/**
             * \u{3000}(イベント日数をもとに計算)\u{3000}
             * @return\u{3000}int
             * @throws\u{3000}Exception
             */";

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        assert_eq!(document.elements.len(), 3);

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        assert_eq!(text.segments.len(), 1);
        let TextSegment::Paragraph { span, content } = &text.segments[0] else {
            panic!("Expected TextSegment::Paragraph, got {:?}", text.segments[0]);
        };

        assert_eq!(*content, " (イベント日数をもとに計算)");
        assert_eq!(&phpdoc[span.start.offset as usize..span.end.offset as usize], "\u{3000}(イベント日数をもとに計算)");

        let Element::Tag(tag) = &document.elements[1] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[1]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "return");
        assert_eq!(tag.kind, TagKind::Return);
        assert_eq!(description, "int");
        assert_eq!(&phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize], "@return\u{3000}int");

        let Element::Tag(tag) = &document.elements[2] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[2]);
        };

        let name = tag.name;
        let description = tag.description;
        assert_eq!(name, "throws");
        assert_eq!(tag.kind, TagKind::Throws);
        assert_eq!(description, "Exception");
        assert_eq!(&phpdoc[tag.span.start.offset as usize..tag.span.end.offset as usize], "@throws\u{3000}Exception");
    }

    #[test]
    fn test_issue_808() {
        let arena = Bump::new();

        let phpdoc = "/** @param\u{3000}string $foo 中文描述 */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        assert_eq!(document.elements.len(), 1);
        let Element::Tag(tag) = &document.elements[0] else {
            panic!("Expected Element::Tag, got {:?}", document.elements[0]);
        };
        assert_eq!(tag.name, "param");
        assert_eq!(tag.description, "string $foo 中文描述");

        let phpdoc2 = "/** @return\u{3000}int 返回🎉值 */";
        let span2 = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc2.len() as u32));
        let document2 = parse_phpdoc_with_span(&arena, phpdoc2, span2).expect("Failed to parse PHPDoc");

        assert_eq!(document2.elements.len(), 1);
        let Element::Tag(tag2) = &document2.elements[0] else {
            panic!("Expected Element::Tag, got {:?}", document2.elements[0]);
        };
        assert_eq!(tag2.name, "return");
        assert_eq!(tag2.description, "int 返回🎉值");

        let phpdoc3 = "/** @see\u{3000}中文类::方法() 说明 */";
        let span3 = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc3.len() as u32));
        let document3 = parse_phpdoc_with_span(&arena, phpdoc3, span3).expect("Failed to parse PHPDoc");

        assert_eq!(document3.elements.len(), 1);
        let Element::Tag(tag3) = &document3.elements[0] else {
            panic!("Expected Element::Tag, got {:?}", document3.elements[0]);
        };
        assert_eq!(tag3.name, "see");
        assert_eq!(tag3.description, "中文类::方法() 说明");
    }

    #[test]
    fn test_indented_code_with_fullwidth_space_in_indent() {
        // Test case for multi-byte whitespace in indented code (Issue #967)
        // parse_indented_code is only called when line starts with ASCII space/tab
        // The bug occurs when indent contains full-width space after ASCII spaces
        //
        // After lexer processing, content becomes "  \u{3000}code"
        // is_indented_line returns true (starts with ASCII space)
        // indent_len = 3 (2 ASCII spaces + 1 full-width space char)
        // But byte offset should be 2 + 3 = 5
        let arena = Bump::new();
        // Format: " * " (asterisk + space) + "  " (2 ASCII spaces) + "\u{3000}" (full-width) + "code"
        let phpdoc = "/**\n *   \u{3000}code\n */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);
        assert!(result.is_ok(), "Parsing should succeed without panic");

        let document = result.unwrap();
        assert_eq!(document.elements.len(), 1);
        let Element::Code(code) = &document.elements[0] else {
            panic!("Expected Element::Code, got {:?}", document.elements[0]);
        };
        assert_eq!(code.content, "code");
    }

    #[test]
    fn test_indented_code_with_mixed_multibyte_whitespace() {
        // Multiple lines with mixed ASCII and full-width whitespace
        let arena = Bump::new();
        let phpdoc = "/**\n *  \u{3000}first line\n *  \u{3000}second line\n */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);
        assert!(result.is_ok(), "Parsing should succeed without panic");

        let document = result.unwrap();
        assert_eq!(document.elements.len(), 1);
        let Element::Code(code) = &document.elements[0] else {
            panic!("Expected Element::Code, got {:?}", document.elements[0]);
        };
        assert_eq!(code.content, "first line\nsecond line");
    }

    #[test]
    fn test_indented_code_with_tab_and_fullwidth_space() {
        // Tab + full-width space: is_indented_line checks for '\t' as well
        let arena = Bump::new();
        // After "* " there is a tab followed by full-width space
        let phpdoc = "/**\n * \t\u{3000}code\n */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);
        assert!(result.is_ok(), "Parsing should succeed without panic");

        let document = result.unwrap();
        assert_eq!(document.elements.len(), 1);
        let Element::Code(code) = &document.elements[0] else {
            panic!("Expected Element::Code, got {:?}", document.elements[0]);
        };
        assert_eq!(code.content, "code");
    }

    #[test]
    fn test_issue_967_original_pattern() {
        // Original Issue #967 reproduction case
        // Error: byte index 3 is not a char boundary; it is inside '\u{3000}' (bytes 1..4) of `   メールクリックがない`
        // After lexer processing: " " + "\u{3000}" + " " + Japanese text
        // This triggers parse_indented_code because line starts with ASCII space
        let arena = Bump::new();
        // Format: " * " + " " (1 ASCII space) + "\u{3000}" (full-width) + " " (1 ASCII space) + text
        let phpdoc = "/**\n *  \u{3000} メールクリックがない\n */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));

        let result = parse_phpdoc_with_span(&arena, phpdoc, span);
        assert!(result.is_ok(), "Parsing should succeed without panic");

        let document = result.unwrap();
        assert_eq!(document.elements.len(), 1);
        let Element::Code(code) = &document.elements[0] else {
            panic!("Expected Element::Code, got {:?}", document.elements[0]);
        };
        assert_eq!(code.content, "メールクリックがない");
    }

    #[test]
    fn test_multiline_inline_tag() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * This method gets a count of the Foo.
            * {@internal Developers should note that it silently
            *            adds one extra Foo.}
            *
            * @return int
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        assert!(text.segments.len() >= 2, "Expected at least 2 segments, got {:?}", text.segments);

        let has_inline_tag =
            text.segments.iter().any(|seg| matches!(seg, TextSegment::InlineTag(tag) if tag.name == "internal"));

        assert!(has_inline_tag, "Expected an InlineTag with name 'internal', got segments: {:?}", text.segments);
    }

    #[test]
    fn test_multiline_inline_tag_with_nested() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * {@internal Developers should note that it silently
            *            adds one extra Foo (see {@link http://example.com}).}
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        let has_internal_tag =
            text.segments.iter().any(|seg| matches!(seg, TextSegment::InlineTag(tag) if tag.name == "internal"));

        assert!(has_internal_tag, "Expected an InlineTag with name 'internal', got segments: {:?}", text.segments);
    }

    #[test]
    fn test_single_line_inline_tag_still_works() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * See {@see \Some\Class} for details.
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse PHPDoc");

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        let has_see_tag =
            text.segments.iter().any(|seg| matches!(seg, TextSegment::InlineTag(tag) if tag.name == "see"));

        assert!(has_see_tag, "Expected an InlineTag with name 'see', got segments: {:?}", text.segments);
    }

    #[test]
    fn test_multiline_inline_tag_chinese() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * 获取用户数量的方法。
            * {@internal 开发者请注意,此方法会静默地
            *            添加一个额外的用户。}
            *
            * @return int
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse Chinese PHPDoc");

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        let has_internal =
            text.segments.iter().any(|seg| matches!(seg, TextSegment::InlineTag(tag) if tag.name == "internal"));
        assert!(has_internal, "Expected InlineTag 'internal' with Chinese content, got: {:?}", text.segments);
    }

    #[test]
    fn test_multiline_inline_tag_japanese() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * ユーザー数を取得するメソッド。
            * {@see \App\Service\UserCounter このクラスは
            *       ユーザーの数を数えます。}
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse Japanese PHPDoc");

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        let has_see = text.segments.iter().any(|seg| matches!(seg, TextSegment::InlineTag(tag) if tag.name == "see"));
        assert!(has_see, "Expected InlineTag 'see' with Japanese content, got: {:?}", text.segments);
    }

    #[test]
    fn test_multiline_inline_tag_arabic() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * طريقة للحصول على عدد المستخدمين.
            * {@internal يجب على المطورين ملاحظة أن هذه الطريقة
            *            تضيف مستخدمًا إضافيًا بصمت.}
            *
            * @return int
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse Arabic PHPDoc");

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        let has_internal =
            text.segments.iter().any(|seg| matches!(seg, TextSegment::InlineTag(tag) if tag.name == "internal"));
        assert!(has_internal, "Expected InlineTag 'internal' with Arabic content, got: {:?}", text.segments);
    }

    #[test]
    fn test_multiline_inline_tag_mixed_scripts() {
        let arena = Bump::new();
        let phpdoc = r#"/**
            * Documentation with mixed scripts.
            * {@internal 注意: This method は静かに adds один
            *            дополнительный элемент 요소를 추가합니다.}
            */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(phpdoc.len() as u32));
        let document = parse_phpdoc_with_span(&arena, phpdoc, span).expect("Failed to parse mixed-script PHPDoc");

        let Element::Text(text) = &document.elements[0] else {
            panic!("Expected Element::Text, got {:?}", document.elements[0]);
        };

        let has_internal =
            text.segments.iter().any(|seg| matches!(seg, TextSegment::InlineTag(tag) if tag.name == "internal"));
        assert!(has_internal, "Expected InlineTag 'internal' with mixed-script content, got: {:?}", text.segments);
    }
}