oxc_jsdoc 0.124.0

A collection of JavaScript tools written in Rust.
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
use oxc_span::Span;

/// Represents the raw text of a JSDoc tag *outside* the type expression (`{}`) and tag name (e.g., `@param`),
/// such as the parameter name or trailing description.
///
/// This is used to capture parts of a JSDoc tag that aren't types but still carry semantic meaning,
/// for example, the name `bar` or the description text in `@param {foo=} bar Some description`.
///
/// ```js
/// /**
///  * @param {foo=} bar Some description
///  *               ^^^^^^^^^^^^^^^^^^^^
///  *               This is the `JSDocCommentPart`
///  */
/// ```
///
/// Used to populate the `.comment` field on `JSDoc` and `JSDocTag` nodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JSDocCommentPart<'a> {
    /// The raw string content, such as a parameter name or freeform description text.
    raw: &'a str,

    /// The span in the source text corresponding to this part.
    pub span: Span,
}

impl<'a> JSDocCommentPart<'a> {
    pub fn new(part_content: &'a str, span: Span) -> Self {
        Self { raw: part_content, span }
    }

    // For example, `Span` for the following comment part:
    // ```
    // /**
    //  * @kind1 COMMENT
    //  * WILL BE ...
    //  * @kind2 C2
    //  * @kind3
    //  */
    // ```
    // is ` COMMENT\n * WILL BE ...\n * `.
    //
    // It includes whitespace and line breaks.
    // And it also includes leading `*` prefixes in every line, even in a single line tag.
    // (comment `Span` for `kind2` is ` C2\n * `)
    //
    // Since these are trimmed by `parsed()` output, this raw `Span` may not be suitable for linter diagnostics.
    //
    // And if the passed `Span` for miette diagnostics is multiline,
    // it will just render arrow markers which is not intuitive.
    // (It renders a nice underline for single line span, but not for multiline)
    // ```
    // ╭─▶ * @kind1 COMMENT
    // │   * WILL BE ...
    // ╰─▶ * @kind2 C2
    // ```
    //
    // So instead, just indicate the first visible line of the comment part.
    // ```
    //     * @kind1 COMMENT
    //              ───────
    //     * WILL BE ...
    //     * @kind2 C2
    // ```
    // It may not be perfect for multiline, but for single line, which is probably the majority, it is enough.
    pub fn span_trimmed_first_line(&self) -> Span {
        if self.raw.trim().is_empty() {
            return Span::empty(self.span.start);
        }

        let base_len = self.raw.len();
        if self.raw.lines().count() == 1 {
            let trimmed_start_offset = base_len - self.raw.trim_start().len();
            let trimmed_end_offset = base_len - self.raw.trim_end().len();

            return Span::new(
                self.span.start + u32::try_from(trimmed_start_offset).unwrap_or_default(),
                self.span.end - u32::try_from(trimmed_end_offset).unwrap_or_default(),
            );
        }

        let start_trimmed = self.raw.trim_start();
        let trimmed_start_offset = base_len - start_trimmed.len();
        let trimmed_end_offset = trimmed_start_offset + start_trimmed.find('\n').unwrap_or(0);
        Span::new(
            self.span.start + u32::try_from(trimmed_start_offset).unwrap_or_default(),
            self.span.start + u32::try_from(trimmed_end_offset).unwrap_or_default(),
        )
    }

    /// Returns the content of the comment part without leading `*` prefix in each line,
    /// but preserves empty lines (paragraph structure) and indentation beyond the `* ` prefix.
    ///
    /// Unlike `parsed()` which filters out empty lines, this method keeps them
    /// to preserve paragraph breaks, vertical structure, and indentation in the original text.
    /// This is important for preserving indented code blocks (4+ spaces) and other structured content.
    pub fn parsed_preserving_whitespace(&self) -> String {
        if !self.raw.contains('\n') {
            return self.raw.trim().to_string();
        }

        let mut result = String::with_capacity(self.raw.len());
        for (i, line) in self.raw.lines().enumerate() {
            if i > 0 {
                result.push('\n');
            }
            let trimmed = line.trim();
            if let Some(rest) = trimmed.strip_prefix('*') {
                // Strip `*` as a comment continuation prefix UNLESS it looks like
                // markdown emphasis (`*word*`). Emphasis has `*` followed by an
                // alphanumeric char; continuation prefixes have `*` followed by
                // space, backtick, punctuation, or nothing.
                let is_emphasis = rest.starts_with(|c: char| c.is_alphanumeric() || c == '_');
                if !is_emphasis {
                    // Strip at most one leading space after `*` (the conventional ` * ` prefix)
                    // to preserve any additional indentation (e.g. for indented code blocks)
                    result.push_str(rest.strip_prefix(' ').unwrap_or(rest));
                    continue;
                }
            }
            result.push_str(trimmed);
        }
        result
    }

