Skill: neo-python-to-go-converter (version 1.0.0)

--- name: python-to-go-converter description: Automatically converts Python code to optimized Go code for performance-critical applications. --- # SKILL.md — Python to Go Converter ## Overview This skill automatically converts Python source code to idiomatic, compilable Go code. It handles type mappings, import translations, and produces clean Go output suitable for performance-critical applications. ## Capabilities - Convert Python source files to Go with preserved functionality - Intelligent Python-to-Go type mapping (int, str, list, dict, classes, etc.) - Translate common Python standard library imports to Go equivalents - Generate properly formatted Go code with comments - Provide detailed error diagnostics for unsupported Python features - CLI interface for batch conversion and agent integration - Support for functions, classes, control flow, and basic data structures ## Installation The skill is installed as part of an OpenClaw skill package. Ensure dependencies are met (Python 3.8+, `go` compiler in PATH). ## Usage ### CLI Invocation ```bash python-to-go-converter convert <input.py> [--output <output.go>] ``` ### Agent Integration The skill exposes a single-turn execution model. Provide Python code as input, receive Go code as output. ### Examples ```bash # Convert a single file python-to-go-converter convert examples/basic.py --output output.go # Convert with diagnostics python-to-go-converter convert myscript.py --verbose ``` ## Error Handling The converter produces non-zero exit codes on failure and writes diagnostics to stderr. Common errors include: - Unsupported Python syntax (decorators, metaclasses, async generators) - Library dependencies without Go equivalents - Type inference failures See `error_codes.json` for the full error catalog. ## Files - `scripts/converter.py` — Main CLI and conversion orchestration - `scripts/ast_parser.py` — Python AST parsing and analysis - `scripts/go_generator.py` — Go code emission and formatting - `scripts/type_mapper.py` — Type system translation rules - `scripts/import_handler.py` — Import resolution and library mapping - `references/python_to_go_mappings.json` — Feature mapping table - `references/stdlib_equivalents.json` — Standard library translations - `references/error_codes.json` — Error code definitions - `examples/` — Example conversions and test cases - `tests/` — Unit tests and validation suite ## Limitations - Does not convert GUI frameworks (Tkinter, PyQt) - No support for dynamic metaprogramming (eval, exec, setattr magic) - Machine learning libraries (NumPy, TensorFlow) require manual rewrite - Perfect 1:1 runtime behavior is not guaranteed; testing required ## Performance Typical conversion times: small scripts (<100 LOC) < 1s; medium (500 LOC) ~2-3s; large codebases scale linearly. Conversion is CPU-bound on Python parsing and AST traversal. ## Support For issues, feature requests, or contributions, refer to the skill repository.

path: README.md
content: # python-to-go-converter

