Skip to main content

rust_anything/
risks.rs

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