Agent skill

Cpp To Dafny Translator

by ArabelaTso in ArabelaTso/Skills-4-SE

Translate C/C++ programs to equivalent Dafny code while preserving semantics and ensuring verification.

Apache-2.0Auto-check passedWriting & Content

Install Cpp To Dafny Translator

skills CLI
$ npx skills add ArabelaTso/Skills-4-SE --skill cpp-to-dafny-translator -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install ArabelaTso/Skills-4-SE cpp-to-dafny-translator --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/cpp-to-dafny-translator .claude/skills/cpp-to-dafny-translator && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
cpp-to-dafny-translator
GitHub stars
253
Token cost
~2.9k tokens
SKILL.md length
675 words
Files
4 (incl. references)
Skills in repo
150
Repo updated
First seen
Licence
Apache-2.0

At a glance

Translate C/C++ programs to equivalent Dafny code while preserving semantics and ensuring verification.

  • Works in 12 steps: Memory Safety First → Preserve Semantics → Enable Verification → …
  • Users ask to convert
  • SKILL.md covers Overview, Translation Workflow, Core Translation Principles and Type Mapping Reference, plus 6 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Cpp To Dafny Translator is an agent skill from ArabelaTso/Skills-4-SE. Translate C/C++ programs to equivalent Dafny code while preserving semantics and ensuring verification. Use when users ask to convert, translate, or port C/C++ code to Dafny, or when they need to formally verify C/C++ algorithms using Dafny's verification capabilities. Handles functions, structs, pointers, arrays, memory management, and ensures the generated Dafny code is well-typed, executable, verifiable, and can successfully run.

Its SKILL.md is about 2.9k tokens, which your agent loads only when the skill is triggered. The skill folder holds 4 other files, including reference files (for example `references/memory_patterns.md`, `references/type_mappings.md` and `references/verification_guide.md`).

It sits in Writing & Content, covering Translation. It works with C++. The repository describes itself as: A curated list of 180+ useful Claude Skills for Software Engineering and resources for customizing AI for SE workflows. The licence is Apache-2.0.

When your agent uses it

  • Users ask to convert
  • Port C/C++ code to Dafny
  • They need to formally verify C/C++ algorithms using Dafnys verification capabilities

Example prompts

  • “/cpp-to-dafny-translator”

Workflow steps

12 steps, taken from the step headings in SKILL.md.

  1. Memory Safety First
  2. Preserve Semantics
  3. Enable Verification
  4. Pointer Arithmetic
  5. Dynamic Memory Allocation
  6. Null Pointers
  7. Mutable vs Immutable
  8. Verification Annotations
  9. Analyze C/C++ Code
  10. Plan Type and Memory Mappings
  11. Translate Constructs
  12. Add Verification Annotations

What it can do on your machine

Read from SKILL.md and the folder at commit 4f38503. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are dafny and c).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Cpp To Dafny Translator loads about 2.9k tokens when it runs, and up to ~9.4k if it reads all its reference files. Until then it costs about 115 tokens; SKILL.md has 675 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~115
When it runs · the whole SKILL.md, loaded when a task matches
~2.9k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~9.4k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from ArabelaTso/Skills-4-SE at commit 4f38503, republished under its Apache-2.0 licence (© ArabelaTso). 675 words, ~2,857 tokens.