![Audit](https://img.shields.io/badge/audit%3A%20PASS-brightgreen) ![License](https://img.shields.io/badge/license-MIT-blue) ![OpenClaw](https://img.shields.io/badge/OpenClaw-skill-orange)

> A skill that automatically converts Python code to equivalent Go code for performance-critical applications.

I don't see any previous context or attempt in this session. Could you tell me what task you were working on or what you'd like me to continue with?

## Installation

The skill is installed as part of an OpenClaw skill package. Ensure dependencies are met (Python 3.8+, `go` compiler in PATH).

## OpenClaw Marketplace

This skill is available on [ClawHub](https://clawhub.ai) — the OpenClaw skill marketplace.
Install it in any OpenClaw agent workspace with:

```bash
clawhub install python-to-go-converter
```

**Recommended price when commercial:** $29 USD

## License

MIT © NeoSkillFactory


path: assets/basic.go
content: package main

import "fmt"

func add(x int, y int) int {
	return x + y
}

func main() {
	result := add(3, 5)
	fmt.Println("Result:", result)
}


path: assets/basic.py
content: def add(x: int, y: int) -> int:
    return x + y

def main():
    result = add(3, 5)
    print("Result:", result)


path: assets/complex.go
content: package main

import "fmt"

func factorial(n int) int {
	if n <= 1 {
		return 1
	}
	return n * factorial(n-1)
}

func sum_range(start int, end int) int {
	total := 0
	for i := start; i < end; i++ {
		total += i
	}
	return total
}

func first_even() int {
	nums := []int{1, 3, 5, 8, 10}
	for _, x := range nums {
		if x%2 == 0 {
			return x
		}
	}
	return -1
}

func assert_demo(x int) {
	if !(x > 0) {
		panic("x must be positive")
	}
	fmt.Println("x is positive:", x)
}

func main() {
	fmt.Println("Factorial 5:", factorial(5))
	fmt.Println("Sum 1..9:", sum_range(1, 10))
	fmt.Println("First even:", first_even())
	assert_demo(42)
}


path: assets/complex.py
content: def factorial(n: int) -> int:
    if n <= 1:
        return 1
    return n * factorial(n - 1)

def sum_range(start: int, end: int) -> int:
    total = 0
    for i in range(start, end):
        total += i
    return total

def first_even() -> int:
    nums = [1, 3, 5, 8, 10]
    for x in nums:
        if x % 2 == 0:
            return x
    return -1

def assert_demo(x: int):
    assert x > 0, "x must be positive"
    print("x is positive:", x)

def main():
    print("Factorial 5:", factorial(5))
    print("Sum 1..9:", sum_range(1, 10))
    print("First even:", first_even())
    assert_demo(42)


path: package.json
content: {
  "name": "openclaw-skill-python-to-go-converter",
  "version": "1.0.0",
  "description": "Automatically converts Python code to optimized Go code for performance-critical applications.",
  "main": "scripts/converter.py",
  "scripts": {
    "convert": "python scripts/converter.py",
    "test": "python -m pytest tests/"
  },
  "keywords": [
    "openclaw",
    "skill",
    "python",
    "go",
    "converter",
    "transpiler"
  ],
  "author": "",
  "license": "MIT",
  "dependencies": {},
  "devDependencies": {},
  "engines": {
    "node": ">=14"
  }
}


path: references/best_practices.md
content: # Best Practices for Python-to-Go Conversion

This guide provides recommendations for writing Python code that converts cleanly to Go, and for refining the generated output. Following these practices will improve conversion success rates and reduce manual post-processing.

## Writing Python Code for Conversion

### 1. Use Explicit Type Annotations

Strongly-typed code yields more accurate Go types.

**Good:**
```python
def process(name: str, age: int) -> str:
    return f"{name} is {age} years old"
```

**Bad:**
```python
def process(name, age):
    return name + " is " + str(age) + " years old"
```

### 2. Avoid Dynamic Features

Stick to static constructs. Avoid `eval`, `exec`, `getattr`, `setattr`, `hasattr`, and `import *`.

### 3. Prefer Simple Loops Over Comprehensions

List comprehensions are not supported. Use explicit `for` loops.

**Good:**
```python
result = []
for x in items:
    result.append(x * 2)
```

**Bad:**
```python
result = [x * 2 for x in items]
```

### 4. Use `for` Loops Instead of `while`

`while` loops currently generate invalid Go code. Use `for` with a condition or `range`.

**Good:**
```python
while True:  # still problematic; better:
for { ; condition;  } not directly, but you can break
def process_until(limit):
    i = 0
    while i < limit:  # problematic
        i += 1
# Better: use for with break if needed
def process_until(limit):
    for i := 0; i < limit; i++ { ... } # not Python
# In Python, you can still use while but will need to edit output
```
Actually, avoid loops that rely on while; prefer for loops over iterables or explicit counters with break.

**Better Python for conversion:**
```python
def process_up_to(n):
    for i in range(n):
        # do work
        if some_condition:
            break
```

### 5. Stick to Supported Built-in Functions

Only `print`, `len`, and `range` (in `for`) are reliably translated. Avoid `enumerate`, `zip`, `map`, `filter`, etc.

**Manual counter example:**
```python
i = 0
for item in items:
    # use i and item
    i += 1
```

### 6. Use `try/except` Sparingly

`try/except` blocks are not converted. If exception handling is critical, you may need to rewrite using explicit error checks after conversion.

Consider structuring code to avoid exceptions in the first place (check preconditions). Or accept that `try` bodies will be inserted without handling, and panics will propagate.

### 7. Use `assert` for Preconditions

`assert` converts nicely to `if !cond { panic(...) }`. This is a good way to embed sanity checks.

### 8. Favor Simple Data Structures

`list` and `dict` with homogeneous types yield better Go types (`[]int`, `map[string]string`). Heterogeneous collections default to `interface{}`.

**Good:**
```python
nums = [1, 2, 3]  # -> []int
ages = {"alice": 30, "bob": 25}  # -> map[string]int
```

**Mixed:**
```python
mixed = [1, "two", 3.0]  # -> []interface{}
```

### 9. Avoid Mutable Default Arguments

Python's `def f(x=[])` is a trap; the default is shared. In Go, default arguments are not supported at all, so such patterns will require manual handling anyway. Avoid defaults, or use `None` and set inside.

### 10. Keep Classes Simple

Classes should mainly contain data attributes assigned in `__init__` and simple methods. Avoid complex inheritance, descriptors, properties, and magic methods beyond `__init__`.

**Good:**
```python
class Point:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y
    def distance(self) -> float:
        return (self.x**2 + self.y**2)**0.5
```

### 11. Use `os` and `fmt` Packages

When interacting with the file system or formatting, Python's `os` and `fmt` (print) are supported at the import level. However, specific function calls may need manual adjustment.

### 12. Limit Return Types to Simple Types

Returning tuples (multiple values) is supported in the sense that Go can return multiple values. The converter may handle `return a, b` as `return a, b`. However, tuple literals in other contexts are problematic.

```python
def min_max(nums):
    return min(nums), max(nums)  # This might work if min/max are defined elsewhere.
```

## After Conversion: Manual Refinement

Even with perfect input, the generated Go may need adjustments:

1. **Run `gofmt`** to format the code.
2. **Fix `while` loops** if present: replace `while condition {` with `for condition {`.
3. **Replace stub imports**: If you used unsupported stdlib modules, replace calls with proper Go equivalents.
4. **Add error handling**: Convert any Python exceptions to Go error returns. For `panic` calls from `raise`, consider whether they should be `return err`.
5. **Strengthen types**: Replace `interface{}` with concrete types where possible.
6. **Add missing imports**: The converter adds imports based on Python imports, but if you introduced new Go functions (e.g., `strconv.Atoi`), you must add `import "strconv"`.
7. **Check for variable scoping issues**: Ensure variables declared inside blocks are not incorrectly used outside.
8. **Review method receivers**: The converter uses pointer receivers `(c *ClassName)`. If methods do not modify the receiver, consider using value receivers for efficiency.
9. **Rename methods**: Python's `snake_case` is preserved (e.g., `my_method`). Go prefers `CamelCase` for exported methods. Adjust as needed.
10. **Add tests**: Write Go tests to verify behavior matches the original Python code.

## Example Workflow

1. Write clean Python code with type hints.
2. Run converter: `python-to-go-converter convert input.py --output output.go --verbose`
3. Inspect `output.go` for comments indicating unsupported features.
4. Fix any `while` loops.
5. Replace any placeholder or stub functions (e.g., `internal/enumerate`).
6. Add proper error handling where `panic` appears (unless panic is intended).
7. Run `go build output.go` to compile; address errors.
8. Add missing imports based on compiler errors.
9. Run `go test` if you have a test suite.
10. Refactor to improve idiomatic Go (use `go vet`, `golint`).

## Conclusion

Treat the converter as a **boilerplate generator**, not a fully automated migration tool. Its value is in producing a first draft that captures the control flow and data structure layout. Human refinement is essential for robust, production-ready Go code.


path: references/conversion_rules.md
content: # Conversion Rules

This reference describes the transformation rules applied by the Python-to-Go converter. It details how each Python AST node type is translated into Go code.

## General Principles

- The generated Go code always begins with `package main` unless overridden (future work).
- Imports are automatically added based on Python imports and the mapping table.
- Top-level statements become top-level declarations in Go (functions, variables, etc.).
- Indentation uses tabs.
- Comments originating from the Python source are preserved where possible; the converter adds its own comments for unsupported features.

## Statements

### Function Definition (`def`)

**Python:**

```python
def name(arg1: type1, arg2: type2 = default) -> return_type:
    body
```

**Go:**

```go
func name(arg1 type1, arg2 type2) return_type {
    body
}
```

**Rules:**
- Python function becomes a Go function.
- Arguments with type annotations use the mapped Go types.
- Arguments without annotations default to `interface{}`.
- Default argument values are **not** currently handled; they should be provided manually in Go.
- Return type annotation is mapped; if absent, the function returns no value (or `interface{}` if return statements have mixed types).
- Decorators are ignored (converter does not apply them).
- The function body is translated statement by statement.

**Example:**

```python
def greet(name: str) -> str:
    return "Hello, " + name
```

```go
func greet(name string) string {
    return "Hello, " + name
}
```

---

### Class Definition (`class`)

**Python:**

```python
class ClassName(Base):
    def __init__(self, x: int):
        self.x = x
    def method(self, y: int) -> int:
        return self.x + y
```

**Go:**

```go
type ClassName struct {
    x int
}
func (c *ClassName) Init(x int) {
    c.x = x
}
func (c *ClassName) Method(y int) int {
    return c.x + y
}
```

**Rules:**
- A Python class becomes a Go `struct`.
- Instance fields are discovered by scanning the class body for assignments to `self.attr`. The type is inferred from the assigned value.
- Methods (`def` inside a class) become Go methods with a receiver. The first parameter named `self` (or conventionally `self`) is omitted and replaced by a receiver `(c *ClassName)`.
- `__init__` is renamed to `Init` (capitalized for exportability). It is treated as a regular method; the constructor pattern in Go is manual (usually a `NewClassName` function, not automatically generated yet).
- Inheritance (`class ClassName(Base):`) is **not** supported directly. Go uses composition. The converter does not generate struct embedding for base classes. It will output a comment and ignore bases.

**Limitations:**
- Only simple attributes assigned directly to `self` are recognized. Properties, class variables, and dynamic attributes are not.
- Method resolution order and overriding are not translated; Go interfaces handle behavior differently.
- `super()` calls are not converted.

---

### Assignment (`=`)

**Python:**

```python
x = 42
name = "Alice"
nums = [1, 2, 3]
m = {"a": 1, "b": 2}
```

**Go:**

```go
x := 42
name := "Alice"
nums := []interface{}{1, 2, 3} // or []int if elements homogeneous
m := map[string]interface{}{"a": 1, "b": 2}
```

**Rules:**
- Simple target assignments use short variable declaration (`:=`) when the variable is first encountered in the scope. If the variable already exists in `known_vars`, a regular assignment (`=`) is used.
- Multiple targets (tuple unpacking) are not fully supported; the converter will emit a comment.
- Assignment to attributes (`self.x = value`) becomes `receiver.Attr = value`.
- Assignment to subscripts (`a[0] = x`) becomes `a[0] = x`.

---

### Augmented Assignment (`+=`, `-=`, etc.)

**Python:** `x += 1`

**Go:** `x += 1`

**Rules:** Direct mapping using operator translation. Supported for `+=`, `-=`, `*=`, `/=`, `%=`.

---

### If Statement

**Python:**

```python
if condition:
    body
elif other:
    body2
else:
    body3
```

**Go:**

```go
if condition {
    body
} else if other {
    body2
} else {
    body3
}
```

**Rules:** Straightforward structural translation. The condition expression is translated according to expression rules.

---

### For Loop

**Python:**

```python
# Iteration over a sequence
for item in seq:
    body

# Range-based numeric loop
for i in range(10):
    body

# Range with start/stop
for i in range(2, 10):
    body

# Range with step
for i in range(0, 10, 2):
    body

# Unpacking (limited)
for idx, val in enumerate(seq):
    body
```

**Go:**

```go
// Iteration over a sequence (slice, array, map, channel)
for _, item := range seq {
    body
}

// Numeric range: range(10) -> i from 0 to 9
for i := 0; i < 10; i++ {
    body
}

// range(2, 10)
for i := 2; i < 10; i++ {
    body
}

// range(0, 10, 2)
for i := 0; i < 10; i += 2 {
    body
}

// enumerate(seq) -> currently mapped to internal/enumerate (not implemented); avoid.
```

**Rules:**
- For loops over iterables use Go's `range` construct. The loop variable takes the place of the Python target.
- If the Python for-loop uses `range()` with up to three arguments, the converter expands it into a C-style `for` initialization; condition; post statement.
- Unpacking the tuple returned by `enumerate` is not supported in Go translation; `enumerate` currently maps to an undefined internal package. Use a manual counter if needed.

---

### While Loop

**Python:**

```python
while condition:
    body
```

**Go:**

```go
for condition {
    body
}
```

**Rules:** The converter currently emits `while` loops as `while { ... }` which is invalid Go; this is a known limitation. The expected correct translation should be `for condition { ... }`. As a workaround, avoid `while` loops or manually rewrite them as `for` loops in the Python code (e.g., `while True` -> `for { ... }` with break). The development version may have this bug.

---

### Return Statement

**Python:**

```python
return expression
# or
return
```

**Go:**

```go
return expression
// or
return
```

**Rules:** Direct translation. The expression's type must match the function's return type.

---

### Expression Statement

Any expression used as a statement (e.g., a function call, a binary operation) is emitted as a standalone statement in Go. For `print(...)`, it becomes `fmt.Println(...)`.

---

### Pass

**Python:** `pass`

**Go:** `// pass`

**Rules:** Replaced with an empty comment to maintain line numbering.

---

### Break and Continue

**Python:** `break` / `continue`

**Go:** `break` / `continue`

**Rules:** Direct mapping. They affect the innermost `for` loop.

---

### Delete

**Python:** `del x`

**Go:** `// delete not supported`

**Rules:** Go has no equivalent. The statement is replaced with a comment and ignored.

---

### Raise

**Python:**

```python
raise Exception("msg")
```

**Go:**

```go
panic("msg")
```

**Rules:** All exceptions become panics. This is a drastic but simple translation. Go's `panic` unwinds the stack similar to uncaught exceptions.

---

### Try/Except

**Python:**

```python
try:
    body
except SomeError as e:
    handler
except OtherError:
    handler2
else:
    else_body
finally:
    finally_body
```

**Go:**

```go
// try/except block not automatically converted; manual error handling needed
body
```

**Rules:** The converter currently does not translate structured exception handling to Go's `if err != nil` pattern. The entire `try` statement is replaced with a comment and the body is executed as normal statements. Any `raise` inside will panic. Proper conversion requires manual intervention.

---

### Assert

**Python:**

```python
assert condition, "message"
```

**Go:**

```go
if !condition {
    panic("message")
}
```

**Rules:** Direct translation; if no message is provided, the panic uses `"assertion failed"`.

---

### Unsupported Statements

If a statement type is not recognized, the converter emits a comment indicating the unknown type.

## Expressions

### Constants

| Python Value | Go Literal |
|--------------|------------|
| `None`       | `nil` (or `interface{}`) |
| `True`       | `true` |
| `False`      | `false` |
| `42`         | `42` |
| `3.14`       | `3.14` |
| `"hello"`    | `"hello"` (with escapes) |
| `b"abc"`     | `[]byte("abc")` |

### Names (Variables)

A variable name is emitted as its identifier. If the variable is not known in the current scope, it is assumed to be of type `interface{}`.

### Function Calls

**General:** `func(arg1, arg2, kw=val)` → `func(arg1, arg2, val)` *(note: keyword arguments are not supported in Go; they are passed as regular arguments)*.

**Built-in Functions:**

| Python      | Go                         | Notes |
|-------------|----------------------------|-------|
| `print(...)` | `fmt.Println(...)`        | Variadic |
| `len(x)`    | `len(x)`                  | Works for slices, arrays, maps, strings |
| `range(...)` | `range(...)`              | Used only in for loops; the form `range(a, b, c)` is not valid Go, so the converter rewrites the loop itself, not the expression. |
| `enumerate(seq)` | `internal/enumerate` | Not implemented; avoid. |

**Other calls:** The function expression is translated, and arguments are translated recursively. If the function is an attribute access (e.g., `obj.method()`), the receiver is translated accordingly.

### Attribute Access

**Python:** `obj.attr`

**Go:** `obj.attr`

The base object and attribute name are translated. No property getter/setter logic is added.

### Binary Operations

Operators are mapped according to `python_to_go_mappings.json`:

| Python Operator | Go Operator |
|-----------------|-------------|
| `+`             | `+` |
| `-`             | `-` |
| `*`             | `*` |
| `/`             | `/` (float division; Python `/` is float division even for ints) |
| `%`             | `%` |
| `==`            | `==` |
| `!=`            | `!=` |
| `<`             | `<` |
| `<=`            | `<=` |
| `>`             | `>` |
| `>=`            | `>=` |
| `and`           | `&&` |
| `or`            | `||` |
| `not`           | `!` |

Notes:
- Python's integer division (`//`) is not supported.
- Bitwise operators (`&`, `|`, `^`, `~`, `<<`, `>>`) are not mapped (would need to be added if encountered).

### Unary Operations

| Python | Go |
|--------|----|
| `not x`| `!x` |
| `+x`   | `+x` |
| `-x`   | `-x` |

### Comparisons

Chained comparisons (e.g., `a < b < c`) are translated to logical AND: `a < b && b < c`.

### Boolean Operations

`a and b` → `a && b`<br>
`a or b` → `a || b`

### List Literals

**Python:** `[1, 2, 3]` or `[]`

**Go:** `[]interface{}{1, 2, 3}` or `[]interface{}{}`

If all elements are of the same type, a more specific slice type may be emitted: `[]int{1, 2, 3}`.

### Tuple Literals

**Python:** `(a, b, c)`

**Go:** `/* tuple */ (a, b, c)`

Tuples are not directly represented in Go as a single value. They may appear in multiple assignment contexts (e.g., return multiple values) but in expression contexts the converter produces a placeholder.

### Dictionary Literals

**Python:** `{"key": value}`

**Go:** `map[string]interface{}{"key": value}` or `map[K]V` if key/value types are uniform.

### Subscript (Indexing)

**Python:** `obj[key]`

**Go:** `obj[key]`

Same syntax. For dicts, slices, arrays, strings.

### Lambda Expressions

**Python:** `lambda x: x + 1`

**Go:** `func(x) { return x + 1 }`

**Rules:** The lambda body is a single expression. Parameters are taken from the lambda's argument list. The return type is inferred as `interface{}` (or from lambda usage if known). This is a simplistic translation; real-world lambdas may need manual adjustment.

### List Comprehensions, Generator Expressions, etc.

These are marked as `unsupported` and will be skipped with a warning.

## Scoping and Variable Lifetime

- The converter maintains a simple scope stack. Variables declared with `:=` are added to the current scope's `known_vars`. They persist through the function or top-level scope.
- No block-level scoping (like in Go) is enforced; the converter's `known_vars` dictionary may incorrectly allow a variable declared in an `if` block to be used outside. Go would treat that as an error. Manual cleanup may be needed.

## Comments

- Python comments (`# ...`) are **not** preserved through AST parsing. The converter does not embed them in the output. Consider adding docstrings or explicit comments in code that needs to survive conversion.

## TODOs and FIXMEs

The following areas need improvement:
- Proper `while` translation (use `for`).
- Support for `else` clauses on loops.
- Better conversion of `try/except` to Go `if err != nil`.
- Handling of default argument values.
- Handling of `*args` and `**kwargs`.
- Conversion of `is` and `is not` (identity checks) to pointer comparisons or interface equality.
- Bitwise operators.
- Complex number support.
- `import *` and relative imports.


path: references/error_codes.json
content: {
  "E001": {
    "message": "Unsupported Python syntax: {feature}",
    "description": "The converter encountered a Python feature that is not supported."
  },
  "E002": {
    "message": "Unsupported library: {library}",
    "description": "The Python library has no Go equivalent mapping."
  },
  "E003": {
    "message": "Type inference failed for expression: {expr}",
    "description": "Could not determine Go type for the given expression."
  },
  "E004": {
    "message": "Invalid output path: {path}",
    "description": "The specified output file path is not writable."
  },
  "E005": {
    "message": "Input file not found: {path}",
    "description": "The specified Python file does not exist."
  },
  "E006": {
    "message": "Go compilation failed: {error}",
    "description": "Generated Go code did not compile."
  }
}

path: references/error_codes.md
content: # Error Codes

This document provides detailed explanations for all error codes emitted by the Python-to-Go converter. Understanding these codes helps users diagnose conversion failures and adjust their Python code accordingly.

## E001: Unsupported Python syntax

**Message:** `Unsupported Python syntax: {feature}`

**Description:** The converter encountered a Python language feature that is not implemented. The `{feature}` placeholder indicates the name of the unsupported construct (e.g., "async function", "list comprehension", "with statement").

**Common Causes:**
- Use of `async` / `await`
- `with` context managers
- List/dict/set comprehensions
- Generator expressions
- Metaprogramming (`eval`, `exec`, `setattr` on types)
- Decorators (some are supported but may produce warnings)
- Certain complex expressions

**Resolution:** Rewrite the code to avoid unsupported features. Often, an equivalent construct using basic loops and conditionals can be used. For example, replace list comprehensions with explicit `for` loops.

---

## E002: Unsupported library

**Message:** `Unsupported library: {library}`

**Description:** The Python import `{library}` has no known Go equivalent mapping in `stdlib_equivalents.json`.

**Common Causes:**
- Importing third-party libraries (e.g., `numpy`, `pandas`, `requests`)
- Importing standard library modules that have not been mapped (e.g., `re`, `collections`, `itertools`)
- Misspelled module names

**Resolution:** Remove or replace unsupported imports. For missing stdlib modules, consider adding a mapping to `stdlib_equivalents.json` if a suitable Go package exists. For third-party libraries, you may need to write the corresponding Go code manually.

---

## E003: Type inference failed

**Message:** `Type inference failed for expression: {expr}`

**Description:** The type inference engine could not determine a Go type for the given expression. The `{expr}` placeholder shows a snippet of the expression (or its AST node type).

**Common Causes:**
- Expressions with mixed types that cannot be resolved (e.g., adding a string to an int)
- Lambda expressions with no type hints
- Dynamic attribute access (`getattr`, arbitrary attribute on a variable)
- Complex nested structures with inconsistent element types

**Resolution:** Provide explicit type annotations in the Python code. For ambiguous expressions, break them into smaller steps with typed variables.

---

## E004: Invalid output path

**Message:** `Invalid output path: {path}`

**Description:** The specified output file path is not writable. The path may be a directory, lack write permissions, or the filesystem may be full.

**Resolution:** Choose a different output file location, ensure the directory exists and is writable, or output to stdout by omitting `--output`.

---

## E005: Input file not found

**Message:** `Input file not found: {path}`

**Description:** The Python source file specified as input does not exist at the given path.

**Resolution:** Provide a correct path to an existing `.py` file.

---

## E006: Go compilation failed

**Message:** `Go compilation failed: {error}`

**Description:** The generated Go code was written to a file, but when `go vet` or `go build` was attempted (if `--check` flag is used), compilation failed. The `{error}` contains the compiler output.

**Common Causes:**
- Generated code contains syntax errors (unlikely but possible for unsupported features)
- Missing imports for used functions
- Incorrect type conversions
- Use of features that cannot be directly represented in Go

**Resolution:** Examine the generated `.go` file to identify issues. Consider adjusting the Python code to use supported constructs, or report a bug if the generated code is valid but the compiler rejects it incorrectly.

---

## Non-Zero Exit Codes

The converter exits with the numeric part of the error code (e.g., `E001` → exit code 1). A successful conversion exits with code `0`.

## Diagnostics

For more insight, run the converter with the `--verbose` flag. It prints:
- Detected Python imports
- Resolved Go imports
- Warnings about unsupported features that are skipped

## Troubleshooting Checklist

1. **Unsupported syntax?** Look for `E001` and refactor code to avoid the indicated feature.
2. **Library not found?** Check `E002` and remove or replace the import.
3. **Type errors?** Add type hints or break complex expressions.
4. **Compilation fails?** Inspect generated Go file. Ensure you have a recent Go version.
5. **Blank or incomplete output?** Verify the input file contains supported statements; unsupported statements are replaced with comments.

## Reporting Issues

If you encounter an error that you believe is incorrect or the converter should handle, please provide:
- The original Python code
- The full error message and exit code
- The generated Go output (if any)
- The verbose log (`--verbose`)

Submit issues via the skill repository's issue tracker.


path: references/python_to_go_mappings.json
content: {
  "types": {
    "int": "int",
    "float": "float64",
    "str": "string",
    "bool": "bool",
    "list": "[]interface{}",
    "dict": "map[string]interface{}",
    "None": "nil",
    "bytes": "[]byte"
  },
  "operators": {
    "Add": "+",
    "Sub": "-",
    "Mult": "*",
    "Div": "/",
    "Mod": "%",
    "Eq": "==",
    "NotEq": "!=",
    "Lt": "<",
    "LtE": "<=",
    "Gt": ">",
    "GtE": ">=",
    "And": "&&",
    "Or": "||",
    "Not": "!"
  },
  "functions": {
    "print": "fmt.Println",
    "len": "len",
    "range": "range",
    "enumerate": "internal/enumerate"
  }
}

path: references/standard_library.md
content: # Standard Library Equivalents

## Introduction

When converting Python code to Go, the `import_handler` module translates Python standard library imports to their corresponding Go packages. This document details the currently supported mappings and highlights any behavioral differences.

## Mapping Table

The mapping is defined in `references/stdlib_equivalents.json`. The following modules are supported:

| Python Module       | Go Import Path        | Description |
|---------------------|-----------------------|-------------|
| `os`                | `os`                  | File system operations, environment variables, process management. |
| `sys`               | `sys`                 | System-specific parameters and functions (limited). |
| `json`              | `encoding/json`       | JSON encoding and decoding. |
| `math`              | `math`                | Basic mathematical functions. |
| `strings`           | `strings`             | String manipulation utilities. |
| `fmt`               | `fmt`                 | Formatted I/O (mostly used by `print`). |
| `time`              | `time`                | Time and date operations. |
| `io`                | `io`                  | Basic I/O interfaces. |
| `os.path`           | `path/filepath`       | Path manipulation (POSIX vs Windows differences). |

## Behavioral Notes

### `os`

- The `os` package in Go provides similar functionality to Python's `os`. However:
  - File operations: `os.Open`, `os.ReadFile`, `os.WriteFile` replace `open`, `read`, `write`.
  - The converter does **not** automatically rewrite `os` method calls; it only translates the import. The actual function calls must be manually adapted or may be unsupported.
  - The current scope of conversion covers only the import translation and simple `print` statements, not deep API rewrites.

### `sys`

- Only a subset of `sys` may be mapped. For example, `sys.argv` is not translated; Go uses `os.Args`. Import mapping only.

### `json`

- Python's `json` module functions (`loads`, `dumps`, `load`, `dump`) map to `encoding/json` functions (`Unmarshal`, `Marshal`, `NewDecoder`, `NewEncoder`). The API is different; conversion of calls is not currently performed automatically. The import is provided for when you manually write Go code.

### `math`

- Most mathematical constants and functions have analogs. Function names are similar but may differ in casing (Go uses `Sin`, `Cos`, etc.). Conversion of `math.sqrt(x)` would require rewriting to `math.Sqrt(x)` — not automatic.

### `strings`

- Functions like `strings.ToUpper`, `strings.Join`, `strings.Split` have similar counterparts in Python's `str` methods. Import mapping only.

### `path/filepath` (from `os.path`)

- `os.path.join` becomes `path.Join`. `os.path.dirname` becomes `path.Dir`. However, automatic rewriting of these calls is not implemented; the import is provided for manual use.

## Unsupported Modules

Modules not listed in the mapping will trigger error `E002` ("Unsupported library") during conversion. The converter will still attempt to generate Go code but will skip those imports. It is recommended to either remove unsupported imports or provide fallback stubs.

## Extending the Mapping

The `stdlib_equivalents.json` file can be extended to include additional mappings. For third-party Python libraries, there is no automatic Go equivalent; manual rewrites are required.

## Example

```python
import os
import json
import math

def read_config(path):
    with open(path) as f:
        return json.load(f)
```

Converted Go (illustrative only; `with` is not supported, so this code would not fully convert):

```go
package main

import (
    "os"
    "encoding/json"
    "math"
)

func readConfig(path string) interface{} {
    // Note: with statement not supported; manual rewrite needed
    // content, err := os.ReadFile(path)
    // ...
    return nil
}
```

In this example, the import statements are automatically derived. However, the body of `read_config` contains unsupported features (`with`, `json.load`) and would be partially translated or flagged.

## Best Practices

- Prefer standard library APIs that have direct Go equivalents.
- Avoid complex or obscure modules if conversion is the goal.
- Use explicit type hints to improve type inference.
- When an import is unsupported, consider refactoring to a supported alternative.


path: references/stdlib_equivalents.json
content: os: os
sys: sys
json: encoding/json
math: math
strings: strings
fmt: fmt
time: time
io: io
os.path: path/filepath

Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)