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