Download SKILL.mdSave it as .claude/skills/cpp-to-dafny-translator/SKILL.md (or your agent's skills folder). This skill also uses 3 other files; get the full folder from GitHub.
name
cpp-to-dafny-translator
description
Translate C/C++ programs to equivalent Dafny code while preserving semantics and ensuring verification. Use when users ask to convert, translate, or port C/C++ code to Dafny, or when they need to formally verify C/C++ algorithms using Dafny's verification capabilities. Handles functions, structs, pointers, arrays, memory management, and ensures the generated Dafny code is well-typed, executable, verifiable, and can successfully run.

C/C++ to Dafny Translator

Translate C/C++ programs into equivalent, verifiable Dafny code while preserving program semantics and ensuring memory safety.

Overview

This skill provides systematic guidance for translating C/C++ code to Dafny, handling memory management, pointer semantics, type conversions, and ensuring well-typed, verifiable output with appropriate specifications.

Translation Workflow

C/C++ Input → Analyze Structure → Map Types & Memory → Translate → Add Specifications → Verify
    ├─ Identify types, pointers, memory patterns
    ├─ Map C/C++ constructs to Dafny equivalents
    ├─ Handle memory safety and ownership
    ├─ Add preconditions, postconditions, invariants
    └─ Validate executability and verification

Core Translation Principles

1. Memory Safety First

Dafny enforces memory safety. Every translation must:

  • Replace raw pointers with safe references or arrays
  • Make memory bounds explicit
  • Ensure no null pointer dereferences
  • Handle dynamic memory with sequences or arrays
2. Preserve Semantics

The translated code must maintain the same computational behavior, preserve function contracts, keep algorithmic complexity, and handle all edge cases including error conditions.

3. Enable Verification

Generated Dafny code must include specifications (preconditions, postconditions, invariants), be verifiable by Dafny's verifier, compile and execute correctly, and follow Dafny idioms.

Type Mapping Reference

Basic Types
C/C++ TypeDafny TypeNotes
int, longintUnbounded integers in Dafny
unsigned intnatNatural numbers (≥ 0)
charcharSingle character
boolboolDirect mapping
float, doublerealExact rationals in Dafny
void()Unit type
NULLUse Option or bounds checksNo null pointers
Composite Types
C/C++ TypeDafny TypeNotes
int arr[]array<int>Fixed-size arrays
int* ptrarray<int> or seq<int>Depends on usage
structclass or datatypeMutable vs immutable
enumdatatypeAlgebraic data types
uniondatatype with variantsTagged unions

For detailed mappings, see references/type_mappings.md.

Translation Patterns

Functions

Simple C function:

c
int add(int a, int b) {
    return a + b;
}

Dafny:

dafny
function add(a: int, b: int): int
{
    a + b
}

Function with side effects:

c
void increment(int* x) {
    (*x)++;
}

Dafny (using method):

dafny
method increment(x: array<int>, index: nat)
    requires index < x.Length
    modifies x
    ensures x[index] == old(x[index]) + 1
{
    x[index] := x[index] + 1;
}
Pointers and Arrays

C array access:

c
int sum_array(int* arr, int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum;
}

Dafny:

dafny
method sumArray(arr: array<int>) returns (sum: int)
    ensures sum == arraySum(arr[..])
{
    sum := 0;
    var i := 0;
    while i < arr.Length
        invariant 0 <= i <= arr.Length
        invariant sum == arraySum(arr[..i])
    {
        sum := sum + arr[i];
        i := i + 1;
    }
}

function arraySum(s: seq<int>): int
{
    if |s| == 0 then 0 else s[0] + arraySum(s[1..])
}
Structs and Classes

C struct:

c
struct Point {
    int x;
    int y;
};

int distance_squared(struct Point* p) {
    return p->x * p->x + p->y * p->y;
}

Dafny:

dafny
class Point {
    var x: int
    var y: int

    constructor(x0: int, y0: int)
        ensures x == x0 && y == y0
    {
        x := x0;
        y := y0;
    }
}

function distanceSquared(p: Point): int
    reads p
{
    p.x * p.x + p.y * p.y
}
Control Flow

If-else:

c
int max(int a, int b) {
    if (a > b) return a;
    else return b;
}

Dafny:

dafny
function max(a: int, b: int): int
{
    if a > b then a else b
}

Loops with invariants:

c
int factorial(int n) {
    int result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

Dafny:

dafny
method factorial(n: nat) returns (result: nat)
    ensures result == fact(n)
{
    result := 1;
    var i := 1;
    while i <= n
        invariant 1 <= i <= n + 1
        invariant result == fact(i - 1)
    {
        result := result * i;
        i := i + 1;
    }
}

function fact(n: nat): nat
{
    if n == 0 then 1 else n * fact(n - 1)
}

Handling Common Challenges

1. Pointer Arithmetic

Challenge: C allows pointer arithmetic; Dafny doesn't.

Solution: Use array indices instead:

c
// C
int* ptr = arr + 5;
*ptr = 10;
dafny
// Dafny
arr[5] := 10;
2. Dynamic Memory Allocation

Challenge: C uses malloc/free; Dafny has automatic memory management.

Solution: Use arrays or sequences:

c
// C
int* arr = (int*)malloc(n * sizeof(int));
// ... use arr ...
free(arr);
dafny
// Dafny
var arr := new int[n];
// ... use arr ...
// No explicit free needed
3. Null Pointers

Challenge: C allows NULL; Dafny doesn't have null references.

Solution: Use Option types or ensure non-null:

c
// C
int* find(int* arr, int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) return &arr[i];
    }
    return NULL;
}
dafny
// Dafny
method find(arr: array<int>, target: int) returns (index: int)
    ensures index == -1 || (0 <= index < arr.Length && arr[index] == target)
{
    var i := 0;
    while i < arr.Length
        invariant 0 <= i <= arr.Length
    {
        if arr[i] == target {
            return i;
        }
        i := i + 1;
    }
    return -1;
}
4. Mutable vs Immutable

