arabelatso/skills-4-se/c-cpp-to-lean4-translator
- community
Checking that the SKILL.md file is still in the repository.
Translate C or C++ programs into equivalent Lean4 code, preserving program semantics and ensuring the generated code is well-typed, executable, and can run successfully. Use when the user asks to convert C/C++ code to Lean4, port C/C++ programs to Lean4, translate imperative code to functional Lean4, or create Lean4 versions of C/C++ algorithms.
Install
npx vskill@latest install arabelatso/skills-4-se/c-cpp-to-lean4-translatorSKILL.md
C/C++ to Lean4 Translator
Overview
Transform C or C++ programs into equivalent Lean4 code that preserves the original semantics while leveraging Lean4's functional programming paradigm, strong type system, and proof capabilities.
Translation Workflow
Step 1: Analyze Input Code
Understand the C/C++ program structure and semantics:
- Identify program components:
- Functions and their signatures
- Data structures (structs, classes, arrays)
- Control flow patterns (loops, conditionals)
- Memory management (allocation, pointers)
- I/O operations
- Dependencies and includes
- Understand semantics:
- What does the program compute?
- What are the inputs and outputs?
- Are there side effects?
- What are the invariants and preconditions?
- Note translation challenges:
- Pointer arithmetic
- Mutable state
- Imperative loops
- Manual memory management
- Undefined behavior
Step 2: Design Lean4 Structure
Plan the Lean4 equivalent before writing code:
- Choose appropriate types:
Intfor signed integersNatfor unsigned integers and array indicesFloatfor floating-point numbersArrayfor dynamic arraysListfor linked lists- Custom
structuretypes for structs/classes
- Determine purity:
- Pure functions: return values directly
- Side effects: use
IOmonad - Mutable state: use
IO.ReforSTmonad
- Plan control flow translation:
- Loops → Recursive functions
- Mutable variables → Function parameters
- Early returns → Conditional expressions
- Handle memory:
- Stack allocation → Direct values
- Heap allocation → Automatic memory management
- Pointers → Direct values or references
Step 3: Translate Code
Follow these translation principles:
Functions
Pattern: Pure function
Pattern: Function with side effects
Control Flow
Pattern: If-else
Pattern: For loop → Tail recursion
Pattern: While loop → Recursion
Data Structures
Pattern: Struct
Pattern: Array
Pointers and References
Key principle: Lean4 doesn't have raw pointers. Translate based on usage:
- Read-only pointers: Pass by value
- Output parameters: Return values (use tuples for multiple returns)
- Mutable references: Use
IO.Refor return new values
Step 4: Ensure Type Correctness
Lean4's type system is strict. Address common type issues:
- Integer types:
- Use
Natfor non-negative values (array indices, counts) - Use
Intfor potentially negative values - Convert explicitly:
n.toNat,n.toInt
- Array bounds:
- Lean4 requires proof of valid indices
- Use safe accessors:
arr.get?,arr[i]? - Or use
arr[i]!with runtime check
- Division:
- Natural number division:
n / m(rounds down) - Integer division: use
Int.div - Handle division by zero explicitly
- Type annotations:
- Add explicit types when inference fails
- Use
: Typefor clarity
Step 5: Test and Verify
Ensure the translated code works correctly:
- Compile check:
``bash lake build ``
- Create test cases:
``lean #eval add 2 3 -- Should output 5 #eval factorial 5 -- Should output 120 ``
- Compare outputs:
- Run original C/C++ program
- Run translated Lean4 program
- Verify outputs match for same inputs
- Handle edge cases:
- Empty arrays
- Zero values
- Negative numbers
- Boundary conditions
Step 6: Optimize and Refine
Improve the translated code:
- Use Lean4 idioms:
- Replace manual recursion with
List.foldl,Array.foldl - Use pattern matching instead of nested if-else
- Leverage standard library functions
- Add documentation:
``lean /-- Calculate the sum of first n natural numbers -/ def sum (n : Nat) : Nat := n * (n + 1) / 2 ``
- Consider performance:
- Use tail recursion for loops
- Prefer
ArrayoverListfor random access - Use
@[inline]for small functions
Common Translation Patterns
For detailed patterns, see translation_patterns.md.
Quick Reference
| C/C++ | Lean4 | |
|---|---|---|
int x | def x : Int | |
unsigned int x | def x : Nat | |
float x | def x : Float | |
bool x | def x : Bool | |
char* str | def str : String | |
int arr[] | def arr : Array Int | |
struct S | structure S where | |
for (...) | let rec loop ... | |
while (...) | let rec loop ... | |
if (...) {...} | if ... then ... else ... | |
switch (...) | match ... with | |
return x | x (last expression) | |
void f() | def f : IO Unit | |
printf(...) | IO.println ... |
Examples
Example 1: Simple Algorithm
C/C++ Input:
Lean4 Output:
Example 2: Array Processing
C/C++ Input:
Lean4 Output:
Example 3: Struct with Methods
C/C++ Input:
Lean4 Output:
Example 4: I/O Program
C/C++ Input:
Lean4 Output:
Best Practices
- Start simple: Translate basic functions first, then build up complexity
- Preserve semantics: Ensure the Lean4 code computes the same results
- Use types wisely: Leverage Lean4's type system for correctness
- Embrace immutability: Prefer pure functions over mutable state
- Test thoroughly: Verify outputs match for various inputs
- Document assumptions: Note any semantic differences or limitations
- Leverage standard library: Use built-in functions when available
- Handle errors gracefully: Use
OptionorExceptfor error cases
Limitations and Considerations
- Undefined behavior: C/C++ undefined behavior must be handled explicitly in Lean4
- Performance: Functional code may have different performance characteristics
- Concurrency: C/C++ threading requires different approaches in Lean4
- Low-level operations: Bit manipulation and pointer arithmetic need careful translation
- External libraries: C/C++ library calls may not have direct Lean4 equivalents
- Macros: C preprocessor macros need manual translation
- Templates: C++ templates translate to Lean4 generics differently
Resources
- Translation patterns: See translation_patterns.md for comprehensive pattern catalog
- Lean4 documentation: https://lean-lang.org/documentation/
- Lean4 standard library: https://github.com/leanprover/lean4/tree/master/src/Init
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/c-cpp-to-lean4-translator/SKILL.md
Popularity
- Repository stars
- 63
- Repository forks
- 5
- 7-day trend score
- 21
Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 20 Mar 2026, 7 months ago.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/arabelatso/skills-4-se/c-cpp-to-lean4-translator)