Skip to main content
ClaudeWave
Skill85 estrellas del repoactualizado 3mo ago

imperative-to-coq-model-extractor

Extract abstract mathematical models from imperative code (C, C++, Python, Java, etc.) suitable for formal reasoning in Coq. Use when the user asks to model imperative code in Coq, create Coq specifications from imperative programs, extract mathematical models for verification, or translate imperative algorithms to Coq for formal reasoning and proof.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/imperative-to-coq-model-extractor && cp -r /tmp/imperative-to-coq-model-extractor/skills/imperative-to-coq-model-extractor ~/.claude/skills/imperative-to-coq-model-extractor
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Imperative to Coq Model Extractor

## Overview

Extract abstract mathematical models from imperative code that can be used for formal reasoning and verification in Coq. This skill transforms imperative programs into functional Coq definitions with explicit state modeling, enabling formal proofs about program behavior.

## Extraction Workflow

### Step 1: Analyze Imperative Code

Understand the program structure and semantics:

1. **Identify components:**
   - Functions and their signatures
   - Data structures and types
   - State and mutable variables
   - Control flow (loops, conditionals)
   - Side effects and I/O

2. **Understand semantics:**
   - What does the program compute?
   - What state does it maintain?
   - What are the invariants?
   - What are preconditions and postconditions?

3. **Note modeling challenges:**
   - Mutable state
   - Imperative loops
   - Pointers and memory
   - Side effects

### Step 2: Design Coq Model Structure

Plan the Coq representation:

1. **Choose appropriate types:**
   - `Z` for arbitrary precision integers
   - `nat` for natural numbers
   - `bool` for booleans
   - `list` for sequences
   - `Record` for structured state
   - Inductive types for enumerations

2. **Model state explicitly:**
   - Pure functions: Direct translation
   - Mutable state: State transformation functions
   - Side effects: Explicit state passing

3. **Plan control flow translation:**
   - Conditionals → Pattern matching or if-then-else
   - Loops → Recursive functions (Fixpoint)
   - Early returns → Conditional expressions

### Step 3: Extract Core Model

Translate imperative constructs to Coq:

**Pattern: Pure function**
```c
// Imperative
int add(int a, int b) {
    return a + b;
}
```

```coq
(* Coq Model *)
Definition add (a b : Z) : Z := a + b.
```

**Pattern: Function with state**
```c
// Imperative
int counter = 0;
void increment() {
    counter++;
}
```

```coq
(* Coq Model *)
Definition counter_state : Type := Z.
Definition increment (c : counter_state) : counter_state := c + 1.
```

**Pattern: Loop → Recursion**
```c
// Imperative
int sum(int n) {
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += i;
    }
    return total;
}
```

```coq
(* Coq Model *)
Fixpoint sum_aux (n i total : nat) : nat :=
  match n with
  | 0 => total
  | S n' =>
      if i <? n then
        sum_aux n (S i) (total + i)
      else
        total
  end.

Definition sum (n : nat) : nat := sum_aux n 0 0.
```

### Step 4: Add Specifications

Enhance the model with formal specifications:

1. **Function specifications:**
   ```coq
   Definition abs (n : Z) : Z :=
     if n <? 0 then -n else n.

   Lemma abs_nonneg : forall n : Z, abs n >= 0.
   Proof.
     intros n. unfold abs.
     destruct (n <? 0) eqn:E.
     - apply Z.ltb_lt in E. lia.
     - apply Z.ltb_ge in E. lia.
   Qed.
   ```

2. **Loop invariants:**
   ```coq
   (* Invariant: sum = sum of first i elements *)
   Lemma sum_invariant : forall n i total,
     i <= n ->
     sum_aux n i total = total + (sum of 0..i-1).
   Proof.
     (* Proof by induction *)
   Admitted.
   ```

3. **Correctness properties:**
   ```coq
   Lemma sum_correct : forall n,
     sum n = n * (n - 1) / 2.
   Proof.
     (* Proof *)
   Admitted.
   ```

### Step 5: Verify and Test

Ensure the model is correct:

1. **Type check:**
   ```bash
   coqc model.v
   ```

2. **Test with examples:**
   ```coq
   Compute add 2 3.        (* Should output 5 *)
   Compute sum 5.          (* Should output 10 *)
   ```

3. **Compare semantics:**
   - Run original imperative program
   - Evaluate Coq model
   - Verify outputs match

### Step 6: Refine and Document

Improve the extracted model:

1. **Simplify definitions:**
   - Use standard library functions
   - Remove redundant constructs
   - Factor out common patterns

2. **Add documentation:**
   ```coq
   (* Computes the absolute value of an integer *)
   Definition abs (n : Z) : Z := ...
   ```

3. **Organize proofs:**
   - Group related lemmas
   - Add proof sketches
   - Document proof strategies

## Common Extraction Patterns

For detailed patterns, see [extraction_patterns.md](references/extraction_patterns.md).

### Quick Reference

| Imperative | Coq Model |
|------------|-----------|
| `int x = 10` | `Definition x : Z := 10` |
| `x = x + 1` | `x + 1` (functional update) |
| `if (x > 0)` | `if x >? 0 then ... else ...` |
| `for (i=0; i<n; i++)` | `Fixpoint loop (i : nat) ...` |
| `while (cond)` | `Fixpoint loop ... if cond then ...` |
| `struct S { int x; }` | `Record S := { x : Z }` |
| `int arr[5]` | `list Z` or `Definition arr := [...]` |
| `return x` | `x` (last expression) |

## Examples

### Example 1: Simple Algorithm

**Imperative Input (C):**
```c
int factorial(int n) {
    int result = 1;
    while (n > 1) {
        result *= n;
        n--;
    }
    return result;
}
```

**Coq Model:**
```coq
Fixpoint factorial (n : nat) : nat :=
  match n with
  | 0 => 1
  | S n' => n * factorial n'
  end.

Lemma factorial_positive : forall n,
  factorial n >= 1.
Proof.
  induction n.
  - simpl. lia.
  - simpl. lia.
Qed.
```

### Example 2: Array Processing

**Imperative Input (Python):**
```python
def find_max(arr):
    max_val = arr[0]
    for i in range(1, len(arr)):
        if arr[i] > max_val:
            max_val = arr[i]
    return max_val
```

**Coq Model:**
```coq
Require Import List.
Import ListNotations.

Fixpoint find_max (l : list Z) (default : Z) : Z :=
  match l with
  | [] => default
  | [x] => x
  | x :: xs => Z.max x (find_max xs default)
  end.

Lemma find_max_in_list : forall l default,
  l <> [] ->
  In (find_max l default) l.
Proof.
  (* Proof by induction *)
Admitted.

Lemma find_max_is_max : forall l default x,
  In x l ->
  x <= find_max l default.
Proof.
  (* Proof by induction *)
Admitted.
```

### Example 3: Stateful Program

**Imperative Input (Java):**
```java
class Counter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public
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.