Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

fix(analyze): risk guide words division and number semantics for the unit's language (#1234)

Orca09a5435d940b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9593f186..0f7bdd4c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -100,6 +100,11 @@
- `docs/STATUS.md`, `CONTRIBUTING.md` and the site's PHP and C# pages say the macOS CI job
installs and requires PHP, .NET and Kotlin, so their tests run in CI there and skip on Linux and
Windows. Before, they said no CI job installed them (#1209, #1219 by @Alkhanizi-hashem).
+- The risk guide under `analyze` words "Division and modulo" and "Number semantics" for the
+ language analyzed: the floor fix is for Python and Ruby only, and C# `decimal`, PHP `/` and
+ Python bitwise operators get their own advice. Before, every language read Python's `//` advice
+ and the JS number advice, so a Go user who followed it broke a port that was right (#1197 by
+ @og-orca).
- The contributor guide lists every integration suite. A test checks the list for missing entries
(#1193, #1224 by @Plastic-time).
- `gate`'s `size` check can allow one unit more than 3x the original's lines, with a reason a
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index cadf4b07..d7d5a740 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -295,7 +295,7 @@ bad it usually is and gives one example. The severities are the ones `analyze` s
| Number semantics | low | TS/JS `number`, bitwise operators, `Math.round`, `Math.sin`/`pow`/`exp`/`log` and the other transcendental functions (last digit differs from libm), `toFixed`, `toPrecision`, `toString(radix)`, `parseInt`/`parseFloat` (and `Number.parseInt`/`Number.parseFloat`); Python bitwise operators; PHP `/`; C# `decimal` |
| JSON round-trips | low | TS/JS `JSON`, Ruby, PHP, Go `encoding/json`, PowerShell `ConvertTo-Json`: key order, `undefined`, `NaN` |
| Integer width and overflow | medium | Python, Ruby and PHP `**` and `<<`; Java, Kotlin, C# shifts, `*` and hash codes; Go and C shifts and conversions: wrap vs panic |
-| Division and modulo | medium | Python, Ruby, PHP, Java, Kotlin, C#, Go, C: `/` and `%` on negatives, Python `//` (floor division: `div_euclid` is not it for a negative divisor); Python `"..." % args` is string formatting and not counted |
+| Division and modulo | medium | Python `//` and `%` and Ruby integer `/` and `%` floor (`div_euclid` is not it for a negative divisor); Java, Kotlin, C#, Go, C integer `/` and `%` and PHP `%`, `intdiv` and `fmod` truncate like Rust, so a zero divisor and `MIN / -1` are what is left; Python `"..." % args` is string formatting and not counted |
| Hash iteration order | high | Python `set`; Java and Kotlin `HashMap`/`HashSet` (also through `import java.util.*`); C# `Dictionary`/`HashSet`; Go `map` range (also over a variable declared as a map); PowerShell `@{}` hashtables |
| Pointers and manual memory | high | C pointers, `malloc`, `memcpy`; Go `unsafe` and pointer types; C# `unsafe` |
| Concurrency | medium | Go goroutines and `sync`, Java and Kotlin threads and `synchronized`, C# `lock` and `System.Threading`, Python, Ruby, PHP and C threads, PowerShell `Start-ThreadJob` |
diff --git a/src/report.rs b/src/report.rs
index 7cb62be5..cf58caec 100644
--- a/src/report.rs
+++ b/src/report.rs
@@ -286,7 +286,7 @@ fn render(out: &mut String, r: &Report, title: &str) -> std::fmt::Result {
"- **{}** ({:?}): {}",
risk.title(),
risk.severity(),
- risk.guidance()
+ risk.guidance_for(r.language)
)?;
}
Ok(())
@@ -354,6 +354,8 @@ fn status_label(status: Status) -> &'static str {
#[cfg(test)]
mod tests {
use super::{count, markdown};
+ use crate::lang::Lang;
+ use crate::risks::Risk;
#[test]
fn one_is_singular_and_everything_else_plural() {
@@ -384,4 +386,149 @@ mod tests {
assert!(guide.contains("- **Exceptions**"), "{guide}");
assert!(!guide.contains("JS"), "{guide}");
}
+
+ fn risk_guide(files: &[(&str, &str)], lang: Lang) -> String {
+ let root = crate::app::temp_dir("risk-guide").unwrap();
+ for (name, body) in files {
+ std::fs::write(root.join(name), body).unwrap();
+ }
+ let report = crate::analyze::analyze_lang(&root, lang).unwrap();
+ std::fs::remove_dir_all(root).unwrap();
+ let plan = markdown(&report, "text");
+ let (_, guide) = plan.split_once("## Risk guide\n").unwrap();
+ guide.to_string()
+ }
+
+ fn entry<'a>(guide: &'a str, title: &str) -> &'a str {
+ guide
+ .lines()
+ .find(|l| l.starts_with(&format!("- **{title}**")))
+ .unwrap_or_else(|| panic!("no {title} in {guide}"))
+ }
+
+ const GO_DIV: &str =
+ "package app\n\nfunc Div(a, b int) (int, error) {\n\treturn a / b, nil\n}\n";
+ const PY_DIV: &str = "def half(a: int, b: int) -> int:\n return a // b\n";
+
+ #[test]
+ fn go_division_guide_says_truncate_and_leaves_out_python_floor_division() {
+ let guide = risk_guide(
+ &[("go.mod", "module x\n\ngo 1.22\n"), ("a.go", GO_DIV)],
+ Lang::Go,
+ );
+ let division = entry(&guide, "Division and modulo");
+ assert!(division.contains("truncate"), "{division}");
+ assert!(division.contains("`wrapping_div`"), "{division}");
+ assert!(!division.contains("//"), "{division}");
+ assert!(!division.contains("floor toward"), "{division}");
+ assert!(!division.contains("Python"), "{division}");
+ }
+
+ #[test]
+ fn python_division_guide_keeps_the_floor_fix() {
+ let guide = risk_guide(&[("a.py", PY_DIV)], Lang::Python);
+ let division = entry(&guide, "Division and modulo");
+ assert!(
+ division.contains("Python integer `//` and `%` floor"),
+ "{division}"
+ );
+ assert!(division.contains("(a < 0) != (b < 0)"), "{division}");
+ assert!(!division.contains("Ruby"), "{division}");
+ }
+
+ #[test]
+ fn a_folder_with_go_and_python_gets_the_guide_of_the_language_analyzed() {
+ let files = [
+ ("go.mod", "module x\n\ngo 1.22\n"),
+ ("a.go", GO_DIV),
+ ("a.py", PY_DIV),
+ ];
+ let go = risk_guide(&files, Lang::Go);
+ let python = risk_guide(&files, Lang::Python);
+ assert!(!entry(&go, "Division and modulo").contains("//"), "{go}");
+ assert!(
+ entry(&python, "Division and modulo").contains("`//`"),
+ "{python}"
+ );
+ }
+
+ #[test]
+ fn csharp_decimal_guide_leaves_out_javascript_number_advice() {
+ let guide = risk_guide(
+ &[(
+ "Money.cs",
+ "public static class Money\n{\n public static decimal Double(decimal d) => d * 2;\n}\n",
+ )],
+ Lang::Csharp,
+ );
+ let number = entry(&guide, "Number semantics");
+ assert!(number.contains("`decimal`"), "{number}");
+ for js in ["parseInt", "toFixed", "Math.round", "js::", "JS numbers"] {
+ assert!(!number.contains(js), "{js} in {number}");
+ }
+ }
+
+ #[test]
+ fn number_guide_names_the_language_that_raised_it() {
+ let py = risk_guide(
+ &[("a.py", "def mask(a: int) -> int:\n return a & 255\n")],
+ Lang::Python,
+ );
+ let number = entry(&py, "Number semantics");
+ assert!(number.contains("Python ints have no width"), "{number}");
+ assert!(!number.contains("parseInt"), "{number}");
+
+ let php = risk_guide(
+ &[(
+ "a.php",
+ "<?php\nfunction half($a, $b) { return $a / $b; }\n",
+ )],
+ Lang::Php,
+ );
+ let number = entry(&php, "Number semantics");
+ assert!(number.contains("`7 / 2` is `3.5`"), "{number}");
+ assert!(!number.contains("toFixed"), "{number}");
+
+ let ts = risk_guide(
+ &[("a.ts", "export const n = (s: string) => parseInt(s);\n")],
+ Lang::Ts,
+ );
+ assert!(
+ entry(&ts, "Number semantics").contains("js::number_to_string"),
+ "{ts}"
+ );
+ }
+
+ #[test]
+ fn every_division_language_gets_text_for_its_own_semantics() {
+ for lang in [Lang::Python, Lang::Ruby] {
+ let text = Risk::DivisionSemantics.guidance_for(lang);
+ assert!(text.contains("floor toward negative infinity"), "{text}");
+ assert!(text.contains(lang.name()), "{text}");
+ }
+ for lang in [
+ Lang::C,
+ Lang::Go,
+ Lang::Java,
+ Lang::Kotlin,
+ Lang::Csharp,
+ Lang::Php,
+ ] {
+ let text = Risk::DivisionSemantics.guidance_for(lang);
+ assert!(text.starts_with(lang.name()), "{text}");
+ assert!(text.contains("truncate toward zero"), "{text}");
+ assert!(
+ !text.contains("//") && !text.contains("floor toward"),
+ "{text}"
+ );
+ }
+ for lang in [Lang::Go, Lang::Java, Lang::Kotlin, Lang::Csharp] {
+ let text = Risk::DivisionSemantics.guidance_for(lang);
+ assert!(text.contains("at the source's width"), "{text}");
+ }
+ let php = Risk::DivisionSemantics.guidance_for(Lang::Php);
+ assert!(php.contains("then use `wrapping_rem`"), "{php}");
+ let neutral = Risk::DivisionSemantics.guidance_for(Lang::Swift);
+ assert_eq!(neutral, Risk::DivisionSemantics.guidance());
+ }
}
diff --git a/src/risks.rs b/src/risks.rs
index 324e8fe2..ed6a03fc 100644
--- a/src/risks.rs
+++ b/src/risks.rs
@@ -1,7 +1,11 @@
//! The catalog of source-language behaviors to account for when porting to Rust.
+use std::borrow::Cow;
+
use serde::Serialize;
+use crate::lang::Lang;
+
/// A construct whose source-language semantics differ from the obvious Rust translation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "kebab-case")]
@@ -224,12 +228,8 @@ impl Risk {
boundaries coarse: pass data in, get data out."
}
Self::NumberSemantics => {
- "JS numbers are f64; bitwise ops truncate to i32; parseInt is lenient. Pick Rust \
- integer types deliberately. Printing differs: `${n}` gives `1e+21`, `1e-7` and `0` \
- for -0 where Rust's `{}` does not, so use `js::number_to_string`. `Math.round` \
- rounds halves up (-2.5 gives -2), Rust's `round` away from zero: use \
- `js::math_round`. `toFixed` rounds exact halves up ((2.5).toFixed(0) is \"3\"), \
- Rust's `{:.0}` to even."
+ "Numbers differ between languages in width, rounding, parsing and printing. Pick \
+ Rust types deliberately and record values at the edges."
}
Self::Json => {
"JSON.stringify key order and number formatting must match `serde_json` output if \
@@ -240,12 +240,9 @@ impl Risk {
Pick i64, i128 or a bignum crate deliberately, and use wrapping_* where the source wraps."
}
Self::DivisionSemantics => {
- "Python `//` and `%` floor toward negative infinity (the remainder takes the sign \
- of the divisor); Rust `/` and `%` truncate. `div_euclid` and `rem_euclid` equal \
- the floor forms only for a positive divisor (`7.div_euclid(-2)` is -3, Python's \
- `7 // -2` is -4): write `q = a / b; if a % b != 0 && (a < 0) != (b < 0) { q - 1 }` \
- and `r = a % b; if r != 0 && (r < 0) != (b < 0) { r + b }`, and record negative \
- divisors. C division by zero is undefined."
+ "Languages differ in rounding, the sign of the remainder, a zero divisor and \
+ `MIN / -1`. Rust `/` and `%` truncate toward zero, the remainder takes the sign of \
+ the dividend, and integers panic on a zero divisor and on `MIN / -1`."
}
Self::UnorderedIteration => {
"Set and map iteration order comes from the source language's hash function. A port \
@@ -385,6 +382,129 @@ impl Risk {
}
}
}
+
+ /// The guidance for a unit of `lang`. Division and number semantics differ too much between
+ /// languages for one text, so they get one per language. Every other risk reads the same.
+ pub fn guidance_for(self, lang: Lang) -> Cow<'static, str> {
+ match (self, lang) {
+ (Self::NumberSemantics, Lang::Ts) => Cow::Borrowed(
+ "JS numbers are f64; bitwise ops truncate to i32; parseInt is lenient. Pick Rust \
+ integer types deliberately. Printing differs: `${n}` gives `1e+21`, `1e-7` and `0` \
+ for -0 where Rust's `{}` does not, so use `js::number_to_string`. `Math.round` \
+ rounds halves up (-2.5 gives -2), Rust's `round` away from zero: use \
+ `js::math_round`. `toFixed` rounds exact halves up ((2.5).toFixed(0) is \"3\"), \
+ Rust's `{:.0}` to even.",
+ ),
+ (Self::NumberSemantics, Lang::Python) => Cow::Borrowed(
+ "Python ints have no width: `&`, `|`, `^` and `>>` work on any size and read a \
+ negative number as two's complement with endless sign bits (`(1 << 70) | 1` is \
+ exact). A Rust integer has a fixed width: pick `i64`, `i128` or a bignum crate \
+ deliberately, and test negative values and values past 64 bits.",
+ ),
+ (Self::NumberSemantics, Lang::Php) => Cow::Borrowed(
+ "PHP `/` gives an int when both operands are ints, or numeric strings that read \
+ as ints, and divide exactly (`6 / 3` and `\"6\" / \"3\"` are `2`), and a float \
+ otherwise (`7 / 2` is `3.5`), where Rust's `/` on two integers truncates. Decide \
+ the result type per call, and record exact and inexact divisions. \
+ `PHP_INT_MIN / -1` is a float, and a zero divisor throws DivisionByZeroError.",
+ ),
+ (Self::NumberSemantics, Lang::Csharp) => Cow::Borrowed(
+ "C# `decimal` is a base-10 type with 28 to 29 digits: `0.1m + 0.2m` is exactly \
+ `0.3m` and `1.10m` keeps its trailing zero. Rust has no such built-in type, and \
+ no JSON number or `f64` keeps it exactly. `bridge` refuses a `decimal` in a \
+ signature: keep that method in C#, or pass the value as a string through a wrapper \
+ and use `rust_decimal` inside the port.",
+ ),
+ (Self::DivisionSemantics, Lang::Python | Lang::Ruby) => {
+ let (ops, example, floats) = if lang == Lang::Python {
+ (
+ "`//` and `%`",
+ "Python's `7 // -2`",
+ "Floats floor too, but the formulas are for ints: `1.0 // 0.1` is 9.0 where \
+ `(1.0 / 0.1).floor()` is 10. A zero divisor raises ZeroDivisionError for \
+ ints and floats, where Rust panics for ints and gives an infinity or NaN \
+ for floats.",
+ )
+ } else {
+ (
+ "`/` and `%`",
+ "Ruby's `7 / -2`",
+ "The quotient formula is for integers: a float `/` does not floor, and by \
+ zero it gives an infinity or NaN. A float `%` floors too (`-7.5 % 2` is \
+ 0.5). An integer zero divisor raises ZeroDivisionError, where Rust panics.",
+ )
+ };
+ Cow::Owned(format!(
+ "{lang} integer {ops} floor toward negative infinity and the remainder takes \
+ the sign of the divisor. Rust `/` and `%` truncate. `div_euclid` and \
+ `rem_euclid` equal the floor forms only for a positive divisor \
+ (`7.div_euclid(-2)` is -3, {example} is -4): write \
+ `q = a / b; if a % b != 0 && (a < 0) != (b < 0) {{ q - 1 }}` and \
+ `r = a % b; if r != 0 && (r < 0) != (b < 0) {{ r + b }}`, and record negative \
+ divisors. {floats} Ints never overflow in {lang}, but `i64::MIN / -1` and \
+ `i64::MIN % -1` panic in Rust: use `checked_div` for the first and \
+ `wrapping_rem` for the second, whose answer is 0.",
+ lang = lang.name(),
+ ))
+ }
+ (
+ Self::DivisionSemantics,
+ Lang::C | Lang::Go | Lang::Java | Lang::Kotlin | Lang::Csharp | Lang::Php,
+ ) => {
+ let ops = match lang {
+ Lang::Php => "`%`, `intdiv` and `fmod`",
+ _ => "integer `/` and `%`",
+ };
+ let edges = match lang {
+ Lang::C => {
+ "Integer division by zero and `INT_MIN / -1` (also `INT_MIN % -1`) are \
+ undefined behavior in C, and Rust panics on them: check the divisor first, \
+ or use `checked_div` and `checked_rem`. A `short` or `char` divides as \
+ `int`: widen it first."
+ }
+ Lang::Go => {
+ "An integer zero divisor panics in Go: return `Err`, since `wrapping_div` \
+ panics on it too. The most negative value divided by -1 wraps to itself \
+ and its remainder is 0, where Rust panics: use `wrapping_div` and \
+ `wrapping_rem` at the source's width (`i8` for `int8`, `i32` for `int32`, \
+ and `i64` for `int`, or `i32` on a 32-bit target). Float division by zero \
+ gives an infinity or NaN, as in Rust."
+ }
+ Lang::Java | Lang::Kotlin => {
+ "An integer zero divisor throws ArithmeticException: return `Err`, since \
+ `wrapping_div` panics on it too. `MIN_VALUE / -1` wraps to `MIN_VALUE` and \
+ `MIN_VALUE % -1` is 0, where Rust panics: use `wrapping_div` and \
+ `wrapping_rem` at the source's width (`i32` for an int, short or byte, \
+ since Java and Kotlin divide those as int, and `i64` for a long). Float \
+ division by zero gives an infinity or NaN, as in Rust."
+ }
+ Lang::Csharp => {
+ "An integer or `decimal` zero divisor throws DivideByZeroException, and \
+ `int.MinValue / -1` and `int.MinValue % -1` throw OverflowException on \
+ .NET, also in `unchecked`: return `Err` for both, with `checked_div` and \
+ `checked_rem` at the source's width (`i32` for `int`, `short` and `sbyte`, \
+ which C# divides as `int`, and `i64` for `long`). `double` and `float` \
+ division by zero gives an infinity or NaN, as in Rust."
+ }
+ _ => {
+ "A zero divisor throws DivisionByZeroError for `%` and `intdiv`, and \
+ `intdiv(PHP_INT_MIN, -1)` throws ArithmeticError: use `checked_div` and map \
+ `None` to the error the source threw. `PHP_INT_MIN % -1` is 0, where Rust \
+ panics and `checked_rem` gives `None`: check for a zero divisor, then use \
+ `wrapping_rem`. `%` turns float operands into ints first. `fmod` with a \
+ zero divisor gives NAN, as `%` on `f64` does."
+ }
+ };
+ Cow::Owned(format!(
+ "{lang} {ops} truncate toward zero and the remainder takes the sign of the \
+ dividend, like Rust: do not add a floor correction or switch to `div_euclid`, \
+ each changes some results when an operand is negative. {edges}",
+ lang = lang.name(),
+ ))
+ }
+ _ => Cow::Borrowed(self.guidance()),
+ }
+ }
}
/// Strings where regex engines disagree most: `\\w`, `\\d`, `\\s` and `\\b` on non-ASCII,