Skip to main content

rust_anything/ts/
exports.rs

1//! Exported functions of a TS/JS file, with their parameter and return types as written.
2
3use oxc_allocator::Allocator;
4use oxc_ast::ast::{
5    BindingPattern, Declaration, Expression, FormalParameters, Statement, TSTypeAnnotation,
6};
7use oxc_parser::Parser;
8use oxc_span::{GetSpan, SourceType};
9use serde::{Deserialize, Serialize};
10
11use super::jsdoc::{self, JsDoc, ParamTag};
12
13#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
14pub struct Param {
15    pub name: String,
16    /// The type in the TS-like dialect; `unknown` when there is no annotation.
17    pub ts_type: String,
18    pub optional: bool,
19    pub rest: bool,
20    /// The default value as written in the source, when the language has defaults.
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub default: Option<String>,
23    /// Python keyword-only parameter (after `*`).
24    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
25    pub keyword_only: bool,
26    /// The exact source type, for languages whose bridge must match it (C: `size_t`).
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub native_type: Option<String>,
29}
30
31#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
32pub struct ExportedFn {
33    pub name: String,
34    /// Source file, relative to the repository root.
35    pub file: String,
36    pub line: u32,
37    pub params: Vec<Param>,
38    /// The TS return type as written; `unknown` when there is no annotation.
39    pub returns: String,
40    pub is_async: bool,
41    #[serde(default)]
42    pub is_generator: bool,
43    /// Names of the function's own type parameters (`T` in `f<T>(x: T)`).
44    #[serde(default)]
45    pub type_params: Vec<String>,
46    /// The body checks `instanceof`: class identity, which does not survive a bridge.
47    #[serde(default)]
48    pub uses_instanceof: bool,
49    /// Why the function must stay in its language, found by the language plugin.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub blocker: Option<String>,
52    /// The exact source return type (C: `unsigned long`).
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub native_return: Option<String>,
55    /// The declaration as written (C: `int word_count(const char *text)`).
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub prototype: Option<String>,
58}
59
60/// An exported class: its constructor and public instance methods, or why it must stay in TS.
61#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
62pub struct ExportedClass {
63    pub name: String,
64    pub file: String,
65    pub line: u32,
66    pub constructor: Vec<Param>,
67    pub methods: Vec<ExportedFn>,
68    /// Set when the class cannot cross a bridge as it is (inheritance, public fields, ...).
69    pub blocker: Option<String>,
70}
71
72/// Top-level `export class` declarations.
73pub fn exported_classes(path: &str, source: &str) -> Vec<ExportedClass> {
74    use oxc_ast::ast::{ClassElement, MethodDefinitionKind, TSAccessibility};
75    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
76    let allocator = Allocator::default();
77    let ret = Parser::new(&allocator, source, source_type).parse();
78    let text = |span: oxc_span::Span| source[span.start as usize..span.end as usize].to_string();
79    let line = |offset: u32| {
80        u32::try_from(source[..offset as usize].matches('\n').count() + 1).unwrap_or(u32::MAX)
81    };
82    let annotation = |ann: Option<&TSTypeAnnotation>| {
83        ann.map_or_else(|| "unknown".to_string(), |a| text(a.type_annotation.span()))
84    };
85    let params_of = |params: &FormalParameters| -> Vec<Param> {
86        params
87            .items
88            .iter()
89            .enumerate()
90            .map(|(i, p)| Param {
91                name: binding_name(&p.pattern).unwrap_or_else(|| format!("arg{i}")),
92                ts_type: annotation(p.type_annotation.as_deref()),
93                optional: p.optional || p.initializer.is_some(),
94                rest: false,
95                ..Default::default()
96            })
97            .collect()
98    };
99    let mut out = Vec::new();
100    for statement in &ret.program.body {
101        let Statement::ExportDeclaration(export) = statement else {
102            continue;
103        };
104        let Declaration::ClassDeclaration(class) = &export.declaration else {
105            continue;
106        };
107        let Some(id) = &class.id else { continue };
108        let mut blockers: Vec<String> = Vec::new();
109        if class.heritage.is_some() {
110            blockers.push("extends another class".into());
111        }
112        let mut constructor = Vec::new();
113        let mut methods = Vec::new();
114        for element in &class.body.body {
115            match element {
116                ClassElement::MethodDefinition(m) => {
117                    let hidden = m.key.is_private_identifier()
118                        || matches!(
119                            m.accessibility,
120                            Some(TSAccessibility::Private | TSAccessibility::Protected)
121                        );
122                    let name = m
123                        .key
124                        .static_name()
125                        .and_then(|n| n.as_str().map(str::to_string));
126                    match m.kind {
127                        MethodDefinitionKind::Constructor => {
128                            constructor = params_of(&m.value.params);
129                            // `constructor(public data)`: a parameter property is a public field.
130                            if m.value.params.items.iter().any(|p| {
131                                matches!(p.accessibility, Some(TSAccessibility::Public))
132                                    || (p.readonly && p.accessibility.is_none())
133                            }) {
134                                blockers.push("public parameter properties".into());
135                            }
136                        }
137                        _ if hidden => {}
138                        MethodDefinitionKind::Get | MethodDefinitionKind::Set => {
139                            blockers.push(format!("accessor `{}`", name.unwrap_or_default()));
140                        }
141                        MethodDefinitionKind::Method if m.r#static => {
142                            blockers.push(format!("static method `{}`", name.unwrap_or_default()));
143                        }
144                        MethodDefinitionKind::Method => {
145                            let Some(name) = name else {
146                                blockers.push("computed method name".into());
147                                continue;
148                            };
149                            let f = &m.value;
150                            methods.push(ExportedFn {
151                                name,
152                                file: path.to_string(),
153                                line: line(m.span.start),
154                                params: params_of(&f.params),
155                                returns: annotation(f.return_type.as_deref()),
156                                is_async: f.r#async,
157                                is_generator: f.generator,
158                                type_params: Vec::new(),
159                                uses_instanceof: uses_instanceof(&text(m.span)),
160                                ..Default::default()
161                            });
162                        }
163                    }
164                }
165                ClassElement::PropertyDefinition(p) => {
166                    let hidden = p.key.is_private_identifier()
167                        || matches!(
168                            p.accessibility,
169                            Some(TSAccessibility::Private | TSAccessibility::Protected)
170                        );
171                    if !hidden {
172                        let name = p
173                            .key
174                            .static_name()
175                            .and_then(|n| n.as_str().map(str::to_string))
176                            .unwrap_or_default();
177                        blockers.push(format!("public field `{name}`"));
178                    }
179                }
180                ClassElement::AccessorProperty(_) => blockers.push("accessor property".into()),
181                ClassElement::StaticBlock(_) => blockers.push("static block".into()),
182                ClassElement::TSIndexSignature(_) => {}
183            }
184        }
185        let name = id.name.as_str().to_string();
186        for m in &methods {
187            if m.is_async || m.is_generator {
188                blockers.push(format!("async or generator method `{}`", m.name));
189            }
190            let returns_self = m
191                .returns
192                .split(|c: char| !(c.is_alphanumeric() || c == '_'))
193                .any(|w| w == name || w == "this");
194            if returns_self {
195                blockers.push(format!("method `{}` returns an instance", m.name));
196            }
197        }
198        out.push(ExportedClass {
199            name,
200            file: path.to_string(),
201            line: line(class.span.start),
202            constructor,
203            methods,
204            blocker: (!blockers.is_empty()).then(|| blockers.join(", ")),
205        });
206    }
207    out
208}
209
210/// Top-level `export function f()` and `export const f = () => ...` declarations.
211pub fn exported_functions(path: &str, source: &str) -> Vec<ExportedFn> {
212    functions(path, source, false)
213}
214
215pub fn declared_functions(path: &str, source: &str) -> Vec<ExportedFn> {
216    functions(path, source, true)
217}
218
219fn functions(path: &str, source: &str, declarations: bool) -> Vec<ExportedFn> {
220    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
221    let allocator = Allocator::default();
222    let ret = Parser::new(&allocator, source, source_type).parse();
223    let text = |span: oxc_span::Span| source[span.start as usize..span.end as usize].to_string();
224    let annotation = |ann: Option<&TSTypeAnnotation>| {
225        ann.map_or_else(|| "unknown".to_string(), |a| text(a.type_annotation.span()))
226    };
227    let line = |offset: u32| {
228        u32::try_from(source[..offset as usize].matches('\n').count() + 1).unwrap_or(u32::MAX)
229    };
230    let params = |params: &FormalParameters, doc: &JsDoc| -> Vec<Param> {
231        let mut out: Vec<Param> = params
232            .items
233            .iter()
234            .enumerate()
235            .map(|(i, p)| {
236                let name = binding_name(&p.pattern).unwrap_or_else(|| format!("arg{i}"));
237                let tag = doc.param(&name);
238                let documented = tag.and_then(|t| t.ts_type.clone());
239                Param {
240                    ts_type: match (&p.type_annotation, documented, p.initializer.as_deref()) {
241                        (Some(a), _, _) => annotation(Some(a)),
242                        (None, Some(t), _) => t,
243                        // `namespaced = true`: the type comes from the default value.
244                        (None, None, Some(Expression::BooleanLiteral(_))) => "boolean".into(),
245                        (None, None, Some(Expression::NumericLiteral(_))) => "number".into(),
246                        (
247                            None,
248                            None,
249                            Some(Expression::StringLiteral(_) | Expression::TemplateLiteral(_)),
250                        ) => "string".into(),
251                        (None, None, _) => "unknown".into(),
252                    },
253                    optional: p.optional
254                        || p.initializer.is_some()
255                        || (p.type_annotation.is_none() && tag.is_some_and(|t| t.optional)),
256                    rest: false,
257                    name,
258                    ..Default::default()
259                }
260            })
261            .collect();
262        if let Some(rest) = &params.rest {
263            let name = binding_name(&rest.rest.argument).unwrap_or_else(|| "rest".into());
264            let ts_type = match (&rest.type_annotation, doc.param(&name)) {
265                (
266                    None,
267                    Some(ParamTag {
268                        ts_type: Some(t), ..
269                    }),
270                ) => t.clone(),
271                (ann, _) => annotation(ann.as_deref()),
272            };
273            out.push(Param {
274                name,
275                ts_type,
276                optional: true,
277                rest: true,
278                ..Default::default()
279            });
280        }
281        out
282    };
283    let returns_of = |ann: Option<&TSTypeAnnotation>, doc: &JsDoc| match (ann, &doc.returns) {
284        (None, Some(t)) => t.clone(),
285        (ann, _) => annotation(ann),
286    };
287
288    let function_entry = |f: &oxc_ast::ast::Function, doc: &JsDoc, exported: Option<String>| {
289        let id = f.id.as_ref()?;
290        Some(ExportedFn {
291            name: exported.unwrap_or_else(|| id.name.as_str().to_string()),
292            file: path.to_string(),
293            line: line(f.span.start),
294            params: params(&f.params, doc),
295            returns: returns_of(f.return_type.as_deref(), doc),
296            is_async: f.r#async,
297            is_generator: f.generator,
298            type_params: type_params_of(f.type_parameters.as_deref(), &text),
299            uses_instanceof: uses_instanceof(&text(f.span)),
300            ..Default::default()
301        })
302    };
303    let declarator_entry =
304        |declarator: &oxc_ast::ast::VariableDeclarator, doc: &JsDoc, exported: Option<String>| {
305            let name = binding_name(&declarator.id)?;
306            let type_names =
307                |tp: Option<&oxc_ast::ast::TSTypeParameterDeclaration>| type_params_of(tp, &text);
308            let (fn_params, returns, is_async, is_generator, span, type_params) =
309                match &declarator.init {
310                    Some(Expression::ArrowFunctionExpression(f)) => (
311                        &f.params,
312                        f.return_type.as_deref(),
313                        f.r#async,
314                        false,
315                        f.span,
316                        type_names(f.type_parameters.as_deref()),
317                    ),
318                    Some(Expression::FunctionExpression(f)) => (
319                        &f.params,
320                        f.return_type.as_deref(),
321                        f.r#async,
322                        f.generator,
323                        f.span,
324                        type_names(f.type_parameters.as_deref()),
325                    ),
326                    _ => return None,
327                };
328            Some(ExportedFn {
329                name: exported.unwrap_or(name),
330                file: path.to_string(),
331                line: line(span.start),
332                params: params(fn_params, doc),
333                returns: returns_of(returns, doc),
334                is_async,
335                is_generator,
336                type_params,
337                uses_instanceof: uses_instanceof(&text(span)),
338                ..Default::default()
339            })
340        };
341
342    let mut out = Vec::new();
343    let mut local = std::collections::HashMap::new();
344    let mut listed = Vec::new();
345    for statement in &ret.program.body {
346        let doc = jsdoc::leading(source, statement.span().start as usize).unwrap_or_default();
347        match statement {
348            Statement::ExportDeclaration(export) => match &export.declaration {
349                // Overload signatures have no body: the implementation signature follows them.
350                Declaration::FunctionDeclaration(f) if f.body.is_some() != declarations => {
351                    out.extend(function_entry(f, &doc, None));
352                }
353                Declaration::VariableDeclaration(vars) if !declarations => {
354                    for declarator in &vars.declarations {
355                        out.extend(declarator_entry(declarator, &doc, None));
356                    }
357                }
358                _ => {}
359            },
360            Statement::ExportNamedDeclaration(export)
361                if !declarations && !export.export_kind.is_type() =>
362            {
363                for spec in &export.specifiers {
364                    if !spec.export_kind.is_type() {
365                        listed.push((
366                            spec.local.name().to_string(),
367                            spec.exported.name().to_string(),
368                        ));
369                    }
370                }
371            }
372            Statement::FunctionDeclaration(f) if f.body.is_some() => {
373                if let Some(id) = &f.id {
374                    local.insert(id.name.as_str().to_string(), (Local::Function(f), doc));
375                }
376            }
377            Statement::VariableDeclaration(vars) => {
378                for declarator in &vars.declarations {
379                    if let Some(name) = binding_name(&declarator.id) {
380                        local.insert(name, (Local::Declarator(declarator), doc.clone()));
381                    }
382                }
383            }
384            _ => {}
385        }
386    }
387    for (name, exported) in listed {
388        match local.get(&name) {
389            Some((Local::Function(f), doc)) => out.extend(function_entry(f, doc, Some(exported))),
390            Some((Local::Declarator(d), doc)) => {
391                out.extend(declarator_entry(d, doc, Some(exported)));
392            }
393            None => {}
394        }
395    }
396    out
397}
398
399enum Local<'b, 'a> {
400    Function(&'b oxc_ast::ast::Function<'a>),
401    Declarator(&'b oxc_ast::ast::VariableDeclarator<'a>),
402}
403
404/// Type parameters as `T`, or `T extends <constraint>` when constrained.
405fn type_params_of(
406    tp: Option<&oxc_ast::ast::TSTypeParameterDeclaration>,
407    text: &dyn Fn(oxc_span::Span) -> String,
408) -> Vec<String> {
409    tp.map(|tp| {
410        tp.params
411            .iter()
412            .map(|p| match &p.constraint {
413                Some(c) => format!("{} extends {}", p.name.name.as_str(), text(c.span())),
414                None => p.name.name.as_str().to_string(),
415            })
416            .collect()
417    })
418    .unwrap_or_default()
419}
420
421fn uses_instanceof(code: &str) -> bool {
422    code.split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
423        .any(|word| word == "instanceof")
424}
425
426/// A top-level interface or type alias.
427#[derive(Clone, Debug, PartialEq, Eq)]
428pub struct LocalType {
429    pub name: String,
430    /// The whole interface, or the right-hand side of a type alias.
431    pub text: String,
432    /// A type alias without type parameters: its uses can be replaced by `text`.
433    pub alias: bool,
434}
435
436/// Interfaces and type aliases declared at the top level of a file.
437pub fn local_types(path: &str, source: &str) -> Vec<LocalType> {
438    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
439    let allocator = Allocator::default();
440    let ret = Parser::new(&allocator, source, source_type).parse();
441    let text = |span: oxc_span::Span| source[span.start as usize..span.end as usize].to_string();
442    let mut out = Vec::new();
443    for statement in &ret.program.body {
444        let declaration = match statement {
445            Statement::ExportDeclaration(export) => &export.declaration,
446            Statement::TSInterfaceDeclaration(_) | Statement::TSTypeAliasDeclaration(_) => {
447                match statement.as_declaration() {
448                    Some(d) => d,
449                    None => continue,
450                }
451            }
452            _ => continue,
453        };
454        match declaration {
455            Declaration::TSInterfaceDeclaration(d) => out.push(LocalType {
456                name: d.id.name.as_str().to_string(),
457                text: text(d.span),
458                alias: false,
459            }),
460            Declaration::TSTypeAliasDeclaration(d) => out.push(LocalType {
461                name: d.id.name.as_str().to_string(),
462                text: text(d.type_annotation.span()),
463                alias: d.type_parameters.is_none(),
464            }),
465            _ => {}
466        }
467    }
468    out
469}
470
471fn binding_name(pattern: &BindingPattern) -> Option<String> {
472    match pattern {
473        BindingPattern::BindingIdentifier(id) => Some(id.name.as_str().to_string()),
474        _ => None,
475    }
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481
482    #[test]
483    fn reads_function_and_arrow_exports() {
484        let found = exported_functions(
485            "a.ts",
486            "export function score(query: string, text: string): number { return 1 }\n\
487             export const words = (text: string, ...extra: string[]): string[] => []\n\
488             export async function load(path?: string, strict = false) {}\n\
489             function hidden() {}\n\
490             export const value = 1\n",
491        );
492        let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect();
493        assert_eq!(names, ["score", "words", "load"]);
494        assert_eq!(found[0].params[1].ts_type, "string");
495        assert_eq!(found[0].returns, "number");
496        assert_eq!(found[1].line, 2);
497        assert!(found[1].params[1].rest);
498        assert!(found[2].is_async && found[2].params[0].optional);
499        assert_eq!(
500            (
501                found[2].params[1].ts_type.as_str(),
502                found[2].params[1].optional
503            ),
504            ("boolean", true)
505        );
506        assert_eq!(found[2].returns, "unknown");
507    }
508
509    #[test]
510    fn reads_jsdoc_types_of_untyped_parameters() {
511        let found = exported_functions(
512            "m.js",
513            "/**\n * @param {string} source\n * @param {?number} [limit]\n * @returns {string[]}\n */\n\
514             export function parse(source, limit = 0) { return [] }\n\
515             /** @param {...string} parts */\n\
516             export const join = (...parts) => parts.join('')\n\
517             /** @param {function(string): number} f */\n\
518             export function apply(f, n = 1) {}\n",
519        );
520        let types = |i: usize| -> Vec<(&str, bool)> {
521            found[i]
522                .params
523                .iter()
524                .map(|p| (p.ts_type.as_str(), p.optional))
525                .collect()
526        };
527        assert_eq!(types(0), [("string", false), ("(number) | null", true)]);
528        assert_eq!(found[0].returns, "string[]");
529        assert_eq!(types(1), [("(string)[]", true)]);
530        assert_eq!(found[1].returns, "unknown");
531        assert_eq!(types(2), [("unknown", false), ("number", true)]);
532    }
533
534    #[test]
535    fn reads_classes() {
536        let classes = exported_classes(
537            "a.ts",
538            "export class Counter {\n  private lines: string[] = []\n  #seen = 0\n  constructor(initial: string, private readonly sep = '\\n') {}\n\
539             add(text: string): number { return 1 }\n  private hidden(): void {}\n  values(): string[] { return [] }\n}\n\
540             export class Box extends Counter { get size(): number { return 1 } static of(): Box { return new Box('') } }\n\
541             export class Point { x = 1\n  constructor(public y: number) {}\n  clone(): Point { return this } }\n",
542        );
543        assert_eq!(classes.len(), 3);
544        let counter = &classes[0];
545        assert_eq!(counter.blocker, None);
546        assert_eq!(counter.constructor.len(), 2);
547        assert_eq!(
548            counter
549                .methods
550                .iter()
551                .map(|m| m.name.as_str())
552                .collect::<Vec<_>>(),
553            ["add", "values"]
554        );
555        let blocked = classes[1].blocker.as_deref().unwrap();
556        assert!(
557            blocked.contains("extends")
558                && blocked.contains("accessor")
559                && blocked.contains("static")
560        );
561        let point = classes[2].blocker.as_deref().unwrap();
562        assert!(
563            point.contains("public field `x`")
564                && point.contains("parameter properties")
565                && point.contains("returns an instance")
566        );
567    }
568
569    #[test]
570    fn notices_instanceof() {
571        let found = exported_functions(
572            "a.ts",
573            "export function isErr(e: unknown): boolean { return e instanceof Error }\n\
574             export const plain = (instanceofCount: number): number => instanceofCount\n",
575        );
576        assert!(found[0].uses_instanceof);
577        assert!(!found[1].uses_instanceof);
578    }
579
580    #[test]
581    fn reads_local_types() {
582        let types = local_types(
583            "a.ts",
584            "export interface LineIndex { readonly line: (n: number) => string }\ntype Id = string\n",
585        );
586        let names: Vec<&str> = types.iter().map(|t| t.name.as_str()).collect();
587        assert_eq!(names, ["LineIndex", "Id"]);
588        assert!(types[0].text.contains("=>") && !types[0].alias);
589        assert_eq!((types[1].text.as_str(), types[1].alias), ("string", true));
590    }
591
592    #[test]
593    fn reads_export_lists() {
594        let found = exported_functions(
595            "a.js",
596            "function printDoc(doc, options) { return doc }\n\
597             const width = (text) => text.length\n\
598             function hidden() {}\n\
599             const value = 1\n\
600             export { printDoc, width as getWidth, value };\n",
601        );
602        let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect();
603        assert_eq!(names, ["printDoc", "getWidth"]);
604        assert_eq!(found[0].params.len(), 2);
605        assert_eq!(found[1].line, 2);
606    }
607}