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