Challenge: C has mutable everything; Dafny distinguishes functions (pure) from methods (with side effects).

Solution:

  • Use function for pure computations
  • Use method for operations with side effects
  • Add reads clauses for functions that read object fields
  • Add modifies clauses for methods that modify state
5. Verification Annotations

Challenge: Dafny requires specifications for verification.

Solution: Add preconditions, postconditions, and loop invariants:

dafny
method binarySearch(arr: array<int>, target: int) returns (index: int)
    requires forall i, j :: 0 <= i < j < arr.Length ==> arr[i] <= arr[j]  // sorted
    ensures index == -1 || (0 <= index < arr.Length && arr[index] == target)
{
    var low := 0;
    var high := arr.Length;
    while low < high
        invariant 0 <= low <= high <= arr.Length
        invariant forall i :: 0 <= i < low ==> arr[i] < target
        invariant forall i :: high <= i < arr.Length ==> arr[i] > target
    {
        var mid := (low + high) / 2;
        if arr[mid] < target {
            low := mid + 1;
        } else if arr[mid] > target {
            high := mid;
        } else {
            return mid;
        }
    }
    return -1;
}

Translation Process

Step 1: Analyze C/C++ Code

Identify all functions, structs, and global variables. Analyze pointer usage and memory patterns. Identify side effects and state modifications. Note any unsafe operations.

Show full SKILL.md (260 more words)Show less
Step 2: Plan Type and Memory Mappings

Map C/C++ types to Dafny types. Decide how to handle pointers (arrays, sequences, or references). Plan struct translations (class vs datatype). Identify what needs specifications.

Step 3: Translate Constructs

Start with data structures (structs → classes/datatypes). Translate pure functions first. Convert functions with side effects to methods. Add memory safety checks. Include necessary specifications.

Step 4: Add Verification Annotations

Add preconditions (requires). Add postconditions (ensures). Add loop invariants. Add frame conditions (reads, modifies). Add termination measures (decreases).

Step 5: Verify and Test

Run Dafny verifier. Fix verification errors. Test with concrete examples. Ensure executability.

Example Translation

C code:

c
int is_sorted(int* arr, int n) {
    for (int i = 0; i < n - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            return 0;
        }
    }
    return 1;
}

