Skip to main content

rust_anything/ts/
jsdoc.rs

1//! Types for untyped JavaScript: JSDoc `@param`/`@returns` tags and sibling `.d.ts` declarations,
2//! written in the same TS dialect the TypeScript path reads.
3
4use std::path::Path;
5
6use oxc_allocator::Allocator;
7use oxc_parser::Parser;
8use oxc_span::SourceType;
9
10use super::exports::ExportedFn;
11
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub struct ParamTag {
14    pub name: String,
15    pub ts_type: Option<String>,
16    pub optional: bool,
17}
18
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub struct JsDoc {
21    pub params: Vec<ParamTag>,
22    pub returns: Option<String>,
23}
24
25impl JsDoc {
26    pub fn param(&self, name: &str) -> Option<&ParamTag> {
27        self.params.iter().find(|p| p.name == name)
28    }
29}
30
31pub fn leading(source: &str, offset: usize) -> Option<JsDoc> {
32    let before = source[..offset].trim_end();
33    let body_end = before.strip_suffix("*/")?.len();
34    let start = before[..body_end].rfind("/**")?;
35    let body = &before[start + 3..body_end];
36    if body.contains("*/") {
37        return None;
38    }
39    Some(parse(body))
40}
41
42pub fn parse(body: &str) -> JsDoc {
43    let mut chunks: Vec<String> = Vec::new();
44    for line in body.lines() {
45        let line = line.trim_start();
46        let line = line.strip_prefix('*').unwrap_or(line).trim();
47        match (line.strip_prefix('@'), chunks.last_mut()) {
48            (Some(tag), _) => chunks.push(tag.to_string()),
49            (None, Some(chunk)) => {
50                chunk.push('\n');
51                chunk.push_str(line);
52            }
53            (None, None) => {}
54        }
55    }
56    let mut doc = JsDoc::default();
57    let mut nested: Vec<(String, String, Option<String>, bool)> = Vec::new();
58    for chunk in &chunks {
59        let chunk = chunk.as_str();
60        let (tag, rest) = chunk.split_once(char::is_whitespace).unwrap_or((chunk, ""));
61        let rest = rest.trim_start();
62        let (raw_type, rest) = match braced(rest) {
63            Some((t, after)) => (Some(t), after.trim_start()),
64            None => (None, rest),
65        };
66        match tag {
67            "param" | "arg" | "argument" => {
68                let Some((name, bracketed)) = param_name(rest) else {
69                    continue;
70                };
71                let (ts_type, optional_type) = match raw_type {
72                    Some(t) => match to_ts(t) {
73                        Some((ts, opt)) => (Some(ts), opt),
74                        None => (None, false),
75                    },
76                    None => (None, false),
77                };
78                let optional = bracketed || optional_type;
79                if let Some((parent, field)) = name.split_once('.') {
80                    nested.push((parent.to_string(), field.to_string(), ts_type, optional));
81                } else {
82                    doc.params.push(ParamTag {
83                        name,
84                        ts_type,
85                        optional,
86                    });
87                }
88            }
89            "returns" | "return" => {
90                doc.returns = raw_type.and_then(to_ts).map(|(t, _)| t);
91            }
92            _ => {}
93        }
94    }
95    for p in &mut doc.params {
96        let fields: Vec<_> = nested
97            .iter()
98            .filter(|(parent, ..)| *parent == p.name)
99            .collect();
100        if fields.is_empty() || !matches!(p.ts_type.as_deref(), Some("object" | "Object")) {
101            continue;
102        }
103        if fields
104            .iter()
105            .any(|(_, f, t, _)| f.contains('.') || t.is_none())
106        {
107            p.ts_type = None;
108            continue;
109        }
110        let members: Vec<String> = fields
111            .iter()
112            .map(|(_, f, t, opt)| {
113                format!(
114                    "{f}{}: {}",
115                    if *opt { "?" } else { "" },
116                    t.as_deref().unwrap_or("unknown")
117                )
118            })
119            .collect();
120        p.ts_type = Some(format!("{{ {} }}", members.join("; ")));
121    }
122    doc
123}
124
125fn braced(text: &str) -> Option<(&str, &str)> {
126    let rest = text.strip_prefix('{')?;
127    let mut depth = 1;
128    for (i, c) in rest.char_indices() {
129        match c {
130            '{' => depth += 1,
131            '}' => {
132                depth -= 1;
133                if depth == 0 {
134                    return Some((&rest[..i], &rest[i + 1..]));
135                }
136            }
137            _ => {}
138        }
139    }
140    None
141}
142
143fn param_name(text: &str) -> Option<(String, bool)> {
144    if let Some(inner) = text.strip_prefix('[') {
145        let end = inner.find(']')?;
146        let name = inner[..end].split('=').next()?.trim();
147        return valid_name(name).then(|| (name.to_string(), true));
148    }
149    let name = text.split(|c: char| c.is_whitespace()).next()?;
150    let name = name.trim_end_matches(['-', ',']);
151    valid_name(name).then(|| (name.to_string(), false))
152}
153
154fn valid_name(name: &str) -> bool {
155    !name.is_empty()
156        && name
157            .chars()
158            .all(|c| c.is_alphanumeric() || matches!(c, '_' | '$' | '.'))
159}
160
161pub fn to_ts(jsdoc: &str) -> Option<(String, bool)> {
162    let mut t = jsdoc.trim();
163    let optional = t.ends_with('=');
164    t = t.trim_end_matches('=').trim();
165    let rest = t.starts_with("...");
166    t = t.trim_start_matches("...").trim();
167    if t.contains("function(") || t.contains("=>") {
168        return None;
169    }
170    let mut ts = match t {
171        "" | "*" | "?" => "unknown".to_string(),
172        _ => {
173            let (nullable, inner) = match (t.strip_prefix('?'), t.strip_prefix('!')) {
174                (Some(inner), _) => (true, inner),
175                (_, Some(inner)) => (false, inner),
176                _ => (false, t),
177            };
178            let inner = normalize(inner.trim());
179            if nullable {
180                format!("({inner}) | null")
181            } else {
182                inner
183            }
184        }
185    };
186    if rest {
187        ts = format!("({ts})[]");
188    }
189    is_type(&ts).then_some((ts, optional))
190}
191
192fn normalize(t: &str) -> String {
193    let t = t.replace("Object.<", "Record<").replace(".<", "<");
194    let mut out = String::with_capacity(t.len());
195    let mut word = String::new();
196    let flush = |word: &mut String, out: &mut String| {
197        out.push_str(match word.as_str() {
198            "String" => "string",
199            "Number" => "number",
200            "Boolean" => "boolean",
201            "Object" => "object",
202            w => w,
203        });
204        word.clear();
205    };
206    for c in t.chars() {
207        if c.is_alphanumeric() || c == '_' || c == '$' {
208            word.push(c);
209        } else {
210            flush(&mut word, &mut out);
211            out.push(c);
212        }
213    }
214    flush(&mut word, &mut out);
215    out
216}
217
218fn is_type(ts: &str) -> bool {
219    let source = format!("type __T = {ts};");
220    let allocator = Allocator::default();
221    let ret = Parser::new(&allocator, &source, SourceType::ts()).parse();
222    ret.diagnostics.is_empty() && ret.program.body.len() == 1
223}
224
225pub fn declaration_file(root: &Path, file: &str) -> Option<String> {
226    let (stem, ext) = file.rsplit_once('.')?;
227    let own = match ext {
228        "mjs" => "d.mts",
229        "cjs" => "d.cts",
230        "js" | "jsx" => "d.ts",
231        _ => return None,
232    };
233    [own, "d.ts", "d.mts", "d.cts"]
234        .iter()
235        .map(|d| format!("{stem}.{d}"))
236        .find(|candidate| root.join(candidate).is_file())
237}
238
239pub fn apply_declarations(root: &Path, file: &str, fns: &mut [ExportedFn]) {
240    let Some(decl_file) = declaration_file(root, file) else {
241        return;
242    };
243    let Ok(text) = std::fs::read_to_string(root.join(&decl_file)) else {
244        return;
245    };
246    let declared = super::exports::declared_functions(&decl_file, &text);
247    for f in fns {
248        let mut matching = declared.iter().filter(|d| d.name == f.name);
249        let (Some(d), None) = (matching.next(), matching.next()) else {
250            continue;
251        };
252        for (p, dp) in f.params.iter_mut().zip(&d.params) {
253            if dp.rest != p.rest {
254                break;
255            }
256            if dp.ts_type != "unknown" {
257                p.ts_type = dp.ts_type.clone();
258            }
259            p.optional |= dp.optional;
260        }
261        if d.returns != "unknown" {
262            f.returns = d.returns.clone();
263        }
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn maps_jsdoc_types() {
273        let ts = |t: &str| to_ts(t).map(|(t, _)| t);
274        assert_eq!(ts("string"), Some("string".into()));
275        assert_eq!(ts("Array.<String>"), Some("Array<string>".into()));
276        assert_eq!(ts("?number"), Some("(number) | null".into()));
277        assert_eq!(ts("string|undefined"), Some("string|undefined".into()));
278        assert_eq!(
279            ts("Object.<string, number>"),
280            Some("Record<string, number>".into())
281        );
282        assert_eq!(
283            ts("{a: string, b: number}"),
284            Some("{a: string, b: number}".into())
285        );
286        assert_eq!(ts("...string"), Some("(string)[]".into()));
287        assert_eq!(ts("*"), Some("unknown".into()));
288        assert_eq!(to_ts("number="), Some(("number".into(), true)));
289        assert_eq!(ts("function(string): number"), None);
290    }
291
292    #[test]
293    fn reads_param_and_return_tags() {
294        let doc = parse(
295            "\n * Splits a line.\n * @param {string} source - the text\n * @param {string} [delimiter=\",\"]\n\
296             * @param {Object} opts\n * @param {boolean} opts.trim\n * @param {number} [opts.limit]\n\
297             * @returns {string[]}\n ",
298        );
299        assert_eq!(
300            doc.param("source").unwrap().ts_type.as_deref(),
301            Some("string")
302        );
303        assert!(!doc.param("source").unwrap().optional);
304        assert!(doc.param("delimiter").unwrap().optional);
305        assert_eq!(
306            doc.param("opts").unwrap().ts_type.as_deref(),
307            Some("{ trim: boolean; limit?: number }")
308        );
309        assert_eq!(doc.returns.as_deref(), Some("string[]"));
310    }
311}