Skip to main content

rust_anything/ts/
scan.rs

1//! Per-file facts from the oxc AST: imports, platform use, migration risks.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use oxc_allocator::Allocator;
6use oxc_ast::ast::{
7    Argument, ArrowFunctionExpression, AwaitExpression, BinaryExpression, CallExpression, Class,
8    DoWhileStatement, ExportAllDeclaration, ExportFromDeclaration, Expression, ForInStatement,
9    ForOfStatement, ForStatement, Function, IdentifierReference, ImportDeclaration,
10    ImportExpression, NewExpression, RegExpLiteral, StaticMemberExpression, TSAnyKeyword,
11    TSFunctionType, TSMethodSignature, ThrowStatement, TryStatement, WhileStatement,
12    YieldExpression,
13};
14use oxc_ast_visit::{Visit, walk};
15use oxc_parser::Parser;
16use oxc_span::{SourceType, Span};
17use oxc_syntax::scope::ScopeFlags;
18use serde::Serialize;
19
20use crate::risks::{Risk, regex_folds_differently, regex_needs_fancy};
21
22/// A runtime a file depends on directly.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
24#[serde(rename_all = "kebab-case")]
25pub enum Platform {
26    Node,
27    Browser,
28    Editor,
29    Ui,
30}
31
32#[derive(Clone, Debug, Serialize)]
33pub struct Import {
34    pub specifier: String,
35    pub type_only: bool,
36    pub dynamic: bool,
37}
38
39#[derive(Debug, Default, Serialize)]
40pub struct FileFacts {
41    pub loc: usize,
42    pub imports: Vec<Import>,
43    /// Lines (1-based) where each risk shows up.
44    pub risks: BTreeMap<Risk, Vec<u32>>,
45    pub platforms: BTreeSet<Platform>,
46    pub loops: usize,
47    pub parse_errors: usize,
48}
49
50const STRING_OFFSET_METHODS: &[&str] = &[
51    "slice",
52    "substring",
53    "substr",
54    "charAt",
55    "charCodeAt",
56    "codePointAt",
57    "indexOf",
58    "lastIndexOf",
59    "padStart",
60    "padEnd",
61];
62const BROWSER_GLOBALS: &[&str] = &[
63    "window",
64    "document",
65    "navigator",
66    "localStorage",
67    "sessionStorage",
68    "location",
69    "HTMLElement",
70];
71const NODE_GLOBALS: &[&str] = &["process", "Buffer", "__dirname", "__filename"];
72const NODE_BUILTINS: &[&str] = &[
73    "assert",
74    "async_hooks",
75    "buffer",
76    "child_process",
77    "cluster",
78    "console",
79    "constants",
80    "crypto",
81    "dgram",
82    "diagnostics_channel",
83    "dns",
84    "domain",
85    "events",
86    "fs",
87    "http",
88    "http2",
89    "https",
90    "inspector",
91    "module",
92    "net",
93    "os",
94    "path",
95    "perf_hooks",
96    "process",
97    "punycode",
98    "querystring",
99    "readline",
100    "repl",
101    "stream",
102    "string_decoder",
103    "sys",
104    "timers",
105    "tls",
106    "trace_events",
107    "tty",
108    "url",
109    "util",
110    "v8",
111    "vm",
112    "wasi",
113    "worker_threads",
114    "zlib",
115];
116const UI_PACKAGES: &[&str] = &[
117    "vue",
118    "react",
119    "react-dom",
120    "preact",
121    "solid-js",
122    "svelte",
123    "nuxt",
124    "#app",
125    "#imports",
126    "vue-router",
127];
128
129/// The platform an import specifier pins a file to, if any. A Node subpath is the same builtin
130/// (`stream/web`, `util/types`, `fs/promises`), so the builtin list is matched on the package root;
131/// a subpath of anything else stays what its root says it is.
132pub fn platform_of(specifier: &str) -> Option<Platform> {
133    let root = specifier.split('/').next().unwrap_or(specifier);
134    if specifier.starts_with("node:") || NODE_BUILTINS.contains(&root) {
135        Some(Platform::Node)
136    } else if specifier == "vscode" {
137        Some(Platform::Editor)
138    } else if UI_PACKAGES.contains(&specifier) {
139        Some(Platform::Ui)
140    } else {
141        None
142    }
143}
144
145/// Parses one file and collects its facts. Never fails: syntax errors are counted.
146pub fn scan(path: &str, source: &str) -> FileFacts {
147    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
148    let allocator = Allocator::default();
149    let ret = Parser::new(&allocator, source, source_type).parse();
150    let mut collector = Collector {
151        line_starts: std::iter::once(0)
152            .chain(
153                source
154                    .match_indices('\n')
155                    .map(|(i, _)| u32::try_from(i + 1).unwrap_or(u32::MAX)),
156            )
157            .collect(),
158        facts: FileFacts {
159            loc: source.lines().filter(|l| !l.trim().is_empty()).count(),
160            parse_errors: ret.diagnostics.len(),
161            ..FileFacts::default()
162        },
163    };
164    collector.visit_program(&ret.program);
165    for import in &collector.facts.imports {
166        if let Some(platform) = platform_of(&import.specifier) {
167            collector.facts.platforms.insert(platform);
168        }
169    }
170    collector.facts
171}
172
173struct Collector {
174    line_starts: Vec<u32>,
175    facts: FileFacts,
176}
177
178impl Collector {
179    fn line(&self, span: Span) -> u32 {
180        u32::try_from(self.line_starts.partition_point(|&s| s <= span.start)).unwrap_or(u32::MAX)
181    }
182
183    fn add(&mut self, risk: Risk, span: Span) {
184        let line = self.line(span);
185        self.facts.risks.entry(risk).or_default().push(line);
186    }
187
188    fn import(&mut self, specifier: String, type_only: bool, dynamic: bool) {
189        self.facts.imports.push(Import {
190            specifier,
191            type_only,
192            dynamic,
193        });
194    }
195
196    fn check_regex(&mut self, pattern: &str, flags: &str, span: Span) {
197        if regex_needs_fancy(pattern, flags) || regex_folds_differently(pattern, flags) {
198            self.add(Risk::RegexSyntax, span);
199        }
200        if flags.contains('d') {
201            self.add(Risk::StringOffsets, span);
202        }
203    }
204}
205
206fn identifier<'a>(expr: &Expression<'a>) -> Option<&'a str> {
207    match expr {
208        Expression::Identifier(id) => Some(id.name.as_str()),
209        _ => None,
210    }
211}
212
213fn string_arg(arg: Option<&Argument>) -> Option<String> {
214    match arg {
215        Some(Argument::StringLiteral(s)) => Some(s.value.display().to_string()),
216        _ => None,
217    }
218}
219
220impl<'a> Visit<'a> for Collector {
221    fn visit_import_declaration(&mut self, it: &ImportDeclaration<'a>) {
222        self.import(
223            it.source.value.display().to_string(),
224            it.import_kind.is_type(),
225            false,
226        );
227        walk::walk_import_declaration(self, it);
228    }
229
230    fn visit_export_from_declaration(&mut self, it: &ExportFromDeclaration<'a>) {
231        self.import(
232            it.source.value.display().to_string(),
233            it.export_kind.is_type(),
234            false,
235        );
236        walk::walk_export_from_declaration(self, it);
237    }
238
239    fn visit_export_all_declaration(&mut self, it: &ExportAllDeclaration<'a>) {
240        self.import(
241            it.source.value.display().to_string(),
242            it.export_kind.is_type(),
243            false,
244        );
245        walk::walk_export_all_declaration(self, it);
246    }
247
248    fn visit_import_expression(&mut self, it: &ImportExpression<'a>) {
249        match &it.source {
250            Expression::StringLiteral(s) => self.import(s.value.display().to_string(), false, true),
251            _ => self.add(Risk::DynamicCode, it.span),
252        }
253        walk::walk_import_expression(self, it);
254    }
255
256    fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
257        match &it.callee {
258            Expression::StaticMemberExpression(member) => {
259                let property = member.property.name.as_str();
260                match (identifier(&member.object), property) {
261                    (Some("JSON"), _) => self.add(Risk::Json, it.span),
262                    (Some("Object"), "keys" | "values" | "entries" | "fromEntries") => {
263                        self.add(Risk::OrderedCollections, it.span);
264                    }
265                    (
266                        Some("Object"),
267                        "defineProperty" | "getPrototypeOf" | "setPrototypeOf" | "freeze",
268                    )
269                    | (Some("Reflect"), _) => self.add(Risk::Reflection, it.span),
270                    (Some("Promise"), _) => self.add(Risk::Async, it.span),
271                    (Some("Math"), "random")
272                    | (Some("Date" | "performance"), "now")
273                    | (Some("crypto"), "randomUUID" | "getRandomValues") => {
274                        self.add(Risk::ClockAndRandom, it.span);
275                    }
276                    (Some("Math"), "round") | (_, "toFixed") => {
277                        self.add(Risk::NumberSemantics, it.span);
278                    }
279                    (_, "matchAll" | "exec") => self.add(Risk::StringOffsets, it.span),
280                    (_, method) if STRING_OFFSET_METHODS.contains(&method) => {
281                        self.add(Risk::StringOffsets, it.span);
282                    }
283                    _ => {}
284                }
285            }
286            Expression::Identifier(id) => match id.name.as_str() {
287                "eval" => self.add(Risk::DynamicCode, it.span),
288                "Date" => self.add(Risk::ClockAndRandom, it.span),
289                "parseInt" | "parseFloat" => self.add(Risk::NumberSemantics, it.span),
290                "require" => match string_arg(it.arguments.first()) {
291                    Some(specifier) => self.import(specifier, false, true),
292                    None => self.add(Risk::DynamicCode, it.span),
293                },
294                "RegExp" => {
295                    self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span)
296                }
297                _ => {}
298            },
299            _ => {}
300        }
301        walk::walk_call_expression(self, it);
302    }
303
304    fn visit_new_expression(&mut self, it: &NewExpression<'a>) {
305        match identifier(&it.callee) {
306            Some("RegExp") => {
307                self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span);
308            }
309            Some("Map" | "Set") => self.add(Risk::OrderedCollections, it.span),
310            Some("Date") if it.arguments.is_empty() => self.add(Risk::ClockAndRandom, it.span),
311            Some("Function") => self.add(Risk::DynamicCode, it.span),
312            Some("Proxy" | "WeakRef" | "FinalizationRegistry") => {
313                self.add(Risk::Reflection, it.span);
314            }
315            Some("Promise") => self.add(Risk::Async, it.span),
316            _ => {}
317        }
318        walk::walk_new_expression(self, it);
319    }
320
321    fn visit_static_member_expression(&mut self, it: &StaticMemberExpression<'a>) {
322        if matches!(it.property.name.as_str(), "indices" | "lastIndex") {
323            self.add(Risk::StringOffsets, it.span);
324        }
325        walk::walk_static_member_expression(self, it);
326    }
327
328    fn visit_reg_exp_literal(&mut self, it: &RegExpLiteral<'a>) {
329        let flags = it.regex.flags.to_string();
330        self.check_regex(it.regex.pattern.text.as_str(), &flags, it.span);
331    }
332
333    fn visit_throw_statement(&mut self, it: &ThrowStatement<'a>) {
334        self.add(Risk::Exceptions, it.span);
335        walk::walk_throw_statement(self, it);
336    }
337
338    fn visit_try_statement(&mut self, it: &TryStatement<'a>) {
339        self.add(Risk::Exceptions, it.span);
340        walk::walk_try_statement(self, it);
341    }
342
343    fn visit_await_expression(&mut self, it: &AwaitExpression<'a>) {
344        self.add(Risk::Async, it.span);
345        walk::walk_await_expression(self, it);
346    }
347
348    fn visit_function(&mut self, it: &Function<'a>, flags: ScopeFlags) {
349        if it.generator {
350            self.add(Risk::Generators, it.span);
351        }
352        if it.r#async {
353            self.add(Risk::Async, it.span);
354        }
355        walk::walk_function(self, it, flags);
356    }
357
358    fn visit_arrow_function_expression(&mut self, it: &ArrowFunctionExpression<'a>) {
359        if it.r#async {
360            self.add(Risk::Async, it.span);
361        }
362        walk::walk_arrow_function_expression(self, it);
363    }
364
365    fn visit_yield_expression(&mut self, it: &YieldExpression<'a>) {
366        self.add(Risk::Generators, it.span);
367        walk::walk_yield_expression(self, it);
368    }
369
370    fn visit_class(&mut self, it: &Class<'a>) {
371        if it.heritage.is_some() {
372            self.add(Risk::ClassInheritance, it.span);
373        }
374        walk::walk_class(self, it);
375    }
376
377    fn visit_for_in_statement(&mut self, it: &ForInStatement<'a>) {
378        self.facts.loops += 1;
379        self.add(Risk::OrderedCollections, it.span);
380        walk::walk_for_in_statement(self, it);
381    }
382
383    fn visit_for_of_statement(&mut self, it: &ForOfStatement<'a>) {
384        self.facts.loops += 1;
385        walk::walk_for_of_statement(self, it);
386    }
387
388    fn visit_for_statement(&mut self, it: &ForStatement<'a>) {
389        self.facts.loops += 1;
390        walk::walk_for_statement(self, it);
391    }
392
393    fn visit_while_statement(&mut self, it: &WhileStatement<'a>) {
394        self.facts.loops += 1;
395        walk::walk_while_statement(self, it);
396    }
397
398    fn visit_do_while_statement(&mut self, it: &DoWhileStatement<'a>) {
399        self.facts.loops += 1;
400        walk::walk_do_while_statement(self, it);
401    }
402
403    fn visit_binary_expression(&mut self, it: &BinaryExpression<'a>) {
404        if it.operator.is_bitwise() {
405            self.add(Risk::NumberSemantics, it.span);
406        } else if it.operator.is_in() {
407            self.add(Risk::DynamicTyping, it.span);
408        }
409        walk::walk_binary_expression(self, it);
410    }
411
412    fn visit_ts_any_keyword(&mut self, it: &TSAnyKeyword) {
413        self.add(Risk::DynamicTyping, it.span);
414    }
415
416    fn visit_ts_function_type(&mut self, it: &TSFunctionType<'a>) {
417        self.add(Risk::Callbacks, it.span);
418        walk::walk_ts_function_type(self, it);
419    }
420
421    fn visit_ts_method_signature(&mut self, it: &TSMethodSignature<'a>) {
422        self.add(Risk::Callbacks, it.span);
423        walk::walk_ts_method_signature(self, it);
424    }
425
426    fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) {
427        let name = it.name.as_str();
428        if BROWSER_GLOBALS.contains(&name) {
429            self.facts.platforms.insert(Platform::Browser);
430        } else if NODE_GLOBALS.contains(&name) {
431            self.facts.platforms.insert(Platform::Node);
432        } else if name == "Symbol" {
433            self.add(Risk::Reflection, it.span);
434        }
435    }
436}
437
438impl Collector {
439    fn regexp_constructor(
440        &mut self,
441        pattern: Option<&Argument>,
442        flags: Option<&Argument>,
443        span: Span,
444    ) {
445        match string_arg(pattern) {
446            Some(pattern) => {
447                let flags = string_arg(flags).unwrap_or_default();
448                self.check_regex(&pattern, &flags, span);
449            }
450            None => self.add(Risk::DynamicRegex, span),
451        }
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    #[test]
460    fn collects_imports_platforms_and_risks() {
461        let facts = scan(
462            "a.ts",
463            "import { readFile } from 'node:fs'\n\
464             import type { X } from './types'\n\
465             export * from './util.js'\n\
466             const re = /(?<=a)b/g\n\
467             const dyn = new RegExp(input)\n\
468             export function f(s: string) { return s.slice(1) }\n\
469             const m = new Map()\n",
470        );
471        let specifiers: Vec<_> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
472        assert_eq!(specifiers, ["node:fs", "./types", "./util.js"]);
473        assert!(facts.imports[1].type_only);
474        assert!(facts.platforms.contains(&Platform::Node));
475        assert_eq!(facts.risks[&Risk::RegexSyntax], [4]);
476        assert_eq!(facts.risks[&Risk::DynamicRegex], [5]);
477        assert_eq!(facts.risks[&Risk::StringOffsets], [6]);
478        assert_eq!(facts.risks[&Risk::OrderedCollections], [7]);
479        assert_eq!(facts.parse_errors, 0);
480    }
481
482    #[test]
483    fn flags_rounding_and_ascii_case_folds() {
484        let facts = scan(
485            "ms.ts",
486            "const re = /^(\\d+) *(secs?|ms)$/i\n\
487             export const r = (x: number) => Math.round(x)\n\
488             export const f = (x: number) => x.toFixed(2)\n",
489        );
490        assert_eq!(facts.risks[&Risk::RegexSyntax], [1]);
491        assert_eq!(facts.risks[&Risk::NumberSemantics], [2, 3]);
492    }
493
494    #[test]
495    fn a_subpath_names_the_same_builtin() {
496        // A Node subpath is the same module, and every builtin counts, not the ones a fixture
497        // happened to import.
498        for spec in [
499            "stream/web",
500            "util/types",
501            "dns/promises",
502            "fs/promises",
503            "node:fs/promises",
504            "tls",
505            "http2",
506            "querystring",
507            "string_decoder",
508            "wasi",
509        ] {
510            assert_eq!(platform_of(spec), Some(Platform::Node), "{spec}");
511        }
512        // A subpath of a third-party or UI package stays what its root says it is.
513        assert_eq!(platform_of("react/jsx-runtime"), None);
514        assert_eq!(platform_of("@scope/pkg/sub"), None);
515        assert_eq!(platform_of("path-to-regexp"), None);
516        assert_eq!(platform_of("left-pad"), None);
517        assert_eq!(platform_of("vscode"), Some(Platform::Editor));
518        assert_eq!(platform_of("svelte/store"), None);
519    }
520}