1use serde::Serialize;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
7#[serde(rename_all = "kebab-case")]
8pub enum Risk {
9 StringOffsets,
10 RegexSyntax,
11 DynamicRegex,
12 DynamicCode,
13 DynamicTyping,
14 OrderedCollections,
15 Exceptions,
16 Async,
17 Generators,
18 ClassInheritance,
19 Reflection,
20 Callbacks,
21 NumberSemantics,
22 Json,
23 IntegerSemantics,
25 DivisionSemantics,
27 UnorderedIteration,
29 Pointers,
31 Concurrency,
33 NullReferences,
35 Monkeypatching,
37 AlreadyCompiled,
39 ArrayParameters,
41 PlatformSpecific,
44 ClockAndRandom,
46 PipelineOutput,
48 CaseInsensitive,
50 LooseConversion,
53 Intl,
55 DateParsing,
57 WebApis,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
62#[serde(rename_all = "lowercase")]
63pub enum Severity {
64 Low,
65 Medium,
66 High,
67}
68
69impl Severity {
70 pub fn weight(self) -> f64 {
71 match self {
72 Self::Low => 1.0,
73 Self::Medium => 3.0,
74 Self::High => 6.0,
75 }
76 }
77}
78
79impl Risk {
80 pub fn severity(self) -> Severity {
81 match self {
82 Self::StringOffsets | Self::RegexSyntax | Self::DynamicRegex | Self::DynamicCode => {
83 Severity::High
84 }
85 Self::DynamicTyping
86 | Self::OrderedCollections
87 | Self::Async
88 | Self::Generators
89 | Self::ClassInheritance
90 | Self::Reflection
91 | Self::Callbacks => Severity::Medium,
92 Self::Exceptions | Self::NumberSemantics | Self::Json | Self::ClockAndRandom => {
93 Severity::Low
94 }
95 Self::Pointers
96 | Self::Monkeypatching
97 | Self::UnorderedIteration
98 | Self::PlatformSpecific => Severity::High,
99 Self::IntegerSemantics
100 | Self::DivisionSemantics
101 | Self::Concurrency
102 | Self::NullReferences
103 | Self::AlreadyCompiled => Severity::Medium,
104 Self::ArrayParameters => Severity::High,
105 Self::PipelineOutput | Self::CaseInsensitive | Self::LooseConversion => {
106 Severity::Medium
107 }
108 Self::Intl | Self::DateParsing => Severity::High,
109 Self::WebApis => Severity::Medium,
110 }
111 }
112
113 pub fn title(self) -> &'static str {
114 match self {
115 Self::StringOffsets => "String offsets and slicing",
116 Self::RegexSyntax => "Regex features the `regex` crate lacks",
117 Self::DynamicRegex => "Regexes built at runtime",
118 Self::DynamicCode => "Dynamic code (eval, new Function, computed import)",
119 Self::DynamicTyping => "Dynamic typing",
120 Self::OrderedCollections => "Insertion-ordered maps and object keys",
121 Self::Exceptions => "Exceptions",
122 Self::Async => "Async and promises",
123 Self::Generators => "Generators",
124 Self::ClassInheritance => "Class inheritance",
125 Self::Reflection => "Reflection and prototypes",
126 Self::Callbacks => "Callback-shaped APIs",
127 Self::NumberSemantics => "Number semantics",
128 Self::Json => "JSON round-trips",
129 Self::IntegerSemantics => "Integer width and overflow",
130 Self::DivisionSemantics => "Division and modulo",
131 Self::UnorderedIteration => "Hash iteration order",
132 Self::Pointers => "Pointers and manual memory",
133 Self::Concurrency => "Concurrency",
134 Self::NullReferences => "Null references",
135 Self::Monkeypatching => "Runtime changes to code",
136 Self::AlreadyCompiled => "Already compiled (numba, Cython, JAX)",
137 Self::ArrayParameters => "numpy array parameters",
138 Self::PlatformSpecific => "Platform-specific C (asm, volatile, bitfields, packing)",
139 Self::ClockAndRandom => "Clock and random numbers",
140 Self::PipelineOutput => "Implicit output and the pipeline",
141 Self::CaseInsensitive => "Case-insensitive comparison",
142 Self::LooseConversion => "Implicit type conversion",
143 Self::Intl => "Intl and locale-aware strings",
144 Self::DateParsing => "Date parsing",
145 Self::WebApis => "URL and encoding APIs",
146 }
147 }
148
149 pub fn guidance(self) -> &'static str {
150 match self {
151 Self::StringOffsets => {
152 "Rust slices strings at UTF-8 byte offsets that fall on character boundaries. \
153 Convert offsets from the source's indexing units as needed and test with \
154 non-ASCII text."
155 }
156 Self::RegexSyntax => {
157 "Lookaround, backreferences and the `y` flag are not in the `regex` crate. Use \
158 `fancy-regex` for those patterns, or rewrite them, and test them on non-ASCII \
159 text: `\\w`, `\\b` and case-insensitive matching differ between engines even \
160 where a pattern compiles. JS `/i` without `u` never matches a non-ASCII letter to \
161 an ASCII one, Rust `(?i)` does (`ſ` matches `s`, the Kelvin sign `K` matches `k`): \
162 write `(?i-u)` or compare with `eq_ignore_ascii_case`."
163 }
164 Self::DynamicRegex => {
165 "Patterns come from data or config in JS syntax. Rust regex syntax differs, so \
166 user-visible behavior can change. Pin it with tests on real patterns."
167 }
168 Self::DynamicCode => {
169 "eval, new Function and computed imports have no Rust equivalent. Keep this part \
170 in JS or replace it with an explicit registry."
171 }
172 Self::DynamicTyping => {
173 "Values whose shape is checked at runtime need an explicit Rust enum or \
174 `serde_json::Value`."
175 }
176 Self::OrderedCollections => {
177 "JS Map, Set and object keys keep insertion order. `HashMap` does not: use \
178 `indexmap` wherever order reaches output. With serde_json's `preserve_order`, \
179 `Map::remove` swaps the last key into the hole: use `shift_remove` for JS `delete`. \
180 Sort with `js::sort` when a comparator can return NaN: the order then depends \
181 on V8's algorithm."
182 }
183 Self::Exceptions => {
184 "Represent source exceptions with `Result`. Preserve the original exception type \
185 and message when errors cross the bridge."
186 }
187 Self::Async => {
188 "Promises become futures. Bridge with napi-rs `async fn` or `wasm-bindgen-futures`, \
189 or keep the async shell in JS and port the sync core."
190 }
191 Self::Generators => {
192 "Lazy generators become iterators, or return a collected Vec across the bridge."
193 }
194 Self::ClassInheritance => {
195 "Class hierarchies become traits plus composition; `instanceof` checks become enums."
196 }
197 Self::Reflection => {
198 "Proxy, Reflect, Symbol and prototype tricks need a redesign, not a translation."
199 }
200 Self::Callbacks => {
201 "Function-typed parameters and methods cross the bridge on every call. Keep \
202 boundaries coarse: pass data in, get data out."
203 }
204 Self::NumberSemantics => {
205 "JS numbers are f64; bitwise ops truncate to i32; parseInt is lenient. Pick Rust \
206 integer types deliberately. Printing differs: `${n}` gives `1e+21`, `1e-7` and `0` \
207 for -0 where Rust's `{}` does not, so use `js::number_to_string`. `Math.round` \
208 rounds halves up (-2.5 gives -2), Rust's `round` away from zero: use \
209 `js::math_round`. `toFixed` rounds exact halves up ((2.5).toFixed(0) is \"3\"), \
210 Rust's `{:.0}` to even."
211 }
212 Self::Json => {
213 "JSON.stringify key order and number formatting must match `serde_json` output if \
214 the result is user-visible."
215 }
216 Self::IntegerSemantics => {
217 "Python ints never overflow; C, Go and Java ints wrap or are undefined on overflow. \
218 Pick i64, i128 or a bignum crate deliberately, and use wrapping_* where the source wraps."
219 }
220 Self::DivisionSemantics => {
221 "Python `//` and `%` floor toward negative infinity; Rust `/` and `%` truncate: use \
222 `div_euclid`/`rem_euclid` or explicit floor math. C division by zero is undefined."
223 }
224 Self::UnorderedIteration => {
225 "Set and map iteration order comes from the source language's hash function. A port \
226 cannot reproduce it: sort before output, or make the order part of the contract."
227 }
228 Self::Pointers => {
229 "Pointer arithmetic and manual memory become slices, indices and owned types. Code that \
230 exposes pointers across the boundary needs `unsafe`, isolated and explained."
231 }
232 Self::Concurrency => {
233 "Threads, goroutines and locks need a design in Rust (channels, Send/Sync), not a \
234 line-by-line translation; keep concurrency in the caller where possible."
235 }
236 Self::NullReferences => {
237 "Any reference may be null in the source: decide per parameter whether it is `Option` \
238 and what null means, instead of mapping every value to `Option`."
239 }
240 Self::Monkeypatching => {
241 "Code that rewrites classes or modules at runtime has no Rust equivalent: keep it in \
242 the source language and port the stable parts."
243 }
244 Self::AlreadyCompiled => {
245 "numba, Cython and JAX already compile this code to machine code (numba through \
246 LLVM, like Rust): a Rust port is unlikely to run much faster. Port it for a pure \
247 Rust app, not for speed, and profile first. Its floats may not match Rust's bit for \
248 bit (fastmath, operation order): record with `--float-tolerance`."
249 }
250 Self::ArrayParameters => {
251 "`record` passes JSON values, never numpy arrays, so a function that takes \
252 `np.ndarray` gets no valid cases on the unit path. Record the app instead \
253 (`app record`, `app replay`), or port the function together with a caller that \
254 takes and returns plain lists."
255 }
256 Self::PlatformSpecific => {
257 "This C depends on its target: register access, memory layout, the compiler's \
258 type sizes or its assembly. A recording on this machine says nothing about the \
259 target, and battle-tested driver or firmware code gains little from a rewrite: \
260 keep it in C and port the portable logic around it."
261 }
262 Self::ClockAndRandom => {
263 "Results that depend on the time or on random numbers differ on every run, so a \
264 plain recording cannot pin them down. Record with `record --pin-clock` (TS/JS with \
265 the napi bridge, Python): `Date.now()`, `new Date()` and `Math.random` (`time.time`, \
266 `datetime.now` and `random`) then return fixed values during record, diff and \
267 gate, and the port reads the same ones from `src/port/pinned.rs` (`now_ms()`, \
268 `random()`, a documented mulberry32). Or pass the time and the seed in as \
269 parameters."
270 }
271 Self::PipelineOutput => {
272 "Every value a PowerShell function does not assign or discard is output, not only \
273 what `return` names, and arrays unroll on the way out: no output reads as `$null`, \
274 one item as that item, `,@(x)` keeps the array. `$r = f ...` is what callers see, \
275 so the bridge records and compares that value; the port returns it whole (a `Vec` \
276 for several items). `Write-Host` text and non-terminating `Write-Error` records go \
277 to other streams: recorded as `output`, which a port cannot produce, so such cases \
278 fail until the function stops writing them."
279 }
280 Self::CaseInsensitive => {
281 "`-eq`, `-ne`, `-like`, `-match`, `-replace`, `-split`, `-contains`, `-in`, `switch` \
282 and `@{}` keys ignore case unless written `-ceq`, `-cmatch`, `switch -CaseSensitive`. \
283 Rust's `==`, `contains` and `HashMap` do not: compare with `eq_ignore_ascii_case` or \
284 `to_lowercase()` on both sides, write regexes with `(?i)`, and key maps by a folded \
285 string. Test with non-ASCII letters: .NET folds with invariant culture rules."
286 }
287 Self::LooseConversion => {
288 "PowerShell converts the right operand to the left one's type (`'10' -eq 10` is \
289 true, `10 -eq '10.0'` is true, `'a' + 1` is `a1`), `/` on two integers gives a \
290 double (`5 / 2` is 2.5), an `[int]` that overflows becomes a `[double]`, and `[int]` \
291 casts round halves to even (`[int]2.5` is 2). `$null -eq $x` and `$x -eq $null` \
292 differ when `$x` is an array (the second filters it). Write each conversion out in \
293 Rust and record cases at the edges."
294 }
295 Self::Intl => {
296 "`Intl.Segmenter`, `Intl.Collator`, `normalize` and the `toLocale*` methods run on \
297 the engine's ICU data. ICU4X (`icu_segmenter`, `icu_collator`, `icu_normalizer`) \
298 covers them, but engines still differ at the edges: V8 splits a katakana compound \
299 such as \"ドラゴンクエスト\" with its CJK dictionary where ICU4X keeps it whole. Record \
300 CJK, Thai and accented inputs, and list a difference you accept in \
301 `known-diffs.jsonl`."
302 }
303 Self::DateParsing => {
304 "`Date.parse` and `new Date(string)` accept implementation-defined formats: V8 \
305 takes `Wed, 25 Nov 2026 10:00:00 GMT`, `May 1, 21` and \
306 `Wed Sep 1 2021 08:43:51 (Coordinated Universal Time)`, rolls `2026-02-30` over \
307 to 2 March, and reads a date-time without a zone in local time. No crate parses \
308 the same set. Port the formats the data really holds, and test them with a \
309 generator of date strings, not only the recorded cases: dates inside other \
310 encodings rarely come out of `record` or `fuzz`."
311 }
312 Self::WebApis => {
313 "`new URL` and `URLSearchParams` follow the WHATWG URL standard: the `url` crate \
314 does too (`host` with a default port dropped, IDNA to Punycode, `query_pairs` for \
315 `searchParams`). `atob` validates its input before decoding, `TextDecoder` \
316 replaces bad UTF-8 and drops a leading BOM, `btoa` takes Latin-1: port each \
317 exactly, and record malformed inputs."
318 }
319 }
320 }
321}
322
323pub const REGEX_TRAPS: [&str; 12] = [
327 "Iı İi",
328 "K \u{212A} k",
329 "ſ s S",
330 "x\u{200D}y 👨\u{200D}👩\u{200D}👧",
331 "a\u{00A0}b\u{2009}c\u{3000}d",
332 "١٢٣ ٤٥",
333 "𝟘𝟙 ²³",
334 "snake_case foo-bar o'neil",
335 "Džungla DŽ",
336 "one\r\ntwo\u{2028}three\u{85}four",
337 "cafe\u{301} café",
338 "ΣΑΣ σας ς",
339];
340
341pub fn uses_regex(lang: crate::lang::Lang, source: &str) -> bool {
343 use crate::lang::Lang;
344 static JS_LITERAL: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
345 let has = |needles: &[&str]| needles.iter().any(|n| source.contains(n));
346 match lang {
347 Lang::Ts => {
348 has(&["RegExp("])
349 || JS_LITERAL
350 .get_or_init(|| {
351 regex::Regex::new(
352 r"(?:^|[=(,:!&|?{;]|return)\s*/[^/*\s\n][^/\n]*/[dgimsuyv]*",
353 )
354 .expect("valid regex")
355 })
356 .is_match(source)
357 }
358 Lang::Python => has(&[
359 "import re\n",
360 "import re ",
361 "from re import",
362 "import regex",
363 "re.compile(",
364 ]),
365 Lang::Ruby => has(&[
366 "=~", "Regexp", "%r{", ".match(", ".scan(/", ".gsub(/", ".sub(/", ".split(/",
367 ".match?(",
368 ]),
369 Lang::Go => has(&["\"regexp\""]),
370 Lang::Java => has(&[
371 "java.util.regex",
372 "Pattern.compile",
373 ".replaceAll(",
374 ".matches(",
375 ".split(",
376 ]),
377 Lang::Kotlin => has(&["kotlin.text.Regex", "Regex(", ".toRegex("]),
378 Lang::C => has(&["<regex.h>", "pcre", "regcomp("]),
379 Lang::Php => has(&["preg_", "mb_ereg"]),
380 Lang::Csharp => has(&["Regex", "RegularExpressions"]),
381 Lang::Powershell => {
382 let lower = source.to_ascii_lowercase();
383 ["-match", "-replace", "-split", "[regex]", "select-string"]
384 .iter()
385 .any(|n| lower.contains(n))
386 }
387 }
388}
389
390pub fn compiled_by(decorator: &str) -> Option<&'static str> {
393 let d = decorator.trim().trim_start_matches('@');
394 let name = d.split('(').next().unwrap_or(d).trim();
395 if name.starts_with("cython.") {
396 return Some("Cython");
397 }
398 let (module, last) = name.rsplit_once('.').map_or(("", name), |(m, l)| (m, l));
399 if module == "jax" || module.starts_with("jax.") {
400 return (last == "jit").then_some("JAX");
401 }
402 let numba_module = matches!(module, "" | "numba" | "nb" | "cuda" | "numba.cuda");
403 let numba_name = matches!(
404 last,
405 "jit" | "njit" | "vectorize" | "guvectorize" | "cfunc" | "stencil" | "generated_jit"
406 );
407 (numba_module && numba_name).then_some("numba")
408}
409
410pub fn python_compiled(source: &str) -> Vec<(String, u32, &'static str)> {
412 let mut out = Vec::new();
413 let (mut pending, mut depth) = (None, 0i32);
414 for (i, line) in source.lines().enumerate() {
415 let t = line.trim_start();
416 if depth > 0 {
417 depth += paren_balance(t);
418 continue;
419 }
420 if let Some(rest) = t.strip_prefix('@') {
421 pending = pending.or(compiled_by(rest));
422 depth = paren_balance(t).max(0);
423 } else if let Some(def) = t
424 .strip_prefix("def ")
425 .or_else(|| t.strip_prefix("async def "))
426 {
427 if let Some(by) = pending.take() {
428 let name = def.split(['(', ':']).next().unwrap_or("").trim();
429 out.push((name.to_string(), (i + 1) as u32, by));
430 }
431 } else if !t.is_empty() && !t.starts_with('#') {
432 pending = None;
433 }
434 }
435 out
436}
437
438fn paren_balance(line: &str) -> i32 {
439 line.chars().fold(0, |n, c| match c {
440 '(' => n + 1,
441 ')' => n - 1,
442 _ => n,
443 })
444}
445
446pub fn regex_folds_differently(pattern: &str, flags: &str) -> bool {
449 if !flags.contains('i') || flags.contains('u') || flags.contains('v') {
450 return false;
451 }
452 let mut escaped = false;
453 pattern.chars().any(|c| {
454 let letter = !escaped && matches!(c, 's' | 'S' | 'k' | 'K');
455 escaped = !escaped && c == '\\';
456 letter
457 })
458}
459
460pub fn regex_needs_fancy(pattern: &str, flags: &str) -> bool {
462 if flags.contains('y') {
463 return true;
464 }
465 if ["(?=", "(?!", "(?<=", "(?<!", "\\k<"]
466 .iter()
467 .any(|needle| pattern.contains(needle))
468 {
469 return true;
470 }
471 let bytes = pattern.as_bytes();
472 let mut in_class = false;
473 let mut i = 0;
474 while i < bytes.len() {
475 match bytes[i] {
476 b'\\' => {
477 if !in_class && bytes.get(i + 1).is_some_and(|b| (b'1'..=b'9').contains(b)) {
478 return true;
479 }
480 i += 1;
481 }
482 b'[' => in_class = true,
483 b']' => in_class = false,
484 _ => {}
485 }
486 i += 1;
487 }
488 false
489}
490
491#[cfg(test)]
492mod tests {
493 use super::{
494 compiled_by, python_compiled, regex_folds_differently, regex_needs_fancy, uses_regex,
495 };
496
497 #[test]
498 fn detects_case_folds_rust_widens() {
499 assert!(regex_folds_differently("^(ms|secs?)$", "i"));
500 assert!(regex_folds_differently("K", "gi"));
501 assert!(!regex_folds_differently("secs?", "iu"));
502 assert!(!regex_folds_differently("secs?", "g"));
503 assert!(!regex_folds_differently("\\s+\\d", "i"));
504 assert!(!regex_folds_differently("abc", "i"));
505 }
506 use crate::lang::Lang;
507
508 #[test]
509 fn finds_regex_use() {
510 assert!(uses_regex(Lang::Ts, "const re = /\\w+/gu;"));
511 assert!(uses_regex(Lang::Ts, "return s.replace(/[^a-z]/g, '')"));
512 assert!(uses_regex(Lang::Ts, "new RegExp(p, 'i')"));
513 assert!(!uses_regex(Lang::Ts, "const half = a / b / 2;"));
514 assert!(!uses_regex(Lang::Ts, "// a comment\nconst x = 1;"));
515 assert!(uses_regex(
516 Lang::Python,
517 "import re\n\ndef f(s):\n return re.sub('a', 'b', s)\n"
518 ));
519 assert!(!uses_regex(Lang::Python, "import requests\n"));
520 assert!(uses_regex(Lang::Go, "import \"regexp\""));
521 assert!(uses_regex(Lang::Ruby, "s =~ /a/"));
522 assert!(uses_regex(Lang::Java, "Pattern.compile(\"a+\")"));
523 assert!(uses_regex(Lang::C, "#include <regex.h>"));
524 }
525
526 #[test]
527 fn finds_compiled_python() {
528 assert_eq!(compiled_by("@njit"), Some("numba"));
529 assert_eq!(
530 compiled_by("@numba.jit(nopython=True, cache=True)"),
531 Some("numba")
532 );
533 assert_eq!(compiled_by("@nb.vectorize(['f8(f8)'])"), Some("numba"));
534 assert_eq!(compiled_by("@cuda.jit"), Some("numba"));
535 assert_eq!(compiled_by("@cython.cfunc"), Some("Cython"));
536 assert_eq!(compiled_by("@jax.jit"), Some("JAX"));
537 assert_eq!(compiled_by("@functools.lru_cache"), None);
538 assert_eq!(compiled_by("@app.jit_route"), None);
539 let src = "import numba\n\n@numba.njit(\n cache=True,\n)\ndef step(x, dt):\n return x + dt\n\n@staticmethod\ndef plain():\n pass\n\n@property\n@njit\ndef energy(s):\n return s\n";
540 assert_eq!(
541 python_compiled(src),
542 [
543 ("step".to_string(), 6, "numba"),
544 ("energy".to_string(), 15, "numba")
545 ]
546 );
547 }
548
549 #[test]
550 fn detects_unsupported_regex_features() {
551 assert!(regex_needs_fancy("(?<=a)b", ""));
552 assert!(regex_needs_fancy("(a)\\1", ""));
553 assert!(regex_needs_fancy("a", "y"));
554 assert!(!regex_needs_fancy("[\\w\\d]+?", "g"));
555 assert!(!regex_needs_fancy("(?<name>x)", "d"));
556 assert!(!regex_needs_fancy("[\\1]", ""));
557 }
558}