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.

24.4 KB
Raw Blame

Language plugins part 1: Python, C, Go, Java, shared syntax (audit id A6a)

Scope and coverage ledger

Read in full (every line, in chunks):

File Lines Read
src/lang/mod.rs 430 1-430
src/lang/syntax.rs 519 1-519
src/lang/python.rs 2033 1-2033 (the 300-line STDLIB table read as a list, then grepped for gaps)
src/lang/c.rs 1337 1-1337
src/lang/go.rs 1052 1-1052
src/lang/java.rs 960 1-960
tests/java_package_declaration.rs 54 all
tests/java_replay.rs 513 all
tests/go_internal_packages.rs, go_mod_directives.rs, go_module_paths.rs, go_record_cgo.rs, go_unsigned.rs 50, 68, 58, 61, 106 all
tests/c_pointers.rs, tests/c_structs.rs 288, 381 all

Also read for context: docs/how-it-works.md, DECISIONS.md (Known limits, M8), docs/pitfalls.md, parts of src/harness_c.rs (param kinds, 440-543). Not read: bridge.rs, codegen_*, harness_* beyond what is cited.

Experiments: I copied target/debug/rust-anything (v5.0.2; it may not be exactly HEAD) to my scratch dir and ran analyze, analyze --whole-app, bridge and record on tiny repos under /tmp/claude-0/-home-user-rust-anything/3155f14a-830f-5883-9a8b-e7611d724b3a/scratchpad/A6a/ (py, py2..py7, go, go2, c, java, java2, java3). I never ran cargo, so no port was built or diffed. Where I say "a no-op port would pass", this is inferred from the recorded cases.jsonl (every case has "ok": null), not from a built port.

Summary

  • The biggest hole is not in a parser but in what the plugins call "bridgeable". Any function that communicates by mutating an argument (Python/Go/Java void/None function over a list) is exported with no blocker, and the recording stores "ok": null for every case. A port that does nothing passes diff, and enable then wires a bridge whose callers' lists are never mutated (A6a-01).
  • Type mapping narrows silently in three places: Python infer_numbers turns int(s), float(s) and s * n params into number so no string is ever recorded (A6a-02); C treats every mutable non-byte pointer as a one-cell "out" scalar and every const char * as NUL-terminated even when followed by a length, so arrays and overreads are recorded as UB garbage and SIGSEGV "expected results" (A6a-03); Go named types, cross-file structs and structs with pointer fields become unknown with no blocker, so the recording never reaches their branches (A6a-04).
  • Risk scans are exact-text matchers and miss spelled-differently code (from re import sub, from random import randint, import java.util.*, Go range counts), so analyze shows readiness 100 and no risk on code with lookbehind regexes (A6a-05 to A6a-07).
  • Failure is silent in several places: a file with a parse error is still bridged (functions dropped or mangled, no warning from bridge), C functions under #ifdef vanish, an unparsable pyproject.toml is "no dependencies" (A6a-08, A6a-09, A6a-10).
  • Int widths are handled better than expected (Python big ints, Go unsigned, Java overflow are recorded and kept).

Findings by severity: CRITICAL 1, HIGH 3, MEDIUM 6, LOW 4 (plus 2 WEAK).

Findings

