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