    /// Returns the content of the comment part without leading `*` in each line.
    pub fn parsed(&self) -> String {
        // If single line, there is no leading `*`
        if !self.raw.contains('\n') {
            return self.raw.trim().to_string();
        }

        let mut result = String::with_capacity(self.raw.len());
        for line in self.raw.lines() {
            // Trim leading `*` only when it's a continuation prefix (`* text` or `*` alone),
            // not when it's a markdown emphasis marker (`*word*`)
            let trimmed = line.trim();
            if let Some(rest) = trimmed.strip_prefix('*') {
                let is_emphasis = rest.starts_with(|c: char| c.is_alphanumeric() || c == '_');
                if !is_emphasis {
                    let content = rest.trim();
                    if content.is_empty() {
                        continue;
                    }
                    if !result.is_empty() {
                        result.push('\n');
                    }
                    result.push_str(content);
                    continue;
                }
            }
            if trimmed.is_empty() {
                continue;
            }
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str(trimmed);
        }
        result
    }
}

#[derive(Debug, Clone, Copy)]
pub struct JSDocTagKindPart<'a> {
    raw: &'a str,
    pub span: Span,
}
impl<'a> JSDocTagKindPart<'a> {
    pub fn new(part_content: &'a str, span: Span) -> Self {
        debug_assert!(part_content.starts_with('@'));
        debug_assert!(part_content.trim() == part_content);

        Self { raw: part_content, span }
    }

    /// Returns `kind`, it can be any string like `param`, `type`, `whatever`, ...etc.
    pub fn parsed(&self) -> &'a str {
        // +1 for `@`
        &self.raw[1..]
    }
}

/// Represents the raw type content inside a JSDoc tag's curly braces `{}`.
///
/// This struct captures the type expression including the curly braces.
/// It stores the raw string slice as it appears in the source (with the
/// enclosing braces) and its corresponding span.
///
/// For example, in a JSDoc tag like:
///
/// ```js
/// /**
///  * @param {foo=} bar
///  *         ^^^^
///  *         This is the `JSDocTagTypePart`, covering the full type expression
///  */
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JSDocTagTypePart<'a> {
    /// The raw, unprocessed type expression string inside `{}`, including the braces.
    /// For example: `"{foo=}"`, `"{Array<string>}"`, or `"{number | undefined}"`.
    raw: &'a str,

    /// The span in the source text covering the entire `{...}` expression, including the braces.
    pub span: Span,
}

impl<'a> JSDocTagTypePart<'a> {
    pub fn new(part_content: &'a str, span: Span) -> Self {
        debug_assert!(part_content.starts_with('{'));
        debug_assert!(part_content.ends_with('}'));

        Self { raw: part_content, span }
    }

    /// Returns the raw type string including `{` and `}`.
    pub fn raw(&self) -> &'a str {
        self.raw
    }

    /// Returns the type content without `{` and `}`.
    pub fn parsed(&self) -> &'a str {
        // +1 for `{`, -1 for `}`
        self.raw[1..self.raw.len() - 1].trim()
    }
}

/// Represents a single component of a type name in a JSDoc tag
/// typically seen within unions, generics, or optional/defaulted parameters.
///
/// This structure captures the raw source string, its span in the original code,
/// and any modifiers like optional (`?`) or default (`=`).
///
/// For example, in a JSDoc tag like:
///
/// ```js
/// /**
///  * @param {foo=} bar
///  *               ^^^
///  *               This is the `JSDocTagTypeNamePart`
///  * @type {string} [myStr]
///  *                ~~~~~~~ This is `optional: true` case
///  *
///  * @property {number} [myNum = 1]
///  *                    ~~~~~~~~~~~ This is `optional: true` and `default: true` case
///  */
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JSDocTagTypeNamePart<'a> {
    raw: &'a str,

    /// The span in the source text corresponding to this part.
    pub span: Span,

    /// Indicates whether the type name part is marked as optional (`foo?`).
    pub optional: bool,

    /// Indicates whether the type name part has a default value (`foo=`).
    pub default: bool,
}

