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.5 KB
Raw Blame

Language plugins, part 2: Ruby, Kotlin, PHP, PowerShell, C#, Swift (audit id A6b)

Scope and coverage ledger

Read in full, every line, in chunks of at most 620 lines:

File Lines Read
src/lang/ruby.rs 1246 1-1246
src/lang/kotlin.rs 1205 1-1205
src/lang/php.rs 1202 1-1202
src/lang/powershell.rs 1134 1-1134
src/lang/csharp.rs 1092 1-1092
src/lang/swift.rs 952 1-952
tests/ruby_recording.rs 109 1-109
tests/powershell.rs 403 1-403
tests/swift.rs 263 1-263

Read for context (not in scope, partial): src/lang/mod.rs 1-430 (all), src/lang/syntax.rs 1-260 of 519 (parse, walk, loc/code_lines, powershell_outside), src/bridge.rs 205-355 (js_only_reason, state_through_calls), src/codegen_php.rs 1-135, src/codegen_ruby.rs 1-75 and 150-240, src/codegen_java.rs 670-740 (reflection driver), DECISIONS.md, docs/STATUS.md 1-60, docs/pitfalls.md (given). Not read: the input generators, harness_*, the rest of codegen_*, syntax.rs 260-519 (manifest helpers).

Experiments (scratch folder .../scratchpad/A6b/, nothing written in the repository except this report). I copied the prebuilt target/debug/rust-anything to the scratch folder and ran analyze, bridge and (Ruby, PHP, which only need ruby and php) record on small fixtures I wrote: rb, rb2, rb3, ph, kt, kt2/kt3, cs, cs2, sw, sw2, ps. kotlinc, dotnet, swiftc and pwsh are not installed, so for Kotlin, C#, Swift and PowerShell I confirmed what analyze/bridge claim (exports, blockers, risks, generated wrapper text), not the replay verdicts. No cargo was run in the repository.

