1use 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#[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 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
111pub 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
124pub 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) || regex_folds_differently(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 (Some("Math"), "round") | (_, "toFixed") => {
251 self.add(Risk::NumberSemantics, it.span);
252 }
253 (_, "matchAll" | "exec") => self.add(Risk::StringOffsets, it.span),
254 (_, method) if STRING_OFFSET_METHODS.contains(&method) => {
255 self.add(Risk::StringOffsets, it.span);
256 }
257 _ => {}
258 }
259 }
260 Expression::Identifier(id) => match id.name.as_str() {
261 "eval" => self.add(Risk::DynamicCode, it.span),
262 "parseInt" | "parseFloat" => self.add(Risk::NumberSemantics, it.span),
263 "require" => match string_arg(it.arguments.first()) {
264 Some(specifier) => self.import(specifier, false, true),
265 None => self.add(Risk::DynamicCode, it.span),
266 },
267 "RegExp" => {
268 self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span)
269 }
270 _ => {}
271 },
272 _ => {}
273 }
274 walk::walk_call_expression(self, it);
275 }
276
277 fn visit_new_expression(&mut self, it: &NewExpression<'a>) {
278 match identifier(&it.callee) {
279 Some("RegExp") => {
280 self.regexp_constructor(it.arguments.first(), it.arguments.get(1), it.span);
281 }
282 Some("Map" | "Set") => self.add(Risk::OrderedCollections, it.span),
283 Some("Function") => self.add(Risk::DynamicCode, it.span),
284 Some("Proxy" | "WeakRef" | "FinalizationRegistry") => {
285 self.add(Risk::Reflection, it.span);
286 }
287 Some("Promise") => self.add(Risk::Async, it.span),
288 _ => {}
289 }
290 walk::walk_new_expression(self, it);
291 }
292
293 fn visit_static_member_expression(&mut self, it: &StaticMemberExpression<'a>) {
294 if matches!(it.property.name.as_str(), "indices" | "lastIndex") {
295 self.add(Risk::StringOffsets, it.span);
296 }
297 walk::walk_static_member_expression(self, it);
298 }
299
300 fn visit_reg_exp_literal(&mut self, it: &RegExpLiteral<'a>) {
301 let flags = it.regex.flags.to_string();
302 self.check_regex(it.regex.pattern.text.as_str(), &flags, it.span);
303 }
304
305 fn visit_throw_statement(&mut self, it: &ThrowStatement<'a>) {
306 self.add(Risk::Exceptions, it.span);
307 walk::walk_throw_statement(self, it);
308 }
309
310 fn visit_try_statement(&mut self, it: &TryStatement<'a>) {
311 self.add(Risk::Exceptions, it.span);
312 walk::walk_try_statement(self, it);
313 }
314
315 fn visit_await_expression(&mut self, it: &AwaitExpression<'a>) {
316 self.add(Risk::Async, it.span);
317 walk::walk_await_expression(self, it);
318 }
319
320 fn visit_function(&mut self, it: &Function<'a>, flags: ScopeFlags) {
321 if it.generator {
322 self.add(Risk::Generators, it.span);
323 }
324 if it.r#async {
325 self.add(Risk::Async, it.span);
326 }
327 walk::walk_function(self, it, flags);
328 }
329
330 fn visit_arrow_function_expression(&mut self, it: &ArrowFunctionExpression<'a>) {
331 if it.r#async {
332 self.add(Risk::Async, it.span);
333 }
334 walk::walk_arrow_function_expression(self, it);
335 }
336
337 fn visit_yield_expression(&mut self, it: &YieldExpression<'a>) {
338 self.add(Risk::Generators, it.span);
339 walk::walk_yield_expression(self, it);
340 }
341
342 fn visit_class(&mut self, it: &Class<'a>) {
343 if it.heritage.is_some() {
344 self.add(Risk::ClassInheritance, it.span);
345 }
346 walk::walk_class(self, it);
347 }
348
349 fn visit_for_in_statement(&mut self, it: &ForInStatement<'a>) {
350 self.facts.loops += 1;
351 self.add(Risk::OrderedCollections, it.span);
352 walk::walk_for_in_statement(self, it);
353 }
354
355 fn visit_for_of_statement(&mut self, it: &ForOfStatement<'a>) {
356 self.facts.loops += 1;
357 walk::walk_for_of_statement(self, it);
358 }
359
360 fn visit_for_statement(&mut self, it: &ForStatement<'a>) {
361 self.facts.loops += 1;
362 walk::walk_for_statement(self, it);
363 }
364
365 fn visit_while_statement(&mut self, it: &WhileStatement<'a>) {
366 self.facts.loops += 1;
367 walk::walk_while_statement(self, it);
368 }
369
370 fn visit_do_while_statement(&mut self, it: &DoWhileStatement<'a>) {
371 self.facts.loops += 1;
372 walk::walk_do_while_statement(self, it);
373 }
374
375 fn visit_binary_expression(&mut self, it: &BinaryExpression<'a>) {
376 if it.operator.is_bitwise() {
377 self.add(Risk::NumberSemantics, it.span);
378 } else if it.operator.is_in() {
379 self.add(Risk::DynamicTyping, it.span);
380 }
381 walk::walk_binary_expression(self, it);
382 }
383
384 fn visit_ts_any_keyword(&mut self, it: &TSAnyKeyword) {
385 self.add(Risk::DynamicTyping, it.span);
386 }
387
388 fn visit_ts_function_type(&mut self, it: &TSFunctionType<'a>) {
389 self.add(Risk::Callbacks, it.span);
390 walk::walk_ts_function_type(self, it);
391 }
392
393 fn visit_ts_method_signature(&mut self, it: &TSMethodSignature<'a>) {
394 self.add(Risk::Callbacks, it.span);
395 walk::walk_ts_method_signature(self, it);
396 }
397
398 fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) {
399 let name = it.name.as_str();
400 if BROWSER_GLOBALS.contains(&name) {
401 self.facts.platforms.insert(Platform::Browser);
402 } else if NODE_GLOBALS.contains(&name) {
403 self.facts.platforms.insert(Platform::Node);
404 } else if name == "Symbol" {
405 self.add(Risk::Reflection, it.span);
406 }
407 }
408}
409
410impl Collector {
411 fn regexp_constructor(
412 &mut self,
413 pattern: Option<&Argument>,
414 flags: Option<&Argument>,
415 span: Span,
416 ) {
417 match string_arg(pattern) {
418 Some(pattern) => {
419 let flags = string_arg(flags).unwrap_or_default();
420 self.check_regex(&pattern, &flags, span);
421 }
422 None => self.add(Risk::DynamicRegex, span),
423 }
424 }
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430
431 #[test]
432 fn collects_imports_platforms_and_risks() {
433 let facts = scan(
434 "a.ts",
435 "import { readFile } from 'node:fs'\n\
436 import type { X } from './types'\n\
437 export * from './util.js'\n\
438 const re = /(?<=a)b/g\n\
439 const dyn = new RegExp(input)\n\
440 export function f(s: string) { return s.slice(1) }\n\
441 const m = new Map()\n",
442 );
443 let specifiers: Vec<_> = facts.imports.iter().map(|i| i.specifier.as_str()).collect();
444 assert_eq!(specifiers, ["node:fs", "./types", "./util.js"]);
445 assert!(facts.imports[1].type_only);
446 assert!(facts.platforms.contains(&Platform::Node));
447 assert_eq!(facts.risks[&Risk::RegexSyntax], [4]);
448 assert_eq!(facts.risks[&Risk::DynamicRegex], [5]);
449 assert_eq!(facts.risks[&Risk::StringOffsets], [6]);
450 assert_eq!(facts.risks[&Risk::OrderedCollections], [7]);
451 assert_eq!(facts.parse_errors, 0);
452 }
453
454 #[test]
455 fn flags_rounding_and_ascii_case_folds() {
456 let facts = scan(
457 "ms.ts",
458 "const re = /^(\\d+) *(secs?|ms)$/i\n\
459 export const r = (x: number) => Math.round(x)\n\
460 export const f = (x: number) => x.toFixed(2)\n",
461 );
462 assert_eq!(facts.risks[&Risk::RegexSyntax], [1]);
463 assert_eq!(facts.risks[&Risk::NumberSemantics], [2, 3]);
464 }
465}