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