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_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    "buffer",
75    "child_process",
76    "crypto",
77    "events",
78    "fs",
79    "fs/promises",
80    "http",
81    "https",
82    "module",
83    "net",
84    "os",
85    "path",
86    "perf_hooks",
87    "process",
88    "readline",
89    "stream",
90    "tty",
91    "url",
92    "util",
93    "v8",
94    "vm",
95    "worker_threads",
96    "zlib",
97];
98const UI_PACKAGES: &[&str] = &[
99    "vue",
100    "react",
101    "react-dom",
102    "preact",
103    "solid-js",
104    "svelte",
105    "nuxt",
106    "#app",
107    "#imports",
108    "vue-router",
109];
110
111/// The platform an import specifier pins a file to, if any.
112pub fn platform_of(specifier: &str) -> Option<Platform> {
113    if specifier.starts_with("node:") || NODE_BUILTINS.contains(&specifier) {
114        Some(Platform::Node)
115    } else if specifier == "vscode" {
116        Some(Platform::Editor)
117    } else if UI_PACKAGES.contains(&specifier) {
118        Some(Platform::Ui)
119    } else {
120        None
121    }
122}
123
124/// Parses one file and collects its facts. Never fails: syntax errors are counted.
125pub fn scan(path: &str, source: &str) -> FileFacts {
126    let source_type = SourceType::from_path(path).unwrap_or_else(|_| SourceType::ts());
127    let allocator = Allocator::default();
128    let ret = Parser::new(&allocator, source, source_type).parse();
129    let mut collector = Collector {
130        line_starts: std::iter::once(0)
131            .chain(
132                source
133                    .match_indices('\n')
134                    .map(|(i, _)| u32::try_from(i + 1).unwrap_or(u32::MAX)),
135            )
136            .collect(),
137        facts: FileFacts {
138            loc: source.lines().filter(|l| !l.trim().is_empty()).count(),
139            parse_errors: ret.diagnostics.len(),
140            ..FileFacts::default()
141        },
142    };
143    collector.visit_program(&ret.program);
144    for import in &collector.facts.imports {
145        if let Some(platform) = platform_of(&import.specifier) {
146            collector.facts.platforms.insert(platform);
147        }
148    }
149    collector.facts
150}
151
152struct Collector {
153    line_starts: Vec<u32>,
154    facts: FileFacts,
155}
156
157impl Collector {
158    fn line(&self, span: Span) -> u32 {
159        u32::try_from(self.line_starts.partition_point(|&s| s <= span.start)).unwrap_or(u32::MAX)
160    }
161
162    fn add(&mut self, risk: Risk, span: Span) {
163        let line = self.line(span);
164        self.facts.risks.entry(risk).or_default().push(line);
165    }
166
167    fn import(&mut self, specifier: String, type_only: bool, dynamic: bool) {
168        self.facts.imports.push(Import {
169            specifier,
170            type_only,
171            dynamic,
172        });
173    }
174
175    fn check_regex(&mut self, pattern: &str, flags: &str, span: Span) {
176        if regex_needs_fancy(pattern, flags) {
177            self.add(Risk::RegexSyntax, span);
178        }
179        if flags.contains('d') {
180            self.add(Risk::StringOffsets, span);
181        }
182    }
183}
184
185fn identifier<'a>(expr: &Expression<'a>) -> Option<&'a str> {
186    match expr {
187        Expression::Identifier(id) => Some(id.name.as_str()),
188        _ => None,
189    }
190}
191
192fn string_arg(arg: Option<&Argument>) -> Option<String> {
193    match arg {
194        Some(Argument::StringLiteral(s)) => Some(s.value.display().to_string()),
195        _ => None,
196    }
197}
198
199impl<'a> Visit<'a> for Collector {
200    fn visit_import_declaration(&mut self, it: &ImportDeclaration<'a>) {
201        self.import(
202            it.source.value.display().to_string(),
203            it.import_kind.is_type(),
204            false,
205        );
206        walk::walk_import_declaration(self, it);
207    }
208
209    fn visit_export_from_declaration(&mut self, it: &ExportFromDeclaration<'a>) {
210        self.import(
211            it.source.value.display().to_string(),
212            it.export_kind.is_type(),
213            false,
214        );
215        walk::walk_export_from_declaration(self, it);
216    }
217
218    fn visit_export_all_declaration(&mut self, it: &ExportAllDeclaration<'a>) {
219        self.import(
220            it.source.value.display().to_string(),
221            it.export_kind.is_type(),
222            false,
223        );
224        walk::walk_export_all_declaration(self, it);
225    }
226
227    fn visit_import_expression(&mut self, it: &ImportExpression<'a>) {
228        match &it.source {
229            Expression::StringLiteral(s) => self.import(s.value.display().to_string(), false, true),
230            _ => self.add(Risk::DynamicCode, it.span),
231        }
232        walk::walk_import_expression(self, it);
233    }
234
235    fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
236        match &it.callee {
237            Expression::StaticMemberExpression(member) => {
238                let property = member.property.name.as_str();
239                match (identifier(&member.object), property) {
240                    (Some("JSON"), _) => self.add(Risk::Json, it.span),
241                    (Some("Object"), "keys" | "values" | "entries" | "fromEntries") => {
242                        self.add(Risk::OrderedCollections, it.span);
243                    }
244                    (
245                        Some("Object"),
246                        "defineProperty" | "getPrototypeOf" | "setPrototypeOf" | "freeze",
247                    )
248                    | (Some("Reflect"), _) => self.add(Risk::Reflection, it.span),
249                    (Some("Promise"), _) => self.add(Risk::Async, it.span),
250                    (_, "matchAll" | "exec") => self.add(Risk::StringOffsets, it.span),
251                    (_, method) if STRING_OFFSET_METHODS.contains(&method) => {
252                        self.add(Risk::StringOffsets, it.span);
253                    }
254                    _ => {}
255                }
256            }
257            Expression::Identifier(id) => match id.name.as_str() {
258                "eval" => self.add(Risk::DynamicCode, it.span),
259                "parseInt" | "parseFloat" => self.add(Risk::NumberSemantics, it.span),
260                "require" => match string_arg(it.arguments.first()) {
261                    Some(specifier) => self.import(specifier, false, true),
262                    None => self.add(Risk::DynamicCode, it.span),
263                },
264                "RegExp" => {
265                    self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span)
266                }
267                _ => {}
268            },
269            _ => {}
270        }
271        walk::walk_call_expression(self, it);
272    }
273
274    fn visit_new_expression(&mut self, it: &NewExpression<'a>) {
275        match identifier(&it.callee) {
276            Some("RegExp") => {
277                self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span);
278            }
279            Some("Map" | "Set") => self.add(Risk::OrderedCollections, it.span),
280            Some("Function") => self.add(Risk::DynamicCode, it.span),
281            Some("Proxy" | "WeakRef" | "FinalizationRegistry") => {
282                self.add(Risk::Reflection, it.span);
283            }
284            Some("Promise") => self.add(Risk::Async, it.span),
285            _ => {}
286        }
287        walk::walk_new_expression(self, it);
288    }
289
290    fn visit_static_member_expression(&mut self, it: &StaticMemberExpression<'a>) {
291        if matches!(it.property.name.as_str(), "indices" | "lastIndex") {
292            self.add(Risk::StringOffsets, it.span);
293        }
294        walk::walk_static_member_expression(self, it);
295    }
296
297    fn visit_reg_exp_literal(&mut self, it: &RegExpLiteral<'a>) {
298        let flags = it.regex.flags.to_string();
299        self.check_regex(it.regex.pattern.text.as_str(), &flags, it.span);
300    }
301
302    fn visit_throw_statement(&mut self, it: &ThrowStatement<'a>) {
303        self.add(Risk::Exceptions, it.span);
304        walk::walk_throw_statement(self, it);
305    }
306
307    fn visit_try_statement(&mut self, it: &TryStatement<'a>) {
308        self.add(Risk::Exceptions, it.span);
309        walk::walk_try_statement(self, it);
310    }
311
312    fn visit_await_expression(&mut self, it: &AwaitExpression<'a>) {
313        self.add(Risk::Async, it.span);
314        walk::walk_await_expression(self, it);
315    }
316
317    fn visit_function(&mut self, it: &Function<'a>, flags: ScopeFlags) {
318        if it.generator {
319            self.add(Risk::Generators, it.span);
320        }
321        if it.r#async {
322            self.add(Risk::Async, it.span);
323        }
324        walk::walk_function(self, it, flags);
325    }
326
327    fn visit_arrow_function_expression(&mut self, it: &ArrowFunctionExpression<'a>) {
328        if it.r#async {
329            self.add(Risk::Async, it.span);
330        }
331        walk::walk_arrow_function_expression(self, it);
332    }
333
334    fn visit_yield_expression(&mut self, it: &YieldExpression<'a>) {
335        self.add(Risk::Generators, it.span);
336        walk::walk_yield_expression(self, it);
337    }
338
339    fn visit_class(&mut self, it: &Class<'a>) {
340        if it.heritage.is_some() {
341            self.add(Risk::ClassInheritance, it.span);
342        }
343        walk::walk_class(self, it);
344    }
345
346    fn visit_for_in_statement(&mut self, it: &ForInStatement<'a>) {
347        self.facts.loops += 1;
348        self.add(Risk::OrderedCollections, it.span);
349        walk::walk_for_in_statement(self, it);
350    }
351
352    fn visit_for_of_statement(&mut self, it: &ForOfStatement<'a>) {
353        self.facts.loops += 1;
354        walk::walk_for_of_statement(self, it);
355    }
356
357    fn visit_for_statement(&mut self, it: &ForStatement<'a>) {
358        self.facts.loops += 1;
359        walk::walk_for_statement(self, it);
360    }
361
362    fn visit_while_statement(&mut self, it: &WhileStatement<'a>) {
363        self.facts.loops += 1;
364        walk::walk_while_statement(self, it);
365    }
366
367    fn visit_do_while_statement(&mut self, it: &DoWhileStatement<'a>) {
368        self.facts.loops += 1;
369        walk::walk_do_while_statement(self, it);
370    }
371
372    fn visit_binary_expression(&mut self, it: &BinaryExpression<'a>) {
373        if it.operator.is_bitwise() {
374            self.add(Risk::NumberSemantics, it.span);
375        } else if it.operator.is_in() {
376            self.add(Risk::DynamicTyping, it.span);
377        }
378        walk::walk_binary_expression(self, it);
379    }
380
381    fn visit_ts_any_keyword(&mut self, it: &TSAnyKeyword) {
382        self.add(Risk::DynamicTyping, it.span);
383    }
384
385    fn visit_ts_function_type(&mut self, it: &TSFunctionType<'a>) {
386        self.add(Risk::Callbacks, it.span);
387        walk::walk_ts_function_type(self, it);
388    }
389
390    fn visit_ts_method_signature(&mut self, it: &TSMethodSignature<'a>) {
391        self.add(Risk::Callbacks, it.span);
392        walk::walk_ts_method_signature(self, it);
393    }
394
395    fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) {
396        let name = it.name.as_str();
397        if BROWSER_GLOBALS.contains(&name) {
398            self.facts.platforms.insert(Platform::Browser);
399        } else if NODE_GLOBALS.contains(&name) {
400            self.facts.platforms.insert(Platform::Node);
401        } else if name == "Symbol" {
402            self.add(Risk::Reflection, it.span);
403        }
404    }
405}
406
407impl Collector {
408    fn regexp_constructor(
409        &mut self,
410        pattern: Option<&Argument>,
411        flags: Option<&Argument>,
412        span: Span,
413    ) {
414        match string_arg(pattern) {
415            Some(pattern) => {
416                let flags = string_arg(flags).unwrap_or_default();
417                self.check_regex(&pattern, &flags, span);
418            }
419            None => self.add(Risk::DynamicRegex, span),
420        }
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427
428    #[test]
429    fn collects_imports_platforms_and_risks() {
430        let facts = scan(
431            "a.ts",
432            "import { readFile } from 'node:fs'\n\
433             import type { X } from './types'\n\
434             export * from './util.js'\n\
435             const re = /(?<=a)b/g\n\
436             const dyn = new RegExp(input)\n\
437             export function f(s: string) { return s.slice(1) }\n\
438             const m = new Map()\n",
439        );
440        let specifiers: Vec<_> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
441        assert_eq!(specifiers, ["node:fs", "./types", "./util.js"]);
442        assert!(facts.imports[1].type_only);
443        assert!(facts.platforms.contains(&Platform::Node));
444        assert_eq!(facts.risks[&Risk::RegexSyntax], [4]);
445        assert_eq!(facts.risks[&Risk::DynamicRegex], [5]);
446        assert_eq!(facts.risks[&Risk::StringOffsets], [6]);
447        assert_eq!(facts.risks[&Risk::OrderedCollections], [7]);
448        assert_eq!(facts.parse_errors, 0);
449    }
450}