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