Receber por email
← Voltar para o catálogo

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.

105estrelas
Atualizado há 8 meses

Ver no GitHub ↗ Licença: Apache-2.0

Como adicionar

/plugin marketplace add ArabelaTso/Skills-4-SE

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/imperative-to-coq-model-extractor/svg)](https://www.skillteca.com.br/skills/imperative-to-coq-model-extractor)

Alerta por categoria

Receba novas skills de Design e Frontend toda segunda

1 email curto, só com as skills novas de Design e Frontend. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

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:
  2. Functions and their signatures
  3. Data structures and types
  4. State and mutable variables
  5. Control flow (loops, conditionals)
  6. Side effects and I/O
  1. Understand semantics:
  2. What does the program compute?
  3. What state does it maintain?
  4. What are the invariants?
  5. What are preconditions and postconditions?
  1. Note modeling challenges:
  2. Mutable state
  3. Imperative loops
  4. Pointers and memory
  5. Side effects

Step 2: Design Coq Model Structure

Plan the Coq representation:

  1. Choose appropriate types:
  2. Z for arbitrary precision integers
  3. nat for natural numbers
  4. bool for booleans
  5. list for sequences
  6. Record for structured state
  7. Inductive types for enumerations
  1. Model state explicitly:
  2. Pure functions: Direct translation
  3. Mutable state: State transformation functions
  4. Side effects: Explicit state passing
  1. Plan control flow translation:
  2. Conditionals → Pattern matching or if-then-else
  3. Loops → Recursive functions (Fixpoint)
  4. Early returns → Conditional expressions

Step 3: Extract Core Model

Translate imperative constructs to Coq:

Pattern: Pure function

// Imperative
int add(int a, int b) {
    return a + b;
}
(* Coq Model *)
Definition add (a b : Z) : Z := a + b.

Pattern: Function with state

// Imperative
int counter = 0;
void increment() {
    counter++;
}
(* Coq Model *)
Definition counter_state : Type := Z.
Definition increment (c : counter_state) : counter_state := c + 1.

Pattern: Loop → Recursion

// Imperative
int sum(int n) {
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += i;
    }
    return total;
}
(* 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. ```

  1. 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. ``

  1. 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 ``

  1. Test with examples:

``coq Compute add 2 3. ( Should output 5 ) Compute sum 5. ( Should output 10 ) ``

  1. Compare semantics:
  2. Run original imperative program
  3. Evaluate Coq model
  4. Verify outputs match

Step 6: Refine and Document

Improve the extracted model:

  1. Simplify definitions:
  2. Use standard library functions
  3. Remove redundant constructs
  4. Factor out common patterns
  1. Add documentation:

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

  1. Organize proofs:
  2. Group related lemmas
  3. Add proof sketches
  4. 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):

int factorial(int n) {
    int result = 1;
    while (n > 1) {
        result *= n;
        n--;
    }
    return result;
}

Coq Model:

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):

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:

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):

class Counter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Coq Model:

Record CounterState : Type := mkCounter {
  count : nat
}.

Definition init_counter : CounterState := {|
  count := 0
|}.

Definition increment (s : CounterState) : CounterState := {|
  count := S s.(count)
|}.

Definition getCount (s : CounterState) : nat :=
  s.(count).

(* Specification *)
Lemma increment_increases : forall s,
  getCount (increment s) = S (getCount s).
Proof.
  intros s. unfold increment, getCount. simpl. reflexivity.
Qed.

Example 4: Binary Search

Imperative Input (C++):

int binary_search(int arr[], int n, int target) {
    int left = 0, right = n - 1;
    while (left <= right) {
        int mid = (left + right) / 2;
        if (arr[mid] == target)
            return mid;
        else if (arr[mid] < target)
            left = mid + 1;
        else
            right = mid - 1;
    }
    return -1;
}

Coq Model:

Require Import List.
Import ListNotations.

Fixpoint binary_search_aux (l : list Z) (target : Z)
                            (left right : nat) : option nat :=
  match right - left with
  | 0 =>
      match nth_error l left with
      | Some v => if v =? target then Some left else None
      | None => None
      end
  | S _ =>
      if left <=? right then
        let mid := (left + right) / 2 in
        match nth_error l mid with
        | Some v =>
            if v =? target then Some mid
            else if v <? target then
              binary_search_aux l target (S mid) right
            else
              binary_search_aux l target left (mid - 1)
        | None => None
        end
      else None
  end.

Definition binary_search (l : list Z) (target : Z) : option nat :=
  binary_search_aux l target 0 (length l - 1).

(* Specification: if result is Some i, then l[i] = target *)
Lemma binary_search_correct : forall l target i,
  binary_search l target = Some i ->
  nth_error l i = Some target.
Proof.
  (* Proof *)
Admitted.

#

Compartilhar X LinkedIn