Summary

  • No plugin in this group knows that an export reads or writes state outside its arguments. Mutation of an argument in place, module/object/global state, clock, environment and file reads are not blockers, and (except PowerShell Get-Date/Get-Random, Swift Date()/.random) not even risks. Such units come out ready with readiness 86-98 and every export "bridgeable". Because record stores only the return value, a function that mutates its argument and returns nothing is "matched" by an empty port (A6b-01, CONFIRMED on Ruby, same shape traced for Kotlin, C#, PowerShell).
  • Zero-argument functions (state, clock, env) get one recorded case, so a constant passes; env_name recorded "/root" into the file the workflow says to commit (A6b-03, CONFIRMED Ruby and PHP).
  • Type narrowing that hides behaviour from recordings: Ruby Symbol is generated as String although the codec has a $sym marker (A6b-04); Kotlin @JvmOverloads functions are driven through whichever overload getMethods() returns last, which changed between two JVM runs (A6b-05).
  • A tree-sitter parse error silently shortens the export list: Kotlin context(...) made 3 of 4 functions vanish and bridge still said "Created ... for before" (A6b-06). PowerShell Export-ModuleMember -Function $names and PHP if (!function_exists(..)) { function .. } also yield no exports with no explanation (A6b-07).
  • Risk scans have holes that make the "Risks" column look cleaner than it is (Ruby flags <<, not *; Swift SwiftTraps never fires for +/-/subscript; PHP $f() unflagged), but recordings with emoji and extreme integers catch most of those, so they are advice-level (A6b-08, A6b-12).

Findings

A6b-01 [H1] [HIGH] [CONFIRMED] A function that mutates its argument in place and returns nothing passes with an empty port

  • Where: src/lang/ruby.rs:802-923 (method_fn: blockers only for =/! names, splat, block, yield), src/lang/kotlin.rs:639-766 (IntArray, Array<T>, MutableList, MutableMap map to int[]/string[]/Record with native_type List<String> etc.), src/lang/csharp.rs:752-797 (only ref/out/in/params blocked; int[], List<T> allowed), src/lang/powershell.rs:526-560 (ps_to_ts: collections.arraylist, array, hashtable, int[] are plain JSON types, parameter_blocker only for scriptblock/[ref]/unknown .NET types). PHP is fine (&$x blocked, reference_modifier); Swift is fine (inout blocked).
  • What happens: the bridge copies the argument into Rust. The driver records {"ok": <return value>} only (codegen_ruby.rs call: { "ok" => enc(value) }; Java reflection driver codegen_java.rs:~720: out.put("ok", ... result); PowerShell compares $Expected['ok'] -ceq $Got['ok']), and the arguments are not re-read after the call. The mutation, which callers rely on, is never compared.
  • Failing scenario (Ruby, run): def self.sort_in_place(xs); xs.sort!; nil; end with @param xs [Array<Integer>]. bridge lists it as exported; record writes {"fn":"sort_in_place","args":[[100,7,-2147483648]],"ok":null} (7 cases, all ok:null). A port.rs body of Ok(()) passes diff 7/7, and callers of the wrapper see an unsorted array. Same for mark(s) (s << "!"; nil): 20 cases, all ok:null. Bridge outputs of the same shape: Kotlin fun sortInPlace(xs: IntArray) and fun appendAll(xs: MutableList<String>, ..) -> pub fn sort_in_place(xs: Vec<i64>) -> Result<(), String>; C# SortInPlace(int[]), AddAll(List<string>, ..); PowerShell Add-Item([System.Collections.ArrayList]$List, ..) -> unknown[], Sort-InPlace([int[]]$Xs). Only the Ruby case was replayed; the others stop at bridge because the runtimes are missing, but the driver code paths are the ones quoted above. (Ruby's append! was blocked only because of the ! in its name.)
  • Fix / verification improvement: (1) mechanical blocker in each plugin: an export whose return type is void/undefined/nil/Unit and that takes an array/list/map/string (Ruby)/ArrayList/hashtable parameter stays in the original, reason "mutates its argument in place?". (2) Better, in the shared record/diff drivers: record a args_after snapshot for each case (encode the arguments again after the call) and compare it in diff; the wrapper must then write mutated values back, or the export is kept. (3) Mutation self-test in tests/: fixture with sort_in_place, assert that diff fails against Ok(()).

A6b-02 [H3] [MEDIUM] [CONFIRMED] State, clock, environment and I/O are neither blockers nor risks in Ruby, Kotlin, PHP, C#; thin in Swift and PowerShell

  • Where: ruby.rs:477-599, kotlin.rs:162-258, php.rs:261-419, csharp.rs:268-400 have no Risk::ClockAndRandom at all (grep: it is used only by ts, python, powershell (get-date, get-random, new-guid only) and swift (.random, Date(), UUID() only)). No plugin has an I/O or environment risk (the Risk enum has none). Module/object/global state is never a blocker; calls/state_through_calls only chase uses_class (Ruby, PHP, C#, PowerShell do not even fill calls).
  • Failing scenarios (all run through analyze --json and bridge): every function below is listed as an export with no blocker, and the unit is ready:
    • Ruby (readiness 86): @count += 1, n + Time.now.year, ENV.fetch("HOME"), File.read(path). Only risk shown: "Dynamic typing", "Null references".
    • PHP (readiness 93): static $n; return ++$n;, date('Y'), getenv('HOME'), $fname($x).
    • Kotlin (readiness 98): object Counter { private var n = 0; @JvmStatic fun next() }, java.time.Year.now().
    • C# (readiness 91): static int _n; _n++, DateTime.Now.Year, x.ToString("N2"), s.ToUpper(), a.StartsWith(b), string.Compare.
    • Swift (readiness 88): global var counter, Date.now, xs.randomElement(), xs.shuffled(). Not flagged: randomElement/shuffled/Date.now (scan matches only a nav suffix named exactly random and the call Date()).
    • PowerShell (87): $script:count++, $Prefix read from module scope, [DateTime]::Now, $env:HOME, Get-Content. $script:/$global: count as "Dynamic typing".
  • Why it matters: A8/A7 readiness and "Start here" treat these as safe first ports, an agent reads "ready" as "pure". The port then must reproduce hidden state or a different year/host; what is recorded is one machine's moment. Several of these are exactly the categories the brief lists (globals, environment, culture).
  • Fix: add a shared Risk::ReadsEnvironment/ReadsState (ENV/getenv/$env:/System.getenv/File.read, module-level mutable @ivar/static/global/top-level var) and clock/random calls per language; make "unit-level mutable state read by an export" a blocker like uses_class. Cheap test: one fixture per language holding the listed snippets, assert the risk appears (tests/analyze.rs style).

A6b-03 [H1/H5] [MEDIUM] [CONFIRMED] Zero-argument exports get one recorded case; environment values are recorded into the committed file

  • Where: input generation (outside my files) plus the plugins marking such functions bridgeable (ruby.rs:802, php.rs:696, kotlin.rs:639, ...). The secret filter in record only looks at variable names that say secret (pitfall "A recording held a secret from the environment").
  • Failing scenario (run): Ruby def self.bump; @count += 1; end -> 1 case {"fn":"bump","args":[],"ok":1}; a port Ok(1) passes and gate's literal check needs three or more literals. PHP counter() same ({"fn":"counter","args":[],"ok":1}). ENV.fetch("HOME") and (string) getenv('HOME') recorded {"fn":"env_name","args":[],"ok":"/root"} and {"fn":"env_home","args":[],"ok":"/root"} into cases.jsonl: a local path in the file the workflow tells people to commit (cf. pitfall "A local path reached a committed manifest"). today_plus(n) recorded the year 2026 in 17 cases; a port n + 2026 passes today and gate sees 17 different outputs, not 3 identical literals.
  • Fix: record should warn when a case has no arguments and the function has no blocker ("one case; a constant satisfies it; is it state or clock?"), flag recorded string values that equal $HOME, $USER, the cwd or hostname (extend the secret filter to the values of well-known env vars, not only names), and --pin-clock should exist for Ruby/PHP/Kotlin (STATUS lists it only for TS/Python). Mutation test: port bump as Ok(1), assert gate or record reports a warning.

A6b-04 [H1/H3] [MEDIUM] [CONFIRMED] Ruby Symbol parameters are typed string, so the original is only ever called with Strings

  • Where: ruby.rs:741 ("Symbol" => "string", also as Hash key, :742). The codec has $sym (codegen_ruby.rs:25,45) and dec would build a Symbol, but nothing generates one for a string parameter.
  • Failing scenario (run): @param mode [Symbol], case mode when :a then "A" when :b then "B" else "other" end. All 27 recorded kind cases are "other" (inputs are strings like "hello"; "a" as a string also yields "other" in the original). A port that implements only "other", or the faithful port for real symbol callers ("a" -> "A"), is judged by behaviour of a never-matching comparison. A wrong port passes; a correct one fails if the generator hits "a".
  • Fix: map Symbol to a distinct dialect type (symbol) so the generator emits {"$sym": ..} (and Hash keys likewise); mutation self-test: fixture with case sym when :a, break the port's :a branch, assert diff fails.

A6b-05 [H5/H1] [MEDIUM] [CONFIRMED mechanism, not replayed (no kotlinc)] Kotlin @JvmOverloads is driven through an arbitrary overload

  • Where: kotlin.rs:639-766 never looks at @JvmOverloads (the JvmName check at :668 is the only annotation check); the reflection driver codegen_java.rs:696 does for (Method m : c.getMethods()) if name matches METHODS.put(key, m) (last one wins) and then reads only types.length arguments (values[i] loop at ~:718); extra recorded arguments are dropped without error.
  • Failing scenario: @JvmOverloads fun pad(s: String, width: Int = 10, fill: String = " ") is exported as the 3-argument function (bridge output: acme.UtilKt.pad(String s, Int width, String fill)), but the class has three pad methods. I ran the same loop on a Java class with three overloads: the chosen method was pad(String,int) on the default run, pad(String) with -Xshare:off, pad(String,int) with -XX:+UseSerialGC. So the recorded results are those of a shorter overload, differ between runs, and ignore later arguments; the 3-argument port then fails (or, with defaults that coincide, passes for the wrong reason).
  • Fix: in kotlin::collect set blocker "@JvmOverloads generates overloads" (the same way kotlin::exports blocks repeated names at :899), or make the driver select the method by parameter count of the prototype and fail on ambiguity. Test: Kotlin fixture with @JvmOverloads, assert bridge keeps it (runs without kotlinc).

A6b-06 [H6] [MEDIUM] [CONFIRMED] A parse error silently shortens the export list; bridge says nothing

  • Where: all plugins use syntax::parse (returns a tree even with errors) and exports ignores has_error. analyze sets parse_errors (kotlin.rs:171) and marks the unit caution, but bridge does not mention it.
  • Failing scenario (run): Kotlin file with fun before(..), context(ctx: String) fun ctxFun(..), fun after(..), fun last(..): analyze --json -> exports 1, status caution, note "1 parse error: results for this unit are partial."; bridge -> "Created ... for before". Three functions are not reported as "kept" or as "not seen". An agent reading bridgeable 1/1 believes the unit has one function. (The same file without the context line: 3 of 3 exports; a value class is fine.) Ruby with a real syntax error still listed all three functions, so the damage depends on grammar recovery; newer syntax of any of the six languages is the realistic trigger (Kotlin 2.2 context parameters here).
  • Fix: bridge and analyze --json should refuse (or warn loudly with the count) when parse_errors > 0 for a unit that is bridged, and list byte ranges of ERROR nodes; add exports_incomplete: true to the JSON. Test: the Kotlin snippet above must make bridge fail without --force.

A6b-07 [H6] [LOW] [CONFIRMED] Exports silently missing for conditional/computed definitions

  • PowerShell powershell.rs:618-644: Export-ModuleMember -Function $names puts the literal $names on the list, wildcard("$names", f) matches nothing, so every function is dropped (run: analyze said "No unit exports anything a bridge can carry yet: the units below expose constants, types or nothing a port could call", and bridge said "exports no functions"). Wrong cause, fails closed. Also FunctionsToExport in the .psd1 is never read (helpers the manifest hides are listed as exports) and functions inside if (...) { function .. } are skipped.
  • PHP php.rs:879-927: only top-level and namespace-level function_definition; if (!function_exists('x')) { function x() {} } (the usual shape for polyfills and helper files) is dropped (run: guarded missing, no mention). Methods of enums/interfaces/traits and nested classes are also dropped; C# record/struct statics and nested public classes (csharp.rs:841) and Ruby top-level def likewise.
  • Fix: report "N function definitions not seen (conditional, nested)" in analyze; for PowerShell treat a non-literal Export-ModuleMember argument as "unknown export list" with a note.

A6b-08 [H3] [LOW] [CONFIRMED] Risk scans mislabel or miss the operations their risk text names

  • Ruby ruby.rs:577-585: IntegerSemantics is flagged for ** and << (string/array append, common) and not for *, +. Run: s << "x" flagged ("Integer width and overflow x1") while n * n * n was not; recorded cube(9223372036854775807) is a 57-digit bignum, which the recording does capture, so a port must use a bignum. Advice-level only.
  • Swift swift.rs:282-289: the arm matches multiplicative_expression | additive_expression but the op test is "*" | "/" | "%", so + and - (the documented M14 example: a + b traps on overflow) are never flagged; array subscripts (xs[0]) and try!/as! are not either, though the risk label says "overflow, !, index out of range". Run: add, sub, first(xs[0]) unflagged, Int(s) flagged. Recordings with Int.max do catch overflow (see tests/swift.rs).
  • Kotlin kotlin.rs:228-253 matches substrings of the whole call text, so println("indexOf") is flagged (StringOffsets) while s.length, s[0], take, drop are not; C# flags Substring, IndexOf, not .Length or indexers. The recording corpus includes emoji and combining marks ("a😀b" appears in every Ruby/PHP run), which is what really protects the UTF-16 versus UTF-8 distinction.

A6b-09 [H3] [LOW] [CONFIRMED text, not compiled (no swiftc)] Swift typed throws throws(E) is not seen as throws

  • swift.rs:597-605 reads only a throws child; with func typed(_ a: Int) throws(E) -> Int the signature has throws == false, and the generated wrapper for it is return raTrap { try raDecode(raCall(..).get()) } where the plain-throws wrapper rethrows. A port error becomes fatalError (a trap) while the original throws E: diff fails a correct port. Fails closed, no blocker or note.
  • Fix: detect throws( in the declaration text and either support or block with a reason; fixture test in tests/swift.rs that does not need swiftc (bridge only).

A6b-10 [H5] [MEDIUM] [PLAUSIBLE] Locale, culture and time zone are neither pinned nor flagged (C#, Ruby, PHP, Kotlin, Swift)

  • No harness sets LANG, LC_ALL, TZ, DOTNET_SYSTEM_GLOBALIZATION_INVARIANT (grep of .env( in harness_*.rs: only .NET telemetry, RUST_ANYTHING_*). C# ToUpper(), StartsWith(string), string.Compare, ToString("N2"), SortedDictionary<string,..> (mapped to Record<string, ..> at csharp.rs:691) and OrderBy are culture-sensitive and the plugin has no risk for them (csharp.rs:384-392 lists only Substring/IndexOf/...); PowerShell has the pitfall text for İ but a -f/.ToString() format uses the current culture. The recording stores whatever the recording machine did and the port is judged against that; recording on another machine gives different cases.jsonl.
  • Fix: run drivers with TZ=UTC, LC_ALL=C.UTF-8, DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 (and say so in the report), add a C# risk for culture-sensitive string/number APIs, and record the environment in cases.jsonl's header so diff can warn when it differs.

A6b-11 [H3] [LOW] [CONFIRMED] Ruby module_function :name / private_class_method :name match by substring

  • ruby.rs:1019-1029 uses call.contains(":clamp"), so module_function :clamp_all also exports a method clamp that is not a module function, and :1060 hidden.contains(":foo") hides foo when private_class_method :foobar is written. Run (rb2): clamp was exported and its 9 recorded cases are NoMethodError: undefined method clamp' for module M2; the generated wrapper defines clamp anyway (ruby/m2_rs.rb:19`). Fails closed (the port would have to raise NoMethodError) but adds an API method the original does not have.
  • Fix: parse the symbols of the call's argument list instead of contains.

A6b-12 [H3] [LOW] [CONFIRMED] Obfuscated dynamic calls are not flagged in PHP, PowerShell, Kotlin

  • PHP php.rs:317-368: $fname($x), $obj->$method(), new $class are not DynamicCode/Reflection (only call_user_func* and named reflection functions are); shell and process calls (shell_exec, exec, system, backticks) are unflagged (proc_open only). Run: call_by_name($fname, $x) -> no risk at line 18 (only the function_exists at line 39 appeared).
  • PowerShell powershell.rs:347: invoke-expression/iex/invoke-command flagged, but icm, [scriptblock]::Create(...), $ExecutionContext.InvokeCommand.InvokeScript, & $cmd (only Callbacks) are not.
  • Note: the scan is AST based, so comments and strings are not flagged (good); the exception is Kotlin's substring match (A6b-08).

A6b-13 [H3] [WEAK] Type mappings that drop distinctions

  • PHP array<int, V> -> V[] (php.rs:561): sparse integer keys never generated; array -> unknown[] | Record<..> is fine. C# HashSet/ISet -> T[] (csharp.rs:682), Kotlin refuses Set: inconsistent; the original dedupes a list given as input, the port sees duplicates. PowerShell [char] -> string, [decimal] -> number (f64). Ruby Float, Numeric -> number conflates Integer/Float results (the 5 versus 5.0 comparison is exact in the Ruby/PHP codecs, so recordings catch this).

A6b-14 [H2] [LOW] [CONFIRMED] Doc understates, and LOC edge cases

  • docs/STATUS.md:39 says calls are followed for Java and Kotlin, "other languages do not list calls yet"; Swift fills calls too (swift.rs:748). Harmless understatement.
  • LOC (lang/mod.rs:229-237, syntax.rs): PHP #[Attribute] lines count as comments (# prefix); lines inside Kotlin/Swift raw strings that begin with //, * or # and Ruby text after __END__ are miscounted. Only affects size/priority numbers.

Verification improvements for this area (ranked)

  1. Record args_after for every case and compare it in diff; until then block void-returning exports with mutable parameters (A6b-01). Mutation self-test: fixture with an in-place function per language, assert diff fails against an empty port.
  2. Shared "reads state / environment / clock / random" detection per plugin, as risk and (for module-level mutable state) blocker; fixture per language with the snippets of A6b-02 (all runnable with analyze only).
  3. bridge/analyze --json must fail or warn loudly when parse_errors > 0 for the unit and expose exports_incomplete (A6b-06); regression test with the Kotlin context(...) snippet.
  4. record: warn for zero-argument exports (one case) and redact/flag recorded values equal to $HOME, $USER, cwd, hostname (A6b-03); pin TZ, locale and .NET invariant globalization in all drivers (A6b-10).
  5. Ruby Symbol as its own dialect type; Kotlin @JvmOverloads blocker; Swift typed-throws detection; Ruby module_function argument parsing (A6b-04, 05, 09, 11), each with a bridge-only test.
  6. Fix the dead additive_expression arm in Swift's scan and Ruby's <</* split (A6b-08).

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

  • PHP: by-reference parameters (&$x, reference_modifier), variadics, callables/Closure, object types and object returns, magic methods, yield are all blockers (php.rs:725-804); output is captured (ob_start) and compared; results are compared as JSON text, so 5 versus 5.0 and [] versus {} differ as PHP would see them (codegen_php.rs:10-64). declare(strict_types=1) files recorded fine in my run.
  • Ruby codec: Symbols, NaN/Infinity/-0 and non-string-key hashes have markers; pitfalls entry about unencodable results is covered by tests/ruby_recording.rs (it asserts the recording file is kept on failure).
  • Kotlin: tree-sitter supertype pitfall is handled (collect reads function_declaration directly under class_body); @JvmStatic/companion/@file:JvmName/private/internal/extension/suspend/inline/generic and repeated names are blocked or placed on the right JVM owner (kotlin.rs:604-918); unknown types fail closed to uses the class (typealiases and (Int)->Int without spaces are blocked, not guessed).
  • C#: decimal, ulong, char, object, delegates, Task, tuples, unknown types, ref/out/in/params, generics and overloaded names are blocked; records/POCOs are resolved only when plain.
  • Swift: closures, inout, Set, Character, Decimal, Date, optional some/any, generics, async, rethrows, variadics, @objc and overloads are blocked with reasons; the Int trap is recorded as trap and matched (tests/swift.rs mutates the port with wrapping_add and with chars().count() and expects diff to fail).
  • PowerShell: filter, workflow, begin/process blocks, $input, $PSCmdlet/$args, pipeline-bound parameters, script blocks, [ref] and unknown .NET types are blockers; the wrapper reuses the original param() block so defaults and validation attributes stay in PowerShell (tests/powershell.rs checks it and mutates the port).
  • tests/powershell.rs, tests/swift.rs, tests/ruby_recording.rs skip with a printed skipped: ... when the runtime is missing, and RUST_ANYTHING_REQUIRE turns that into a failure (tests/common/mod.rs:3,39); the first test of each of the PowerShell and Swift files (bridge only) runs without the runtime. STATUS marks all of them "Tested", not "Verified".
  • Comments and string contents do not produce AST-based risks (Ruby, PHP, C#, Swift, PowerShell); only Kotlin's substring heuristics can (A6b-08).