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