impl<'a> JSDocTagTypeNamePart<'a> {
    pub fn new(part_content: &'a str, span: Span) -> Self {
        debug_assert!(part_content.trim() == part_content);

        let optional = part_content.starts_with('[') && part_content.ends_with(']');
        let default = optional && part_content.contains('=');

        Self { raw: part_content, span, optional, default }
    }

    /// Returns the raw text including brackets for optional/default params.
    /// e.g. `[name]`, `[name = default]`
    pub fn raw(&self) -> &'a str {
        self.raw
    }

    /// Returns the type name itself.
    /// `.raw` may be like `[foo = var]`, so extract the name
    pub fn parsed(&self) -> &'a str {
        if self.optional {
            let inner = self.raw.trim_start_matches('[').trim_end_matches(']').trim();
            return inner.split_once('=').map_or(inner, |(v, _)| v.trim());
        }

        self.raw
    }
}

#[cfg(test)]
#[expect(clippy::literal_string_with_formatting_args)]
mod test {
    use oxc_span::{SPAN, Span};

    use super::{JSDocCommentPart, JSDocTagKindPart, JSDocTagTypeNamePart, JSDocTagTypePart};

    #[test]
    fn comment_part_parsed() {
        for (actual, expect) in [
            ("", ""),
            ("hello  ", "hello"),
            ("  * single line", "* single line"),
            (" * ", "*"),
            (" * * ", "* *"),
            ("***", "***"),
            (
                "
      trim
    ",
                "trim",
            ),
            (
                "

    ", "",
            ),
            (
                "
                    *
                    *
                    ",
                "",
            ),
            (
                "
     * asterisk
    ",
                "asterisk",
            ),
            (
                "
     * * li
     * * li
    ",
                "* li\n* li",
            ),
            (
                "
    * list
    * list
    ",
                "list\nlist",
            ),
            (
                "
     * * 1
     ** 2
    ",
                "* 1\n* 2",
            ),
            (
                "
    1

    2

    3
                ",
                "1\n2\n3",
            ),
        ] {
            // `Span` is not used in this test
            let comment_part = JSDocCommentPart::new(actual, SPAN);
            assert_eq!(comment_part.parsed(), expect);
        }
    }

    #[test]
    fn comment_part_span_trimmed() {
        for (actual, expect) in [
            ("", ""),
            ("\n", ""),
            ("\n\n\n", ""),
            ("...", "..."),
            ("c1\n", "c1"),
            ("\nc2\n", "c2"),
            (" c 3\n", "c 3"),
            ("\nc4\n * ...\n ", "c4"),
            (
                "
 extra text
*
",
                "extra text",
            ),
            (
                "
 * foo
 * bar
",
                "* foo",
            ),
        ] {
            let comment_part =
                JSDocCommentPart::new(actual, Span::new(0, u32::try_from(actual.len()).unwrap()));
            assert_eq!(comment_part.span_trimmed_first_line().source_text(actual), expect);
        }
    }

    #[test]
    fn kind_part_parsed() {
        for (actual, expect) in [("@foo", "foo"), ("@", ""), ("@かいんど", "かいんど")] {
            // `Span` is not used in this test
            let kind_part = JSDocTagKindPart::new(actual, SPAN);
            assert_eq!(kind_part.parsed(), expect);
        }
    }

    #[test]
    fn type_part_parsed() {
        for (actual, expect) in [
            ("{}", ""),
            ("{-}", "-"),
            ("{string}", "string"),
            ("{ string}", "string"),
            ("{ bool  }", "bool"),
            ("{{x:1}}", "{x:1}"),
            ("{[1,2,3]}", "[1,2,3]"),
        ] {
            // `Span` is not used in this test
            let type_part = JSDocTagTypePart::new(actual, SPAN);
            assert_eq!(type_part.parsed(), expect);
        }
    }

    #[test]
    fn type_name_part_parsed() {
        for (actual, expect) in [
            ("foo", "foo"),
            ("Bar", "Bar"),
            ("変数", "変数"),
            ("[opt]", "opt"),
            ("[ opt2 ]", "opt2"),
            ("[def1 = [ 1 ]]", "def1"),
            (r#"[def2 = "foo bar"]"#, "def2"),
        ] {
            // `Span` is not used in this test
            let type_name_part = JSDocTagTypeNamePart::new(actual, SPAN);
            assert_eq!(type_name_part.parsed(), expect);
        }
    }
}