mago-docblock 1.27.1

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
use mago_span::Span;

use crate::error::ParseError;
use crate::internal::token::Token;

#[inline]
pub fn tokenize<'src>(comment: &'src str, span: Span) -> Result<Vec<Token<'src>>, ParseError> {
    if comment.len() < 5 || !comment.starts_with("/**") || !comment.ends_with("*/") {
        return Err(ParseError::InvalidComment(span));
    }

    let mut content_start = 3u32;
    let mut content_end = (comment.len() - 2) as u32;

    let content = &comment[3..(comment.len() - 2)];

    if content.contains('\n') {
        let lines_with_positions: Vec<(&'src str, u32)> = content
            .split('\n')
            .map(|line| {
                let cleaned_line = line.strip_suffix('\r').unwrap_or(line);

                let start_offset = (cleaned_line.as_ptr() as usize - content.as_ptr() as usize) as u32;

                (cleaned_line, start_offset)
            })
            .collect();

        let mut comment_lines = Vec::new();
        for (line, line_start_in_content) in lines_with_positions {
            let trimmed_line = line.trim_end();

            if trimmed_line.trim().is_empty() {
                continue;
            }

            let line_indent_length = trimmed_line.find(|c: char| !c.is_whitespace()).unwrap_or(trimmed_line.len());
            let line_content_after_indent = &trimmed_line[line_indent_length..];

            let mut content_start_in_line = line_indent_length as u32;
            let line_after_asterisk = if let Some(line_after_asterisk) = line_content_after_indent.strip_prefix('*') {
                content_start_in_line += 1;
                line_after_asterisk
            } else {
                line_content_after_indent
            };

            if let Some(first_char) = line_after_asterisk.chars().next() {
                if first_char.is_whitespace() {
                    content_start_in_line += first_char.len_utf8() as u32;
                }

                let content_end_in_line = trimmed_line.len() as u32;

                let content_start_in_comment = content_start + line_start_in_content + content_start_in_line;
                let content_end_in_comment = content_start + line_start_in_content + content_end_in_line;

                let content_str = &comment[content_start_in_comment as usize..content_end_in_comment as usize];
                let content_span = span.subspan(content_start_in_comment, content_end_in_comment);

                comment_lines.push(Token::Line { content: content_str, span: content_span });
            } else {
                comment_lines.push(Token::EmptyLine {
                    span: span.subspan(content_start + line_start_in_content, content_start + line_start_in_content),
                });
            }
        }

        Ok(comment_lines)
    } else {
        if content.is_empty() {
            return Ok(Vec::new());
        }

        let content = if let Some(content) = content.strip_prefix(' ') {
            content_start += 1; // Adjust start position to skip leading space
            content
        } else {
            content
        };

        let content = if let Some(content) = content.strip_suffix(' ') {
            content_end -= 1; // Adjust end position to skip trailing space
            content
        } else {
            content
        };

        if content.is_empty() {
            return Ok(Vec::new());
        }

        Ok(vec![Token::Line { content, span: span.subspan(content_start, content_end) }])
    }
}

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

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

    #[test]
    fn test_lex_empty_single_line_comment() {
        let comment = "/***/";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 0);
            }
            Err(e) => {
                panic!("Error parsing comment: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_empty_multiline_line_comment() {
        let comment = "/**\n*/";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 0);
            }
            Err(e) => {
                panic!("Error parsing comment: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_single_line_comment() {
        let comment = "/** This is a single-line comment */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 1);

                let Token::Line { content, span } = &tokens[0] else {
                    panic!("Expected a line, but got something else");
                };

                assert_eq!(*content, "This is a single-line comment");
                assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
            }
            Err(e) => {
                panic!("Error parsing comment: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_single_line_comment_missing_whitespace_front() {
        let comment = "/**This is a single-line comment */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 1);

                let Token::Line { content, span } = &tokens[0] else {
                    panic!("Expected a line, but got something else");
                };

                assert_eq!(*content, "This is a single-line comment");
                assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
            }
            Err(e) => {
                panic!("Error parsing comment: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_single_line_comment_missing_whitespace_back() {
        let comment = "/** This is a single-line comment*/";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 1);

                let Token::Line { content, span } = &tokens[0] else {
                    panic!("Expected a line, but got something else");
                };

                assert_eq!(*content, "This is a single-line comment");
                assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
            }
            Err(e) => {
                panic!("Error parsing comment: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_multi_line_comment() {
        let comment = "/**
                * This is a multi-line comment.
                * It has multiple lines.
                * Each line starts with an asterisk.
                */";

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 3);

                let expected_contents =
                    ["This is a multi-line comment.", "It has multiple lines.", "Each line starts with an asterisk."];

                for (i, line) in tokens.iter().enumerate() {
                    let Token::Line { content, span } = line else {
                        panic!("Expected a line, but got something else");
                    };

                    assert_eq!(*content, expected_contents[i]);
                    assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
                }
            }
            Err(e) => {
                panic!("Error parsing comment: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_multi_line_comment_indent() {
        let comment = r#"/**
                * This is a multi-line comment.
                * It has multiple lines.
                * Each line starts with an asterisk.
                *
                *     $foo = "bar";
                *     $bar = "baz";
                */"#;

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 6);

                let expected_contents = [
                    "This is a multi-line comment.",
                    "It has multiple lines.",
                    "Each line starts with an asterisk.",
                    "",
                    "    $foo = \"bar\";",
                    "    $bar = \"baz\";",
                ];

                for (i, line) in tokens.iter().enumerate() {
                    let expected_content = expected_contents[i];
                    if expected_content.is_empty() {
                        match line {
                            Token::EmptyLine { span } => {
                                assert_eq!(&comment[span.start.offset as usize..span.end.offset as usize], "");
                            }
                            _ => {
                                panic!("Expected an empty line, but got something else");
                            }
                        }
                    } else {
                        let Token::Line { content, span } = line else {
                            panic!("Expected a line, but got something else");
                        };

                        assert_eq!(*content, expected_content);
                        assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
                    }
                }
            }
            Err(e) => {
                panic!("Error parsing comment: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_multi_line_comment_inconsistent_indentation() {
        let comment = "/**
        * This is a multi-line comment.
            * It has multiple lines.
        * Each line starts with an asterisk.
        */";

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 3);

                let expected_contents =
                    ["This is a multi-line comment.", "It has multiple lines.", "Each line starts with an asterisk."];

                for (i, line) in tokens.iter().enumerate() {
                    let Token::Line { content, span } = line else {
                        panic!("Expected a line, but got something else");
                    };

                    assert_eq!(*content, expected_contents[i]);
                    assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
                }
            }
            Err(e) => {
                panic!("Unexpected error: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_multi_line_comment_missing_asterisk() {
        let comment = "/**
        * This is a multi-line comment.
        It has multiple lines.
        * Each line starts with an asterisk.
        */";

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 3);

                let expected_contents =
                    ["This is a multi-line comment.", "It has multiple lines.", "Each line starts with an asterisk."];

                for (i, line) in tokens.iter().enumerate() {
                    let Token::Line { content, span } = line else {
                        panic!("Expected a line, but got something else");
                    };

                    assert_eq!(*content, expected_contents[i]);
                    assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
                }
            }
            Err(e) => {
                panic!("Unexpected error: {e:?}");
            }
        }
    }

    #[test]
    fn test_lex_multi_line_comment_missing_whitespace_after_asterisk() {
        let comment = "/**
        * This is a multi-line comment.
        *It has multiple lines.
        * Each line starts with an asterisk.
        */";

        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 3);

                let expected_contents =
                    ["This is a multi-line comment.", "It has multiple lines.", "Each line starts with an asterisk."];

                for (i, line) in tokens.iter().enumerate() {
                    let Token::Line { content, span } = line else {
                        panic!("Expected a line, but got something else");
                    };

                    assert_eq!(*content, expected_contents[i]);
                    assert!(comment[span.start.offset as usize..span.end.offset as usize].eq(*content));
                }
            }
            Err(e) => {
                panic!("Unexpected error: {e:?}");
            }
        }
    }

    /// ref: <https://github.com/carthage-software/mago/issues/345>
    #[test]
    fn test_lex_multi_line_comment_crlf_with_multibyte_char() {
        let comment = "/**\r\n * blah blah ‰©\r\n */";
        let span = Span::new(FileId::zero(), Position::new(0), Position::new(comment.len() as u32));

        match tokenize(comment, span) {
            Ok(tokens) => {
                assert_eq!(tokens.len(), 1, "Should have parsed exactly one line of content");

                let Token::Line { content, span: token_span } = &tokens[0] else {
                    panic!("Expected a Token::Line");
                };

                let expected_content = "blah blah ‰©";
                assert_eq!(*content, expected_content);

                let sliced = &comment[token_span.start.offset as usize..token_span.end.offset as usize];
                assert_eq!(sliced, expected_content);
            }
            Err(e) => {
                panic!("Failed to tokenize comment with CRLF endings: {e:?}");
            }
        }
    }
}