ctb_formats_javascript/
jsdoc.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND BSD-3-Clause
2// SPDX-License-Identifier for parts derived from from eslint-plugin-jsdoc: BSD-3-Clause
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21// Derived from eslint-plugin-jsdoc (https://github.com/gajus/eslint-plugin-jsdoc).
22
23// Copyright (c) 2018, Gajus Kuizinas (http://gajus.com/)
24
25// See additional licensing details at end of file.
26
27//! `JSDoc` comment parser and documentation extraction utilities.
28
29use deno_ast::ParsedSource;
30use deno_ast::SourceRange;
31use deno_ast::SourceRanged;
32use deno_ast::swc::common::comments::CommentKind;
33use deno_ast::view::NodeTrait;
34use deno_lint::diagnostic::{
35    LintDiagnostic, LintDiagnosticDetails, LintDiagnosticRange, LintDocsUrl,
36};
37
38#[derive(Debug, Clone, Copy, Default)]
39pub struct JSDocRules {
40    pub require_jsdoc: bool,
41    pub require_param: bool,
42    pub require_returns: bool,
43}
44
45pub fn run_jsdoc_linter(
46    parsed_source: &ParsedSource,
47    rules: JSDocRules,
48) -> Vec<LintDiagnostic> {
49    if !rules.require_jsdoc && !rules.require_param && !rules.require_returns {
50        return vec![];
51    }
52
53    let parsed_source = parsed_source.clone();
54    std::thread::spawn(move || {
55        let mut visitor = JSDocVisitor {
56            parsed_source: &parsed_source,
57            rules,
58            diagnostics: vec![],
59        };
60
61        parsed_source.with_view(|program| {
62            visitor.traverse(program.as_node());
63        });
64
65        visitor.diagnostics
66    })
67    .join()
68    // Reason for fallback: thread join returns Err if thread panics, defaulting to empty diagnostics vector.
69    .unwrap_or_default()
70}
71
72struct JSDocVisitor<'a> {
73    parsed_source: &'a ParsedSource,
74    rules: JSDocRules,
75    diagnostics: Vec<LintDiagnostic>,
76}
77
78impl<'view> JSDocVisitor<'_> {
79    fn traverse(&mut self, node: deno_ast::view::Node<'view>) {
80        self.visit_node(node);
81        for child in node.children() {
82            self.traverse(child);
83        }
84    }
85
86    fn visit_node(&mut self, node: deno_ast::view::Node<'view>) {
87        let is_func = matches!(
88            node,
89            deno_ast::view::Node::FnDecl(_)
90                | deno_ast::view::Node::FnExpr(_)
91                | deno_ast::view::Node::ArrowExpr(_)
92                | deno_ast::view::Node::ClassMethod(_)
93                | deno_ast::view::Node::PrivateMethod(_)
94                | deno_ast::view::Node::MethodProp(_)
95        );
96
97        if !is_func {
98            return;
99        }
100
101        // Exempt nested functions from JSDoc checks
102        if is_nested_function(node) {
103            return;
104        }
105
106        // Check if it's an inline callback (for FnExpr or ArrowExpr)
107        if matches!(
108            node,
109            deno_ast::view::Node::FnExpr(_)
110                | deno_ast::view::Node::ArrowExpr(_)
111        ) && is_inline_callback(node)
112        {
113            return;
114        }
115
116        // Constructors are exempt from require_jsdoc unless they have JSDoc
117        let is_constructor = is_constructor_node(node);
118
119        let jsdoc = get_jsdoc_comment(self.parsed_source, node);
120
121        if let Some(comment_text) = jsdoc {
122            let tags = parse_jsdoc_tags(&comment_text);
123
124            if self.rules.require_param {
125                let sig_params = get_parameter_names(node);
126                for param in &sig_params {
127                    if param.is_empty() {
128                        continue;
129                    }
130                    let has_param_tag = tags.iter().any(|t| {
131                        t.name == "param" && t.value_param_name == *param
132                    });
133                    if !has_param_tag {
134                        self.add_diagnostic(
135                            node.range(),
136                            "require-param",
137                            format!("Missing JSDoc @param tag for parameter '{param}'."),
138                        );
139                    }
140                }
141            }
142
143            if self.rules.require_returns && !is_constructor {
144                if has_non_empty_return(node) {
145                    let has_returns_tag = tags
146                        .iter()
147                        .any(|t| t.name == "returns" || t.name == "return");
148                    if !has_returns_tag {
149                        self.add_diagnostic(
150                            node.range(),
151                            "require-returns",
152                            "Missing JSDoc @returns or @return tag."
153                                .to_string(),
154                        );
155                    }
156                }
157            }
158        } else {
159            if self.rules.require_jsdoc && !is_constructor {
160                self.add_diagnostic(
161                    node.range(),
162                    "require-jsdoc",
163                    "Missing JSDoc comment for function/method.".to_string(),
164                );
165            }
166
167            if self.rules.require_param {
168                let sig_params = get_parameter_names(node);
169                for param in &sig_params {
170                    if param.is_empty() {
171                        continue;
172                    }
173                    self.add_diagnostic(
174                        node.range(),
175                        "require-param",
176                        format!(
177                            "Missing JSDoc @param tag for parameter '{param}'."
178                        ),
179                    );
180                }
181            }
182
183            if self.rules.require_returns && !is_constructor {
184                if has_non_empty_return(node) {
185                    self.add_diagnostic(
186                        node.range(),
187                        "require-returns",
188                        "Missing JSDoc @returns or @return tag.".to_string(),
189                    );
190                }
191            }
192        }
193    }
194
195    fn add_diagnostic(
196        &mut self,
197        range: SourceRange,
198        code: &str,
199        message: String,
200    ) {
201        self.diagnostics.push(LintDiagnostic {
202            specifier: self.parsed_source.specifier().clone(),
203            range: Some(LintDiagnosticRange {
204                text_info: self.parsed_source.text_info_lazy().clone(),
205                range,
206                description: None,
207            }),
208            details: LintDiagnosticDetails {
209                message,
210                code: code.to_string(),
211                hint: None,
212                fixes: vec![],
213                custom_docs_url: LintDocsUrl::None,
214                info: vec![],
215            },
216        });
217    }
218}
219
220struct ParsedTag {
221    name: String,
222    value_param_name: String,
223}
224
225fn parse_jsdoc_tags(text: &str) -> Vec<ParsedTag> {
226    let mut tags = vec![];
227    let mut current_tag_name = String::new();
228    let mut current_tag_value = String::new();
229
230    for line in text.lines() {
231        let trimmed = line.trim();
232        let content = if let Some(stripped) = trimmed.strip_prefix('*') {
233            stripped.trim()
234        } else {
235            trimmed
236        };
237
238        if let Some(tag_line) = content.strip_prefix('@') {
239            if !current_tag_name.is_empty() {
240                let val_name = if current_tag_name == "param" {
241                    get_param_name_from_tag_value(&current_tag_value)
242                } else {
243                    String::new()
244                };
245                tags.push(ParsedTag {
246                    name: current_tag_name.clone(),
247                    value_param_name: val_name,
248                });
249            }
250            if let Some(first_space_idx) = tag_line.find(char::is_whitespace) {
251                #[expect(
252                    clippy::expect_used,
253                    reason = "first_space_idx is returned by tag_line.find, guaranteeing valid char boundary"
254                )]
255                let name = tag_line
256                    .get(..first_space_idx)
257                    .expect("first_space_idx is returned by tag_line.find");
258                current_tag_name = name.to_string();
259                #[expect(
260                    clippy::expect_used,
261                    reason = "first_space_idx is returned by tag_line.find, guaranteeing valid char boundary"
262                )]
263                let val_slice = tag_line
264                    .get(first_space_idx..)
265                    .expect("first_space_idx is returned by tag_line.find");
266                current_tag_value = val_slice.trim().to_string();
267            } else {
268                current_tag_name = tag_line.to_string();
269                current_tag_value = String::new();
270            }
271        } else if !current_tag_name.is_empty() && !content.is_empty() {
272            if !current_tag_value.is_empty() {
273                current_tag_value.push(' ');
274            }
275            current_tag_value.push_str(content);
276        }
277    }
278
279    if !current_tag_name.is_empty() {
280        let val_name = if current_tag_name == "param" {
281            get_param_name_from_tag_value(&current_tag_value)
282        } else {
283            String::new()
284        };
285        tags.push(ParsedTag {
286            name: current_tag_name,
287            value_param_name: val_name,
288        });
289    }
290
291    tags
292}
293
294fn get_param_name_from_tag_value(value: &str) -> String {
295    let mut rest = value.trim();
296    if rest.starts_with('{') {
297        let mut depth: i32 = 0;
298        let mut end_idx = None;
299        for (idx, ch) in rest.char_indices() {
300            if ch == '{' {
301                depth = depth.saturating_add(1);
302            } else if ch == '}' {
303                depth = depth.saturating_sub(1);
304                if depth == 0 {
305                    end_idx = Some(idx);
306                    break;
307                }
308            }
309        }
310        if let Some(end_idx) = end_idx {
311            // Reason for fallback: if end_idx + 1 reaches or exceeds string length, empty string is returned.
312            rest = rest.get(end_idx.saturating_add(1)..).unwrap_or("").trim();
313        }
314    }
315
316    // Reason for fallback: if rest string contains only whitespace, empty string is returned as first word.
317    let first_word = rest.split_whitespace().next().unwrap_or("");
318    let mut param_name = first_word;
319    if param_name.starts_with('[') && param_name.ends_with(']') {
320        #[expect(
321            clippy::expect_used,
322            reason = "param_name starts with [ and ends with ], guaranteeing len >= 2"
323        )]
324        let inner = param_name
325            .get(1..param_name.len().saturating_sub(1))
326            .expect("param_name starts with [ and ends with ]");
327        param_name = inner;
328    }
329    if let Some(eq_idx) = param_name.find('=') {
330        #[expect(
331            clippy::expect_used,
332            reason = "eq_idx is returned by param_name.find('=')"
333        )]
334        let prefix = param_name
335            .get(..eq_idx)
336            .expect("eq_idx is returned by find('=')");
337        param_name = prefix;
338    }
339    param_name.to_string()
340}
341
342fn get_jsdoc_comment(
343    parsed_source: &ParsedSource,
344    node: deno_ast::view::Node,
345) -> Option<String> {
346    // Check the node itself first
347    if let Some(comment) = get_leading_jsdoc_at_pos(parsed_source, node.start())
348    {
349        return Some(comment);
350    }
351
352    // Check parent nodes
353    let mut parent = node.parent();
354    while let Some(p) = parent {
355        match p {
356            deno_ast::view::Node::ExportDecl(_)
357            | deno_ast::view::Node::ExportDefaultDecl(_)
358            | deno_ast::view::Node::ExportDefaultExpr(_)
359            | deno_ast::view::Node::VarDeclarator(_)
360            | deno_ast::view::Node::VarDecl(_)
361            | deno_ast::view::Node::ClassProp(_)
362            | deno_ast::view::Node::PrivateProp(_) => {
363                if let Some(comment) =
364                    get_leading_jsdoc_at_pos(parsed_source, p.start())
365                {
366                    return Some(comment);
367                }
368                parent = p.parent();
369            }
370            _ => break,
371        }
372    }
373    None
374}
375
376fn get_leading_jsdoc_at_pos(
377    parsed_source: &ParsedSource,
378    pos: deno_ast::SourcePos,
379) -> Option<String> {
380    if let Some(comments) = parsed_source.comments().get_leading(pos) {
381        for comment in comments.iter().rev() {
382            if comment.kind == CommentKind::Block
383                && comment.text.starts_with('*')
384            {
385                return Some(comment.text.to_string());
386            }
387        }
388    }
389    None
390}
391
392fn is_inline_callback(node: deno_ast::view::Node) -> bool {
393    let mut parent = node.parent();
394    while let Some(p) = parent {
395        match p {
396            deno_ast::view::Node::VarDeclarator(_)
397            | deno_ast::view::Node::ClassProp(_)
398            | deno_ast::view::Node::PrivateProp(_)
399            | deno_ast::view::Node::ExportDecl(_)
400            | deno_ast::view::Node::ExportDefaultDecl(_)
401            | deno_ast::view::Node::ExportDefaultExpr(_) => return false,
402            deno_ast::view::Node::KeyValueProp(_)
403            | deno_ast::view::Node::CallExpr(_)
404            | deno_ast::view::Node::NewExpr(_)
405            | deno_ast::view::Node::ArrayLit(_)
406            | deno_ast::view::Node::AssignExpr(_) => return true,
407            _ => {
408                parent = p.parent();
409            }
410        }
411    }
412    true
413}
414
415fn is_nested_function(node: deno_ast::view::Node) -> bool {
416    let mut parent = node.parent();
417    while let Some(p) = parent {
418        match p {
419            deno_ast::view::Node::FnDecl(_)
420            | deno_ast::view::Node::FnExpr(_)
421            | deno_ast::view::Node::ArrowExpr(_)
422            | deno_ast::view::Node::ClassMethod(_)
423            | deno_ast::view::Node::PrivateMethod(_)
424            | deno_ast::view::Node::MethodProp(_)
425            | deno_ast::view::Node::Constructor(_) => return true,
426            _ => {
427                parent = p.parent();
428            }
429        }
430    }
431    false
432}
433
434fn is_constructor_node(node: deno_ast::view::Node) -> bool {
435    matches!(node, deno_ast::view::Node::Constructor(_))
436}
437
438fn get_parameter_names(node: deno_ast::view::Node) -> Vec<String> {
439    let mut names = vec![];
440    match node {
441        deno_ast::view::Node::FnDecl(fn_decl) => {
442            for param in fn_decl.function.params {
443                collect_pat_names(&param.pat, &mut names);
444            }
445        }
446        deno_ast::view::Node::FnExpr(fn_expr) => {
447            for param in fn_expr.function.params {
448                collect_pat_names(&param.pat, &mut names);
449            }
450        }
451        deno_ast::view::Node::ArrowExpr(arrow_expr) => {
452            for param in arrow_expr.params {
453                collect_pat_names(param, &mut names);
454            }
455        }
456        deno_ast::view::Node::ClassMethod(class_method) => {
457            for param in class_method.function.params {
458                collect_pat_names(&param.pat, &mut names);
459            }
460        }
461        deno_ast::view::Node::PrivateMethod(private_method) => {
462            for param in private_method.function.params {
463                collect_pat_names(&param.pat, &mut names);
464            }
465        }
466        deno_ast::view::Node::MethodProp(method_prop) => {
467            for param in method_prop.function.params {
468                collect_pat_names(&param.pat, &mut names);
469            }
470        }
471        deno_ast::view::Node::Constructor(constructor) => {
472            for param in constructor.params {
473                match param {
474                    deno_ast::view::ParamOrTsParamProp::Param(p) => {
475                        collect_pat_names(&p.pat, &mut names);
476                    }
477                    deno_ast::view::ParamOrTsParamProp::TsParamProp(tp) => {
478                        match &tp.param {
479                            deno_ast::view::TsParamPropParam::Ident(ident) => {
480                                names.push(ident.id.sym().to_string());
481                            }
482                            deno_ast::view::TsParamPropParam::Assign(
483                                assign,
484                            ) => {
485                                collect_pat_names(&assign.left, &mut names);
486                            }
487                        }
488                    }
489                }
490            }
491        }
492        _ => {}
493    }
494    names
495}
496
497fn collect_pat_names(pat: &deno_ast::view::Pat, names: &mut Vec<String>) {
498    match pat {
499        deno_ast::view::Pat::Ident(binding_ident) => {
500            names.push(binding_ident.id.sym().to_string());
501        }
502        deno_ast::view::Pat::Assign(assign_pat) => {
503            collect_pat_names(&assign_pat.left, names);
504        }
505        deno_ast::view::Pat::Rest(rest_pat) => {
506            collect_pat_names(&rest_pat.arg, names);
507        }
508        _ => {}
509    }
510}
511
512fn has_non_empty_return(node: deno_ast::view::Node) -> bool {
513    if let deno_ast::view::Node::ArrowExpr(arrow) = node {
514        if let deno_ast::view::BlockStmtOrExpr::Expr(_) = arrow.body {
515            return true;
516        }
517    }
518
519    let mut finder = ReturnFinder { has_return: false };
520    match node {
521        deno_ast::view::Node::FnDecl(fn_decl) => {
522            if let Some(body) = fn_decl.function.body {
523                finder.visit_block(body);
524            }
525        }
526        deno_ast::view::Node::FnExpr(fn_expr) => {
527            if let Some(body) = fn_expr.function.body {
528                finder.visit_block(body);
529            }
530        }
531        deno_ast::view::Node::ArrowExpr(arrow) => {
532            if let deno_ast::view::BlockStmtOrExpr::BlockStmt(body) = arrow.body
533            {
534                finder.visit_block(body);
535            }
536        }
537        deno_ast::view::Node::ClassMethod(class_method) => {
538            if let Some(body) = class_method.function.body {
539                finder.visit_block(body);
540            }
541        }
542        deno_ast::view::Node::PrivateMethod(private_method) => {
543            if let Some(body) = private_method.function.body {
544                finder.visit_block(body);
545            }
546        }
547        deno_ast::view::Node::MethodProp(method_prop) => {
548            if let Some(body) = method_prop.function.body {
549                finder.visit_block(body);
550            }
551        }
552        _ => {}
553    }
554    finder.has_return
555}
556
557struct ReturnFinder {
558    has_return: bool,
559}
560
561impl<'view> ReturnFinder {
562    fn visit_block(&mut self, block: &deno_ast::view::BlockStmt<'view>) {
563        for stmt in block.stmts {
564            self.visit_stmt(stmt.as_node());
565            if self.has_return {
566                break;
567            }
568        }
569    }
570
571    fn visit_stmt(&mut self, stmt: deno_ast::view::Node<'view>) {
572        if self.has_return {
573            return;
574        }
575        match stmt {
576            deno_ast::view::Node::ReturnStmt(ret) => {
577                if ret.arg.is_some() {
578                    self.has_return = true;
579                }
580            }
581            deno_ast::view::Node::FnDecl(_)
582            | deno_ast::view::Node::FnExpr(_)
583            | deno_ast::view::Node::ArrowExpr(_)
584            | deno_ast::view::Node::ClassDecl(_)
585            | deno_ast::view::Node::ClassExpr(_) => {}
586            _ => {
587                for child in stmt.children() {
588                    self.visit_stmt(child);
589                }
590            }
591        }
592    }
593}
594
595#[cfg(test)]
596#[allow(
597    clippy::panic,
598    clippy::expect_used,
599    clippy::unwrap_used,
600    clippy::unwrap_in_result,
601    clippy::panic_in_result_fn,
602    clippy::indexing_slicing,
603    clippy::arithmetic_side_effects,
604    reason = "Standard repository test boilerplate"
605)]
606mod tests {
607    use super::*;
608    use deno_ast::MediaType;
609    use deno_ast::ModuleSpecifier;
610    use deno_ast::ParseParams;
611    use deno_ast::parse_program;
612
613    fn parse_code(code: &str) -> ParsedSource {
614        parse_program(ParseParams {
615            specifier: ModuleSpecifier::parse("file:///my_file.js").unwrap(),
616            text: code.into(),
617            media_type: MediaType::JavaScript,
618            capture_tokens: true,
619            maybe_syntax: None,
620            scope_analysis: false,
621        })
622        .unwrap()
623    }
624
625    #[crate::ctb_test]
626    fn test_require_jsdoc() {
627        let code = "function foo() {}";
628        let parsed = parse_code(code);
629        let rules = JSDocRules {
630            require_jsdoc: true,
631            ..Default::default()
632        };
633        let diags = run_jsdoc_linter(&parsed, rules);
634        assert_eq!(diags.len(), 1);
635        assert_eq!(diags[0].details.code, "require-jsdoc");
636
637        let code_with_jsdoc = "/**\n * @param x\n */\nfunction foo() {}";
638        let parsed = parse_code(code_with_jsdoc);
639        let diags = run_jsdoc_linter(&parsed, rules);
640        assert_eq!(diags.len(), 0);
641    }
642
643    #[crate::ctb_test]
644    fn test_require_param() {
645        let code = "/**\n * @param {string} a\n */\nfunction foo(a, b) {}";
646        let parsed = parse_code(code);
647        let rules = JSDocRules {
648            require_param: true,
649            ..Default::default()
650        };
651        let diags = run_jsdoc_linter(&parsed, rules);
652        assert_eq!(diags.len(), 1);
653        assert_eq!(diags[0].details.code, "require-param");
654        assert!(diags[0].details.message.contains("'b'"));
655    }
656
657    #[crate::ctb_test]
658    fn test_require_returns() {
659        let code =
660            "/**\n * Some description\n */\nfunction foo() { return 1; }";
661        let parsed = parse_code(code);
662        let rules = JSDocRules {
663            require_returns: true,
664            ..Default::default()
665        };
666        let diags = run_jsdoc_linter(&parsed, rules);
667        assert_eq!(diags.len(), 1);
668        assert_eq!(diags[0].details.code, "require-returns");
669
670        let code_returns_void =
671            "/**\n * Some description\n */\nfunction foo() { return; }";
672        let parsed = parse_code(code_returns_void);
673        let diags = run_jsdoc_linter(&parsed, rules);
674        assert_eq!(diags.len(), 0);
675    }
676}
677
678/*
679Code from eslint-plugin-jsdoc is used under the following license:
680======
681
682Copyright (c) 2018, Gajus Kuizinas (http://gajus.com/)
683All rights reserved.
684
685Redistribution and use in source and binary forms, with or without
686modification, are permitted provided that the following conditions are met:
687    * Redistributions of source code must retain the above copyright
688      notice, this list of conditions and the following disclaimer.
689    * Redistributions in binary form must reproduce the above copyright
690      notice, this list of conditions and the following disclaimer in the
691      documentation and/or other materials provided with the distribution.
692    * Neither the name of the Gajus Kuizinas (http://gajus.com/) nor the
693      names of its contributors may be used to endorse or promote products
694      derived from this software without specific prior written permission.
695
696THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
697ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
698WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
699DISCLAIMED. IN NO EVENT SHALL ANUARY BE LIABLE FOR ANY
700DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
701(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
702LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
703ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
704(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
705SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
706
707*/