skills/code-analysis/code-translation/SKILL.md
Translates a single function or small code unit between programming languages, mapping idioms and preserving observable behavior. Use when porting one function, when the user pastes code and asks for it in another language, or as the per-unit primitive for larger migrations.
npx skillsauth add santosomar/general-secure-coding-agent-skills code-translationInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Function-level translation between languages. The goal is observably equivalent behavior — same inputs → same outputs, same side effects, same error behavior. Not line-by-line transliteration; idiomatic code in the target.
For whole modules/packages, → module-level-code-translator (handles imports, file structure, cross-function concerns).
for x in xs ↔ for (auto& x : xs). Mechanical.3 / 2 is 1 in Python 2, 1.5 in Python 3, 1 in C. Integer overflow, null semantics, string encoding.[x*2 for x in xs if x > 0] → Java stream, not a for-loop with an ArrayList. Optional but expected.| Source → Target | What silently changes |
| ---------------- | ---------------------------------------------------------------- |
| Python → Java | int unbounded → int 32-bit overflow. / float vs int. Dicts ordered since 3.7 — HashMap isn't. None vs checked exceptions. |
| Java → Python | int overflow at 2³¹ → Python never overflows. == on objects is identity, not equality. Checked exceptions disappear. |
| C++ → Rust | UB becomes panic or won't compile. Raw pointers need lifetime decisions. Move semantics are default, not opt-in. Implicit conversions gone. |
| JS → TypeScript | Mostly additive (types) — but == coercion stays, strictNullChecks changes nullability. |
| Python → Go | Exceptions → explicit error returns. Duck typing → interfaces. No default args. **kwargs has no equivalent. |
| C → Go | Manual memory → GC. Pointer arithmetic gone. goto cleanup → defer. No unions. |
Before translating, write down the three semantic mismatches that matter for this function. Check them in the output.
| Pattern (Python) | Java | Go | Rust |
| ----------------------------------- | ---------------------------------------- | ------------------------------------ | ------------------------------------- |
| [f(x) for x in xs] | xs.stream().map(f).toList() | for-append loop | xs.iter().map(f).collect() |
| {k: v for k, v in ...} | Collectors.toMap(...) | make + loop | HashMap::from_iter(...) |
| try/except for control flow | Anti-pattern — check first | if err != nil | Result<T, E> / ? |
| with open(...) as f: | try-with-resources | defer f.Close() | Drop (automatic) |
| *args, **kwargs | Overloads or a params object | variadic (...T) — no kwargs | No direct — builder or options struct |
| Multiple return values | Record/Pair (awkward) | Native — (T, error) | Tuple or struct |
Python:
def top_k(items, k, key=lambda x: x):
"""Return the k largest items by key."""
if k <= 0:
return []
if k >= len(items):
return sorted(items, key=key, reverse=True)
import heapq
return heapq.nlargest(k, items, key=key)
Go translation:
import "sort"
// TopK returns the k largest items by the given key function.
// If k <= 0, returns an empty slice. If k >= len(items), returns all items sorted descending.
func TopK[T any](items []T, k int, key func(T) int) []T {
if k <= 0 {
return nil
}
// Go has no heapq.nlargest — full sort then slice.
// (O(n log n) vs Python's O(n log k). Acceptable unless n is huge and k is small.)
sorted := make([]T, len(items))
copy(sorted, items)
sort.Slice(sorted, func(i, j int) bool {
return key(sorted[i]) > key(sorted[j]) // descending
})
if k >= len(sorted) {
return sorted
}
return sorted[:k]
}
Semantic deltas noted:
key explicitly (or make a TopKInt wrapper).container/heap. Flagged, not fixed — premature optimization.nil vs [] — both are zero-length in Go, but nil is more idiomatic for "empty result."heapq.nlargest doesn't mutate either). Matches.After translating, → behavior-preservation-checker or → multi-version-behavior-comparator: run both versions on the same inputs, diff outputs. Pay attention to edge cases — empty input, k=0, k=len, duplicate keys.
for i in range(len(xs)): f(xs[i]) → don't index in Go/Rust, use for _, x := range xs.heapq.nlargest has no exact Go equivalent — note the complexity tradeoff.str.format → Java String.format, not concatenation. No strcpy in C targets.## Target
<language + version>
## Translation
<code block>
## Semantic deltas
- <what behaves differently, and why it's acceptable or flagged>
## Idiom choices
- <non-obvious mappings — why this Go/Rust/Java pattern and not the literal one>
## Verify with
<example inputs to diff against the source — especially the edge cases>
development
Extracts human-readable pseudocode from a verified formal artifact (Dafny, Lean, TLA+) while preserving the verified properties as annotations, so the proof-carrying logic can be reimplemented in a production language. Use when porting verified code to an unverified target, when documenting what a formal spec actually does, or when handing a verified algorithm to an implementer.
development
Translates natural-language or pseudocode descriptions of concurrent and distributed systems into TLA+ specifications ready for the TLC model checker. Identifies state variables, actions, type invariants, safety properties, and liveness properties from the description. Use when formalizing a protocol, when the user describes a distributed algorithm to verify, when designing a consensus or locking scheme, or when starting formal verification of a concurrent system.
testing
Reduces a TLA+ model so TLC can actually check it — shrinks constants, adds state constraints, abstracts data, or applies symmetry — when the state space is too large to enumerate. Use when TLC runs out of memory, when checking takes hours, or when a spec works at N=2 and you need confidence at larger scale.
development
TLA+-specific instance of model-guided repair — reads a TLC error trace, identifies the enabling condition that should have been false, strengthens the corresponding action, and maps the fix to source code. Use when TLC reports an invariant violation or deadlock and you have the code-to-TLA+ mapping from extraction.