Skip to main content
ClaudeWave
Skill85 repo starsupdated 3mo ago

code-translation

Convert code between programming languages while preserving functionality and semantics. Use when: (1) Translating functions, classes, or modules between languages (Python, JavaScript/TypeScript, Java, Go, Rust, C/C++), (2) Migrating entire projects to a different language, (3) Need idiomatic translation that follows target language conventions, (4) Converting between different paradigms (OOP to functional, etc.), (5) Porting legacy code to modern languages. Provides language-specific patterns, idiomatic translation guides, and project migration strategies.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/code-translation && cp -r /tmp/code-translation/skills/code-translation ~/.claude/skills/code-translation
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Code Translation

Convert code between programming languages while preserving functionality, adapting to target language idioms and best practices.

## Translation Workflow

### 1. Analyze Source Code

Understand what the code does:
- Core functionality and algorithms
- Dependencies and external libraries
- Language-specific features used
- Performance characteristics

### 2. Choose Translation Strategy

**Direct Translation**: Literal conversion maintaining structure
- **Use for**: Simple algorithms, data transformations, utility functions
- **Pros**: Faster, easier to verify correctness
- **Cons**: May not be idiomatic in target language

**Idiomatic Translation**: Adapt to target language patterns
- **Use for**: Production code, public APIs, long-term maintenance
- **Pros**: Native-feeling code, better performance, maintainable
- **Cons**: Takes longer, requires deep language knowledge

**Recommended**: Start with direct translation, then refine to idiomatic.

### 3. Translate Code

Perform the translation following language patterns and conventions.

### 4. Verify Correctness

Ensure translated code behaves identically to source:
- Port existing tests
- Add behavioral tests
- Compare outputs on same inputs

## Quick Translation Examples

### Python → JavaScript

**Source (Python)**
```python
def calculate_total(items):
    """Calculate total price with tax."""
    subtotal = sum(item['price'] * item['quantity'] for item in items)
    tax = subtotal * 0.08
    return subtotal + tax

# Usage
items = [
    {'name': 'Widget', 'price': 10.0, 'quantity': 2},
    {'name': 'Gadget', 'price': 15.0, 'quantity': 1}
]
total = calculate_total(items)
```

**Target (JavaScript)**
```javascript
function calculateTotal(items) {
    // Calculate total price with tax
    const subtotal = items.reduce(
        (sum, item) => sum + item.price * item.quantity,
        0
    );
    const tax = subtotal * 0.08;
    return subtotal + tax;
}

// Usage
const items = [
    { name: 'Widget', price: 10.0, quantity: 2 },
    { name: 'Gadget', price: 15.0, quantity: 1 }
];
const total = calculateTotal(items);
```

### JavaScript → Python

**Source (JavaScript)**
```javascript
async function fetchUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}`);
        }
        return await response.json();
    } catch (error) {
        console.error(`Failed to fetch user: ${error.message}`);
        return null;
    }
}
```

**Target (Python)**
```python
import aiohttp
import logging

async def fetch_user_data(user_id: int) -> dict | None:
    """Fetch user data from API."""
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f'/api/users/{user_id}') as response:
                if not response.ok:
                    raise ValueError(f'HTTP {response.status}')
                return await response.json()
    except Exception as e:
        logging.error(f'Failed to fetch user: {e}')
        return None
```

### Java → Go

**Source (Java)**
```java
public class UserService {
    private final UserRepository repository;

    public UserService(UserRepository repository) {
        this.repository = repository;
    }

    public Optional<User> findById(Long id) {
        return repository.findById(id);
    }

    public List<User> findAll() {
        return repository.findAll();
    }
}
```

**Target (Go)**
```go
type UserService struct {
    repository UserRepository
}

func NewUserService(repository UserRepository) *UserService {
    return &UserService{repository: repository}
}

func (s *UserService) FindById(id int64) (*User, error) {
    return s.repository.FindById(id)
}

func (s *UserService) FindAll() ([]User, error) {
    return s.repository.FindAll()
}
```

## Common Translation Patterns

### Data Structures

**Lists/Arrays**
```python
# Python
numbers = [1, 2, 3]
numbers.append(4)
```
```javascript
// JavaScript
const numbers = [1, 2, 3];
numbers.push(4);
```
```go
// Go
numbers := []int{1, 2, 3}
numbers = append(numbers, 4)
```

**Dictionaries/Maps**
```python
# Python
user = {"name": "Alice", "age": 30}
```
```javascript
// JavaScript
const user = { name: "Alice", age: 30 };
```
```go
// Go
user := map[string]interface{}{
    "name": "Alice",
    "age":  30,
}
```

### Error Handling

**Exceptions → Error Returns**
```python
# Python
def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
```
```go
// Go
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}
```

**Error Returns → Exceptions**
```go
// Go
result, err := divide(10, 0)
if err != nil {
    return err
}
```
```python
# Python
try:
    result = divide(10, 0)
except ValueError as e:
    print(f"Error: {e}")
```

### Async/Concurrency

**Python asyncio → JavaScript async/await**
```python
# Python
async def fetch_all(urls):
    tasks = [fetch(url) for url in urls]
    return await asyncio.gather(*tasks)
```
```javascript
// JavaScript
async function fetchAll(urls) {
    const promises = urls.map(url => fetch(url));
    return await Promise.all(promises);
}
```

**JavaScript Promises → Go Goroutines**
```javascript
// JavaScript
const results = await Promise.all([
    fetchUser(1),
    fetchUser(2),
    fetchUser(3)
]);
```
```go
// Go
var wg sync.WaitGroup
results := make([]*User, 3)

for i := 1; i <= 3; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        results[id-1] = fetchUser(id)
    }(i)
}
wg.Wait()
```

## Translation Decision Tree

```
Is this a complete project migration?
├─ Yes → See [project_migration.md](references/project_migration.md)
│         Follow 8-phase migration process
│
└─ No → Is this a function/class/module?
        │
        ├─ Single function
        │  ├─ Simple logic? → Direct translation
        │  └─ Compl
abstract-domain-explorerSkill

Applies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.

abstract-invariant-generatorSkill

Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.

abstract-state-analyzerSkill

Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.

abstract-trace-summarizerSkill

Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.

acsl-annotation-assistantSkill

Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.

agent-browserSkill

CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

ambiguity-detectorSkill

Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.

api-design-assistantSkill

Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.