Skip to main content

rust_anything/
risks.rs

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