void bubble_sort(int* arr, int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

Dafny:

dafny
predicate isSorted(arr: array<int>)
    reads arr
{
    forall i, j :: 0 <= i < j < arr.Length ==> arr[i] <= arr[j]
}

method bubbleSort(arr: array<int>)
    modifies arr
    ensures isSorted(arr)
    ensures multiset(arr[..]) == multiset(old(arr[..]))
{
    var i := 0;
    while i < arr.Length - 1
        invariant 0 <= i <= arr.Length
        invariant forall k, l :: 0 <= k < i <= l < arr.Length ==> arr[k] <= arr[l]
        invariant multiset(arr[..]) == multiset(old(arr[..]))
    {
        var j := 0;
        while j < arr.Length - i - 1
            invariant 0 <= j <= arr.Length - i - 1
            invariant forall k :: 0 <= k < j ==> arr[k] <= arr[j]
            invariant multiset(arr[..]) == multiset(old(arr[..]))
        {
            if arr[j] > arr[j + 1] {
                arr[j], arr[j + 1] := arr[j + 1], arr[j];
            }
            j := j + 1;
        }
        i := i + 1;
    }
}

Best Practices

  1. Start with Pure Functions: Translate side-effect-free code first
  2. Add Specifications Incrementally: Start with simple contracts, refine as needed
  3. Use Helper Functions: Define pure functions to express properties
  4. Leverage Dafny's Verifier: Let the verifier guide you to correct specifications
  5. Test Executability: Use Main methods to test concrete examples
  6. Document Assumptions: Note where C semantics differ from Dafny
  7. Handle Memory Explicitly: Make all memory bounds and ownership clear

Verification Checklist

Before finalizing translation:

  • All types are correctly mapped
  • Code compiles without errors
  • Dafny verifier succeeds
  • Preconditions capture all assumptions
  • Postconditions specify all guarantees
  • Loop invariants are sufficient for verification
  • Memory safety is ensured (no out-of-bounds access)
  • Termination is proven (decreases clauses if needed)
  • Code is executable and produces correct results

Additional Resources

For complex translations, refer to:

© ArabelaTso, Apache-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 3 other files (references) in skills/cpp-to-dafny-translator of ArabelaTso/Skills-4-SE.

  • SKILL.md
  • references/memory_patterns.md
  • references/type_mappings.md
  • references/verification_guide.md

Open the folder on GitHubat commit 4f38503

Compare with similar skills

Cpp To Dafny Translator next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Cpp To Dafny Translator compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Cpp To Dafny Translator this skillArabelaTso/Skills-4-SE253—~2.9kAutomated safety check: PassApache-2.0
Translationdoxygen/doxygen6.6k—~5.2kAutomated safety check: PassGPL-2.0
Smooth Translationopenforecast-org/smooth107—~2.2kAutomated safety check: PassLGPL-2.1
Msvc Clmohitmishra786/low-level-dev-skills253—~1.3kAutomated safety check: PassMIT
D2mcpp Authoringmcpp-community/d2mcpp1.8k—~2.7kAutomated safety check: PassCustom licence
Mcpp Docs Stylemcpp-community/mcpp156—~3.7kAutomated safety check: PassApache-2.0

Similar skills

  • Translation

    doxygen/doxygen

    Keeps all Doxygen and Doxywizard translations up to date across three mechanisms: translator C++ classes (src/translatorxx.h), Qt .ts locale files for the Doxywizard GUI (addon/doxywizard/i18n/)…

    6.6k GitHub stars~5.2k tokensUpdated 8 days ago
    Writing & ContentAuto-check passed
  • Smooth Translation

    openforecast-org/smooth

    Port a feature from the R smooth package to the Python port, or check how an R name maps to Python.

    107 GitHub stars~2.2k tokensUpdated yesterday
    Writing & ContentAuto-check passed
  • Msvc Cl

    mohitmishra786/low-level-dev-skills

    MSVC cl.exe and clang-cl skill for Windows C/C++ projects. An agent skill from mohitmishra786/low-level-dev-skills.

    253 GitHub stars~1.3k tokensUpdated 3 mo ago
    Writing & ContentAuto-check passed
  • D2mcpp Authoring

    mcpp-community/d2mcpp

    Authoring conventions, design principles, and file formats for the d2mcpp (D2X) Modern C++ tutorial project.

    1.8k GitHub stars~2.7k tokensUpdated 2 mo ago
    DevelopmentAuto-check passed
  • Mcpp Docs Style

    mcpp-community/mcpp

    A skill your agent uses when writing or editing anything under docs/ (English or 简体中文), docs/specs/, README files, or the design records under .agents/docs/ — states which tree a document belongs…

    156 GitHub stars~3.7k tokensUpdated today
    DevelopmentAuto-check passed
  • Translation Diff Export

    Devolutions/UniGetUI

    Compares UniGetUI JSON locale files against English, identifies untranslated or source-changed keys, and generates patch, reference, and handoff files for a target language.

    26k GitHub stars~1.1k tokensUpdated yesterday
    Writing & ContentAuto-check passed

More from ArabelaTso/Skills-4-SE

All 150 skills in this repo
  • Framework Migration Assistant

    ArabelaTso/Skills-4-SE

    Automatically migrate Python web applications between frameworks (Flask → FastAPI, Django → FastAPI).

    253 GitHub stars~1.9k tokensUpdated 1 mo ago
    Auto-check passed
  • Metamorphic Test Generator

    ArabelaTso/Skills-4-SE

    Generate test cases using metamorphic testing by applying transformations based on metamorphic properties.

    253 GitHub stars~798 tokensUpdated 1 mo ago
    Auto-check passed
  • Reproduction Trace Instrumenter

    ArabelaTso/Skills-4-SE

    Instruments programs to capture execution traces specifically for reproducing reported bugs, enabling consistent replay and diagnosis of failures.

    253 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Spring Mvc To Boot Migrator

    ArabelaTso/Skills-4-SE

    Automatically migrate Spring MVC applications to Spring Boot.

    253 GitHub stars~2.2k tokensUpdated 1 mo ago
    Auto-check passed
  • State Snapshot Instrumenter

    ArabelaTso/Skills-4-SE

    Instrument programs (Python, C/C++, Java) to capture snapshots of key program states at runtime, including variables, memory, and call stacks.

    253 GitHub stars~2.2k tokensUpdated 1 mo ago
    Auto-check passed

Works with

Questions about Cpp To Dafny Translator

What does Cpp To Dafny Translator do?

Translate C/C++ programs to equivalent Dafny code while preserving semantics and ensuring verification. Cpp To Dafny Translator is an agent skill from ArabelaTso/Skills-4-SE. Translate C/C++ programs to equivalent Dafny code while preserving semantics and ensuring verification.

When should I use Cpp To Dafny Translator?

Cpp To Dafny Translator fits situations like: users ask to convert; port C/C++ code to Dafny; they need to formally verify C/C++ algorithms using Dafnys verification capabilities.

How do I install Cpp To Dafny Translator in Claude Code?

Run `npx skills add ArabelaTso/Skills-4-SE --skill cpp-to-dafny-translator -a claude-code`. Or copy the skill folder (skills/cpp-to-dafny-translator in ArabelaTso/Skills-4-SE) into .claude/skills/cpp-to-dafny-translator in your project. Claude Code loads it when a task matches its description.

How do I install Cpp To Dafny Translator in Codex?

Run `npx skills add ArabelaTso/Skills-4-SE --skill cpp-to-dafny-translator -a codex`. Or copy the skill folder (skills/cpp-to-dafny-translator in ArabelaTso/Skills-4-SE) into .agents/skills/cpp-to-dafny-translator in your project. Codex loads it when a task matches its description.

Can I use Cpp To Dafny Translator in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add ArabelaTso/Skills-4-SE --skill cpp-to-dafny-translator -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/cpp-to-dafny-translator, .gemini/skills/cpp-to-dafny-translator, .github/skills/cpp-to-dafny-translator and .opencode/skills/cpp-to-dafny-translator in your project.

What does Cpp To Dafny Translator need to run?

SKILL.md names no scripts, command-line tools or credentials: Cpp To Dafny Translator is instructions for the agent only.

Does Cpp To Dafny Translator access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Cpp To Dafny Translator safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Cpp To Dafny Translator use?

Cpp To Dafny Translator is published under the Apache-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Cpp To Dafny Translator use?

About 2.9k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 6.6k tokens, read only when the agent opens those files.

What are the alternatives to Cpp To Dafny Translator?

Skills that share tags, products or a category with Cpp To Dafny Translator: Translation (doxygen/doxygen, 6.6k stars), Smooth Translation (openforecast-org/smooth, 107 stars), Msvc Cl (mohitmishra786/low-level-dev-skills, 253 stars) and D2mcpp Authoring (mcpp-community/d2mcpp, 1.8k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Cpp To Dafny Translator?

ArabelaTso (a GitHub user) maintains it in ArabelaTso/Skills-4-SE, which has 253 GitHub stars. The repository holds 150 skills in this directory. The repository was last updated on August 21, 2026.

Source: ArabelaTso/Skills-4-SE on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.