A6a-01 [H1] [CRITICAL] [CONFIRMED] Functions that mutate their arguments are bridged as pure; recording keeps only null

  • Where: src/lang/python.rs:1297-1355 (function, blockers only for *args, callables, decorators), src/lang/go.rs:435-562, src/lang/java.rs:498-639. No plugin looks at whether a void/None function writes to a container parameter. DECISIONS.md:111 records the limit only for shadow mode, not for record/diff/enable.
  • What happens: sort_in_place(xs: list[int]) -> None, Go func SortInPlace(xs []int), Java public static void sortInPlace(List<Integer> xs) all appear in port.rs as -> Result<(), String> with no warning. record stores the return value only.
  • Failing scenario (run): m.py with def sort_in_place(xs: list[int]) -> None: xs.sort(), record crate --count 20 gives 21 cases of the form {"fn": "sort_in_place", "args": [[100, 7, -2147483648]], "ok": null}. Same for Go ({"args":[[2147483647,2147483647,2]],"fn":"SortInPlace","ok":null}) and Java ({"fn":"sortInPlace","args":[[2,255]],"ok":null}). A port Ok(()) matches all of them, gate has nothing to compare, and enable rebinds the Python function to a version that cannot mutate the caller's list.
  • Evidence: ExportedFn.blocker is set only in the places listed above; returns is "void"/"unknown" and the params are plain string[]/int[]. C is the exception: harness_c.rs records out/buffer params back ({"return":0,"xs":1000}), so the idea exists, it is just not applied to the other languages.
  • Fix / verification improvement: (1) in each plugin, when a function returns nothing (None/void/Go no result) or returns something and also has a container parameter that the body mutates (.sort(), .append(, index assignment, Collections.sort(param), sort.Ints(param)), set a blocker "mutates its argument in place", or (better) have the drivers record the arguments after the call as C does. (2) Mutation self-test in tests/: bridge the three one-liners above, replace the port with a no-op and assert diff fails. (3) gate: refuse a port whose every recorded case for a function is ok: null/void unless the function was marked void by the user.

A6a-02 [H1/H3] [HIGH] [CONFIRMED] Python infer_numbers types string parameters as number, so no string is ever recorded

  • Where: src/lang/python.rs:1230-1295 (infer_numbers); applies from function() at :1308. Documented only as decision M8 (colorsys), not its side effects.
  • What happens: an unannotated parameter becomes number if it is an operand of -, *, /, //, **, if +/% has a numeric literal on the other side, or if it is an argument of min/max/abs/round/float/int/divmod/math.*. int(s), float(text) (string parsing) and s * n (string repetition) therefore make s a number.
  • Failing scenario (run): def parse(s): return int(s) + 1 produces pub fn parse(s: f64); `def rep(s, n): return s
    • nproducesrep(s: f64, n: f64). The 25 recorded parse cases are all numbers ({"fn": "parse", "args": [0.5], "ok": 1}, plus NaN/inf errors); no case passes "42"or"abc". A port that only handles numbers passes diff` and fails for the real callers, who pass strings.
  • Also narrowing (PLAUSIBLE): to_ts_type maps Iterable[str]/Sequence[str]/Collection[...] to string[] (python.rs:1561), but a str (or tuple, set, generator) is a valid argument; cases will only be lists. bridge of def h(xs: Iterable[str]) gives xs: Vec<String>.
  • Fix / verification improvement: exclude int/float calls and * with a non-literal other side from the inference, or keep the param unknown and have record generate both numbers and strings for inferred params. Add a test pair: int(s) must stay unknown; maxc - r must become number. Mutation self-test: make the port of parse reject strings and assert diff fails once the recording contains a string case.

A6a-03 [H1/H3] [HIGH] [CONFIRMED] C: array pointers become one-cell out scalars; const char * + length is not paired

  • Where: src/lang/c.rs:764-849 (classify_params), :861-882; consumed in src/harness_c.rs:478-487 (static T out_N;).
  • What happens: pass 1 gives every const char * the kind string before the const byte pointer + length pass can pair it with a length, so count_a(const char *s, size_t len) has an independent random len. A non-const int */double * followed by a count falls through to Some((base,false)) if scalar(base) and becomes "out": a pointer to ONE static cell. Only const arrays and byte buffers are refused. This contradicts the Known-limits line "C: only scalar and const char * APIs cross the bridge; output buffers ... stay in C".
  • Failing scenario (run): int sum_arr(int *xs, int n), void double_all(int *xs, int n), int count_a(const char *s, size_t len). bridge emits xs: Option<&mut c_int>, n: c_int; record stores {"fn": "sum_arr", "args": [0, 42], "ok": {"return": -1646905891, "xs": 0}} (an out-of-bounds read of neighbouring memory), {"args": [-1, 2147483647], "error": "crash: SIGSEGV"}, count_a("hello", 2147483647) as crash: SIGSEGV and count_a("line1\nline2😀", 42) as ok: 0 (read past the literal). 34 of 84 cases threw. The expected values are layout-dependent garbage; a port cannot match them, and one that does by accident is unportable.
  • Fix / verification improvement: classify a non-const pointer to a non-byte scalar as out only when no sibling integer param is named n/len/size/count/num/cap (else blocker "array pointer: length is a parameter"); in pass 1 skip string when the next param is an integer named like a length and pair it as bytes. In record for C, make a case that dies with a signal an error to report, not an expected result, and refuse to write a recording where more than a few percent of cases crash. Test: this three-function file must produce blockers, not cases.

A6a-04 [H1] [HIGH] [CONFIRMED] Go: named types, cross-file structs and structs with pointer fields become unknown without a blocker

  • Where: src/lang/go.rs:431 (Ok(structs.get(t).cloned().unwrap_or_else(|| "unknown".into()))), structs() :311-372 (per file, so a struct defined in another file of the package is not seen; a struct with a pointer field or embedded field is dropped; type Color int is skipped because ty.kind() != "struct_type").
  • What happens: the parameter is typed serde_json::Value with no blocker, and the case generator produces generic JSON junk instead of values of the real type.
  • Failing scenario (run): type Color int; func Paint(c Color) string { if c == 1 {return "red"}; return "other" } records exactly two cases, args:[null] and args:[0], both "other". A port that always returns "other" passes. func UseOpt(o Opt) where Opt{V *int} records {}/null/{"a":"b"} all returning 1.
  • Fix / verification improvement: resolve types across all files of the package (type_decls already takes several sources); map type X <builtin> to the builtin (with its native type); if a type cannot be resolved, set a blocker (uses the type X, which is not a plain struct) instead of unknown. General rule for all plugins: an unknown parameter type must be a blocker or print a note that its recording is uninformed. Test: the Paint file must record a case with c == 1.

A6a-05 [H3] [MEDIUM] [CONFIRMED] Python risk scan is exact-text on the callee: aliased and from-imported calls are invisible

  • Where: src/lang/python.rs:389-445.
  • What happens: only the dotted spellings re.*, random.*, secrets.*, time.time, datetime.now, ... match. from re import sub, compile as rcompile, import re as regex, from random import randint, from time import time, os.getenv give nothing. re.compile(f"{p}x") is a string node, so an f-string pattern is not DynamicRegex. Conversely re.sub(...).strip() and re.escape(x) match starts_with("re.") with a non-string first arg and report DynamicRegex (false positive).
  • Failing scenario (run): analyze on a file with three functions using sub(r"(?<=a)b", ...), rcompile(r"(a)\1"), regex.compile(r"(?<!x)y") reports risks: [] and readiness 100. from random import randint / from time import time / os.getenv("USER") also report none; only datetime.now() is listed ("Clock and random numbers x1"). The f-string regex function is reported nothing.
  • Fix / verification improvement: build a name table from the file's imports (import re as regex, from re import sub) and match on the resolved dotted name; treat an f"..."/.format pattern as dynamic. Table-driven test for each risk with 4 spellings (plain, alias, from-import, attribute chain), asserting it is flagged.

A6a-06 [H3] [MEDIUM] [CONFIRMED] Go: range over a map is only flagged when the expression text contains "map"

  • Where: src/lang/go.rs:223-231: r.text.contains("map").
  • Failing scenario (run): counts := map[string]int{}; for k, v := range counts {...} is not reported; the analyze output lists only Pointers and Division. A variable named mapping (a slice) is reported (false positive). Hash iteration order is a documented "high" risk.
  • Fix / verification improvement: track local :=/var declarations and parameter types that are map[...] and flag range over those; at minimum warn on every range <identifier> of unknown type. Test with counts, a struct field s.items of map type, and a function result.

A6a-07 [H3] [MEDIUM] [CONFIRMED] Java: import java.util.* hides HashMap/HashSet; concatenated regex strings count as literals

  • Where: src/lang/java.rs:233 (only java.util.HashMap/HashSet imports), :286-291 (p.starts_with('"')).
  • Failing scenario (run): a class with import java.util.*; and Map<String,Integer> m = new HashMap<>() returned from a public static method gives risks "String offsets, Callback-shaped APIs, Integer width" and no "Hash iteration order". The method is bridged and its recorded JSON object keys are in Java's hash order, which a port must reproduce. In replaceAll("[" + chars + "]", "") the argument text starts with ", so it is judged as a literal (DynamicRegex missed).
  • Fix / verification improvement: also match wildcard imports and new HashMap/HashSet/java.util.HashMap uses by name in the AST; require the pattern node kind to be string_literal. Test both spellings.

A6a-08 [H6] [MEDIUM] [CONFIRMED] A file with a parse error is still bridged, with dropped or mangled functions and no warning from bridge

  • Where: exports() of Python (python.rs:973), Go (go.rs:435), C (c.rs:901), Java (java.rs:498) never look at root.has_error(); scan records parse_errors, and analyze prints "1 parse error: results for this unit are partial", but readiness stays 100 and the unit stays in start_here.
  • Failing scenario (run): a Python file with def broken(x: int -> int: in the middle. bridge creates a crate for ident, add, total, broken; after(s: str) -> str, defined after the error, is silently missing, and broken becomes broken(x: serde_json::Value) -> Result<String, String>. bridge prints nothing about it.
  • Fix / verification improvement: bridge should fail (or demand --force) when the unit has a parse error; analyze should subtract readiness for it. Test: the file above must make bridge exit non-zero.

A6a-09 [H6] [MEDIUM] [CONFIRMED] C functions inside #if/#ifdef are not exported (and main inside is not seen)

  • Where: src/lang/c.rs:909 and :1049, :1118 iterate named_children(root) only; tree-sitter-c wraps preprocessor blocks in preproc_ifdef/preproc_if nodes.
  • Failing scenario (run): #ifdef FEATURE\nint hidden_fn(int x) { return x + 1; }\n#endif is absent from port.rs. A whole file wrapped in an include guard style #ifndef X ... #endif or extern "C" yields zero exports and no note. defines_main misses main in a block and the original is then linked into the library.
  • Fix / verification improvement: recurse into preproc_* and linkage_specification children (and emit both-variant definitions as a blocker); tests: guarded file must export its functions.

A6a-10 [H2/H3] [MEDIUM] [CONFIRMED] Manifest parsing: wrong or empty dependency facts with no note

  • Where and what:
    • src/lang/java.rs:37-61: split("<dependency>") also takes entries of <dependencyManagement> and of <plugin><dependencies>; :105-109 takes the first <artifactId>, which in a pom with <parent> is the parent's. Run: such a pom reports package big-parent and, with analyze --whole-app, com.google.guava:guava and commons-lang3 as "Declared: yes" although only managed or plugin dependencies.
    • Gradle: regex at :65 matches only implementation("g:a:v") string forms. Version catalogs (implementation(libs.guava)) and named arguments (group = "org.yaml", name = "snakeyaml") are missed. Run: with import com.google.common.base.Joiner and libs.guava the table shows com.google.common | Declared: no, and snakeyaml is absent.
    • Python read_package (python.rs:120-151): if let Ok(...) && let Ok(doc) means an unparsable pyproject.toml gives no deps and no message (run: a truncated [project table gave an unremarkable report). Only runtime [project].dependencies and tool.poetry.dependencies; dev_deps is always empty; install_requires=VAR in setup.py is skipped silently; requirements-*.txt and -e lines are ignored.
    • Go discover (go.rs:95): read_to_string(...).unwrap_or_default(), and a UTF-8 BOM in go.mod makes module_path return None (without_bom exists in lang/mod.rs but is not applied) so the package name is empty (run: ['']) and intra-module imports resolve as external. WEAK for Go because I did not check whether go itself tolerates the BOM.
    • C discover (c.rs:73-92) reads no manifest at all: Makefile, CMakeLists.txt, meson.build are only used to find folders; deps is always empty, so libraries linked without an #include <...> of a known header are never shown.
  • Fix / verification improvement: parse the pom with an XML parser and take project/dependencies only (and project/artifactId); read gradle/libs.versions.toml; when a manifest exists but fails to parse, add a unit note "pyproject.toml could not be read: dependencies unknown". Tests with each of the shapes above.

A6a-11 [H3] [MEDIUM] [CONFIRMED] Reads of environment, clock, randomness and global state are not risks in Go, Java, C, and most Python spellings

  • Where: scans of go.rs, java.rs, c.rs have no clock/random/environment/I-O category; exports have no check for package-level variables, static fields or global.
  • Evidence (run): Python def env() -> str: return os.environ.get("HOME", "") is bridged, analyze lists no risk, and the recording contains {"fn": "env", "args": [], "ok": "/root"}: a local path in the file the workflow says to commit, and the only protection (record secret-name filter) triggers on names such as TOKEN, not HOME. Java System.getenv, currentTimeMillis, toLowerCase() (default locale; recorded "İstanbul" -> "i̇stanbul") and Go time.Now()/rand.Intn/os.Getenv behave the same. Hidden state: counter() (Python global, Go package var, Java private static, C static int) is bridged as pure; record stores one 1 and memo(k, acc=[]) stores 1, 2, 3, ... order-dependent results.
  • Failing scenario: the port passes on this machine because the constant is /root/this locale; it fails on the caller's machine, or when the order of calls differs.
  • Fix / verification improvement: add an "environment and global state" risk for the five scans (names above, plus assignments to module/package/static variables from inside a function) and a blocker for exports that read environ/getenv. Add the local-path check of scripts/check-secrets.sh to record.

A6a-12 [H3] [LOW] [CONFIRMED] Python STDLIB table lacks the modules removed in 3.12

  • Where: src/lang/python.rs:645-952; the comment says it is "version-agnostic".
  • Run: distutils, imp, asyncore, asynchat, smtpd, binhex are not listed (grep shows 0); analyze --whole-app shows distutils and imp as unknown dependencies (Rust: ?, Fit: unknown), costing readiness 4 each and creating a decision "Use it?" for standard-library modules.
  • Fix: add them; test that every name in a CPython 3.8-3.13 sys.stdlib_module_names union resolves as stdlib.

A6a-13 [H3] [LOW] [CONFIRMED] LOC undercounts/overcounts feed the size check of gate

  • Where: src/lang/mod.rs:229-237, src/lang/syntax.rs:49-150.
  • Python docstrings and """ lines count as code (prefix # only), which inflates the original's size and so loosens gate's "3x the original plus 50"; for C-style languages a continuation line that starts with * (a multiplication wrapped to the next line) is dropped as if it were a comment. Neither can flip a result alone; both affect the reported "Lines" and the size ratio.
  • Fix: strip Python docstrings (first statement of a module/def/class) in loc; for * require being inside a block comment.

A6a-14 [H5] [LOW] [PLAUSIBLE] C typedef/struct tables are built from every .h/.c in the tree, last file wins

  • Where: src/lang/c.rs:489-553 (raw.insert, bodies.insert) over crate::walk::builder(root), which is not sorted and does not skip vendor/third_party/build.
  • Scenario: two files define typedef long Handle; and typedef int Handle; (or two different struct Vec); which one a signature resolves to depends on directory order, so the same repo can bridge differently on two machines and #if/platform variants are merged. Not run.
  • Fix: walk sorted, prefer typedefs from the unit's own include closure, and refuse a bridge when a name has two different definitions.

A6a-15 [H6] [WEAK] Tests in this area return early when the toolchain is missing

  • tests/go_*.rs, java_*.rs, c_*.rs all return when go/java/cc is absent and so report "ok". STATUS "Tested" rows for Go/Java/C therefore hold only for machines where the tool exists. Suggest RUST_ANYTHING_REQUIRE_TOOLS=1 in CI to turn the skip into a failure.

A6a-16 [H3] [WEAK] Python mutable default shared state is described as []

  • ports get /// acc defaults to [] in the source, but the default is one shared list that grows across calls (memo recorded 1, 2, 3...). Loud for the pure port (the second case fails), only the doc comment is misleading.

Verification improvements for this area (ranked)

  1. Argument-mutation check for all non-C languages (A6a-01): record post-call arguments, or block; plus no-op-port self-test per language. Highest value: one mechanism closes the only CRITICAL.
  2. "unknown" must never be silent (A6a-02, A6a-04): an unknown or inferred parameter either gets a blocker or makes record generate mixed JSON types; gate should warn when a param type is unknown and branch coverage is low.
  3. C recordings that depend on UB (A6a-03): refuse crash/signal results as expected values, fix the two classification passes, count crashes in the record summary ("34 of 84 cases threw" was printed but nothing said it was suspicious).
  4. Table-driven risk tests (A6a-05..07): one corpus file per language with the same risk written 3-4 ways; the test asserts every spelling is flagged. Cheap and mechanical.
  5. bridge refuses a unit with parse errors (A6a-08) and C #if recursion (A6a-09).
  6. Manifest "could not read" notes and structural pom/Gradle/pyproject parsers (A6a-10).
  7. Mutation self-tests of the plugins themselves: break one match arm (for example delete "hashCode" or the "map" check) and assert a corresponding test fails.

Things checked and found sound (so nobody re-checks them)

  • Python ints beyond i64: recorded as {"$int": ...}, port errors as OverflowError (codegen_py.rs), not narrowed silently; big(n) with big inputs times out and is reported ("Left out 4 inputs ...").
  • Go unsigned/64-bit: native_type survives (uint64 stays u64, uintptr usize); tests/go_unsigned.rs checks Hash(1) above i64::MAX and the stubs. Go float32 results are recorded at f32 precision (-0.8333333).
  • Java int wraps are recorded (add(-1, -2147483648) gives 2147483647); overloads are all blocked (also --keep paths); char, Object, unordered Set/HashSet, wildcards, generics, functional types, variadics are blockers; byte[] -> int[] is lossless.
  • Python scan uses tree-sitter, so comments and strings cannot raise risks (no false positives from text); decorators, *args/**kwargs, callable parameters, generators and __all__ handling are conservative and tested.
  • C: long double and unknown typedefs are refused; variadics, function pointers, returned pointers that do not point into an argument, writable buffers without a size are blockers; static functions are skipped; the arch-dir guard exists.
  • syntax.rs loc/without_*_comments: block-comment edge cases and PowerShell stop-parsing are covered by tests that read correctly.
  • Go: variadics, generics, pointers, channels, any, fixed arrays, error params are blockers; methods are skipped (documented). Sentinel-error extraction is conservative (None when the text is not static).