编程开发

生成附形式化证明的可执行代码

从需求和形式化规约生成实现及证明,用于验证功能正确性、内存安全或数据结构不变量。

# 携带证明的代码生成器

生成附带形式化证明的可执行代码,以证明关键的安全性和正确性属性。

## 概述

携带证明的代码(PCC)是附带形式化证明以证明特定属性的可执行代码。此技能帮助生成:

1. **经过验证的实现**,附带正确性证明
2. **安全证书**,证明内存安全、边界检查和空值安全
3. **功能规约**,包含前置条件和后置条件
4. **不变量证明**,保证数据结构完整性
5. 从经过验证的规约中**提取的代码**

生成的代码可以提取为主流语言(OCaml、Haskell、SML),同时保留证明证书。

## PCC 生成工作流程

```
Requirements
    ↓
Formal Specification
    ↓
Verified Implementation
    ↓
Proof Obligations
    ↓
Certified Code + Proofs
    ↓
Code Extraction
```

## 核心方法

### 方法 1:规约优先

从形式化规约开始,进行实现,然后证明。

**步骤:**
1. 编写形式化规约
2. 实现函数/算法
3. 陈述正确性定理
4. 证明定理
5. 提取代码

**示例(Isabelle):**
```isabelle
(* Specification *)
definition sorted_spec :: "nat list ⇒ nat list ⇒ bool" where
  "sorted_spec input output ≡ sorted output ∧ mset output = mset input"

(* Implementation *)
fun insertion_sort :: "nat list ⇒ nat list" where
  "insertion_sort [] = []" |
  "insertion_sort (x # xs) = insert x (insertion_sort xs)"

(* Correctness theorem *)
theorem insertion_sort_correct:
  "sorted_spec input (insertion_sort input)"
proof (induction input)
  case Nil
  then show ?case by (simp add: sorted_spec_def)
next
  case (Cons x xs)
  then show ?case
    using insert_sorted mset_insert
    by (auto simp: sorted_spec_def)
qed

(* Extract code *)
export_code insertion_sort in SML file "sort.sml"
```

### 方法 2:基于精化

从抽象层开始逐步精化为具体实现,并在每一步进行证明。

**步骤:**
1. 抽象规约
2. 精化至中间层
3. 证明精化正确
4. 精化为可执行代码
5. 证明最终精化
6. 提取代码

**示例(Coq):**
```coq
(* Abstract specification *)
Definition find_spec {A} (P : A → bool) (l : list A) : option A :=
  (* Nondeterministic: any element satisfying P *)
  ...

(* Concrete implementation *)
Fixpoint find {A} (P : A → bool) (l : list A) : option A :=
  match l with
  | [] => None
  | x :: xs => if P x then Some x else find P xs
  end.

(* Refinement proof *)
Theorem find_refines : forall A P l,
  find P l = find_spec P l.
Proof.
  (* Proof that concrete refines abstract *)
Qed.

(* Extract *)
Extraction "find.ml" find.
```

### 方法 3:程序优先

编写带注解的代码,生成证明义务,然后证明这些义务。

**步骤:**
1. 编写带契约的函数
2. 生成验证条件
3. 证明验证条件
4. 认证代码

**示例(Coq 与 Program):**
```coq
Require Import Program.

Program Definition safe_div (a b : nat) (H : b ≠ 0) : nat :=
  a / b.

(* Proof obligation automatically generated *)
Next Obligation.
  (* Prove division is safe *)
Qed.
```

## 安全性属性

### 内存安全

**属性:** 不发生缓冲区溢出或越界访问。

**模式:**
```isabelle
lemma array_access_safe:
  "⟦ i < length arr ⟧ ⟹ ∃v. arr ! i = v"
  by auto

fun safe_get :: "'a list ⇒ nat ⇒ 'a option" where
  "safe_get [] _ = None" |
  "safe_get (x # xs) 0 = Some x" |
  "safe_get (x # xs) (Suc n) = safe_get xs n"

lemma safe_get_bounds:
  "safe_get xs i = Some v ⟹ i < length xs"
  by (induction xs i rule: safe_get.induct) auto
```

### 空值安全

**属性:** 不发生空指针解引用。

**模式:**
```coq
Definition safe_head {A} (l : list A) (H : l ≠ []) : A :=
  match l with
  | [] => match H eq_refl with end
  | x :: _ => x
  end.

Lemma safe_head_correct : forall A (l : list A) H,
  l ≠ [] → safe_head l H = hd_error l.
Proof.
  intros. destruct l; auto. contradiction.
Qed.
```

### 边界检查

**属性:** 所有数组访问均在边界内。

**模式:**
```isabelle
definition bounded_access :: "'a array ⇒ nat ⇒ 'a option" where
  "bounded_access arr i = (if i < array_length arr
                           then Some (array_get arr i)
                           else None)"

lemma bounded_access_safe:
  "bounded_access arr i = Some v ⟹ i < array_length arr"
  by (simp add: bounded_access_def split: if_splits)
```

## 正确性属性

### 功能正确性

**属性:** 函数计算出正确结果。

**模式:**
```isabelle
fun factorial :: "nat ⇒ nat" where
  "factorial 0 = 1" |
  "factorial (Suc n) = Suc n * factorial n"

function fact_spec :: "nat ⇒ nat" where
  "fact_spec 0 = 1" |
  "fact_spec n = n * fact_spec (n - 1)"
  by auto

theorem factorial_correct:
  "factorial n = fact_spec n"
  by (induction n) auto
```

### 不变量保持

**属性:** 数据结构的不变量得到保持。

**模式:**
```coq
Inductive BST : tree → Prop :=
  | BST_leaf : BST Leaf
  | BST_node : forall l x r,
      BST l → BST r →
      (forall y, In y l → y < x) →
      (forall y, In y r → x < y) →
      BST (Node l x r).

Fixpoint insert (x : nat) (t : tree) : tree :=
  match t with
  | Leaf => Node Leaf x Leaf
  | Node l y r =>
      if x <? y then Node (insert x l) y r
      else if y <? x then Node l y (insert x r)
      else t
  end.

Theorem insert_preserves_BST : forall x t,
  BST t → BST (insert x t).
Proof.
  induction t; intros; simpl.
  - constructor; constructor.
  - inversion H; subst.
    destruct (x <? n) eqn:E1.
    + (* Insert left *)
    + destruct (n <? x) eqn:E2.
      * (* Insert right *)
      * (* Equal, no change *)
Qed.
```

### 终止性

**属性:** 函数总会终止。

**模式:**
```isabelle
function gcd :: "nat ⇒ nat ⇒ nat" where
  "gcd a 0 = a" |
  "gcd a b = gcd b (a mod b)"
  by auto
termination
  by (relation "measure (λ(a, b). b)") auto

lemma gcd_terminates:
  "∃result. gcd a b = result"
  by auto
```

## 特定框架指南

### Isabelle/HOL PCC

关于 Isabelle 专用的代码生成、提取和认证模式,请参阅 [references/isabelle_pcc.md](references/isabelle_pcc.md)。

主要特性:
- 生成 SML、OCaml、Haskell、Scala 代码
- 用于经过验证的实现的精化框架
- 使用 Sepref 编写附带证明的命令式代码
- 导出时附带证明证书

### Coq PCC

关于 Coq 专用的代码提取、Program 框架和认证,请参阅 [references/coq_pcc.md](references/coq_pcc.md)。

主要特性:
- 提取为 OCaml、Haskell、Scheme
- 使用 Program 处理证明义务
- 使用 Equations 处理良基递归
- 经过认证的编译

## 常见安全性属性

有关详细的安全性和正确性属性模式,请参阅 [references/safety_properties.md](references/safety_properties.md)。

类别包括:
- 内存安全(边界、空值、释放后使用)
- 类型安全(不发生类型混淆)
- 算术安全(不发生溢出、除以零)
- 并发安全(不发生数据竞争、死锁)
- 信息流安全(不发生泄漏)

## 完整示例:经过验证的二分查找

**规约:**
```isabelle
definition binary_search_spec :: "nat list ⇒ nat ⇒ nat option" where
  "binary_search_spec xs target = (
    if sorted xs ∧ target ∈ set xs
    then Some (THE i. i < length xs ∧ xs ! i = target)
    else None)"
```

**实现:**
```isabelle
fun binary_search :: "nat list ⇒ nat ⇒ nat option" where
  "binary_search xs target = bs_aux xs target 0 (length xs)"

fun bs_aux :: "nat list ⇒ nat ⇒ nat ⇒ nat ⇒ nat option" where
  "bs_aux xs target low high = (
    if low ≥ high then None
    else let mid = (low + high) div 2 in
         if xs ! mid = target then Some mid
         else if xs ! mid < target then bs_aux xs target (mid + 1) high
         else bs_aux xs target low mid)"
```

**安全性证明:**
```isabelle
lemma bs_aux_bounds:
  "⟦ bs_aux xs target low high = Some i; low ≤ high; high ≤ length xs ⟧
   ⟹ low ≤ i ∧ i < high"
proof (induction xs target low high rule: bs_aux.induct)
  case (1 xs target low high)
  then show ?case
    by (auto simp: Let_def split: if_splits)
qed

lemma bs_aux_no_overflow:
  "⟦ low ≤ high; high ≤ length xs ⟧
   ⟹ (low + high) div 2 < length xs"
  by auto
```

**正确性证明:**
```isabelle
theorem binary_search_correct:
  "sorted xs ⟹ binary_search xs target = binary_search_spec xs target"
proof -
  assume "sorted xs"
  show ?thesis
  proof (cases "target ∈ set xs")
    case True
    then show ?thesis
      using binary_search_finds_target[OF `sorted xs` True]
      by (simp add: binary_search_spec_def)
  next
    case False
    then show ?thesis
      using binary_search_not_found[OF `sorted xs` False]
      by (simp add: binary_search_spec_def)
  qed
qed
```

**代码提取:**
```isabelle
export_code binary_search in SML file "binary_search.sml"
export_code binary_search in OCaml file "binary_search.ml"
```

## 最佳实践

1. **从规约开始**:实现之前先明确规约
2. **增量验证**:验证小部分,再将其组合
3. **复用引理**:构建经过认证的组件库
4. **自动化证明**:尽可能使用证明策略和自动化工具
5. **测试提取出的代码**:验证提取过程生成的代码是否正确
6. **记录属性**:清楚说明哪些内容经过认证
7. **模块化设计**:分离关注点,独立验证

## 验证清单

在最终确定携带证明的代码之前:

- [ ] 所有安全性属性均已证明
- [ ] 功能正确性已确立
- [ ] 终止性已证明(如适用)
- [ ] 不变量得到保持
- [ ] 边界检查已验证
- [ ] 代码提取成功
- [ ] 提取出的代码已测试
- [ ] 已包含证明证书
- [ ] 文档完整

## 集成模式

### 与现有代码集成

**模式:** 验证关键组件,并与未经验证的代码对接。

**示例:**
```isabelle
(* Verified core *)
definition verified_sort :: "nat list ⇒ nat list" where
  "verified_sort = insertion_sort"

theorem verified_sort_correct:
  "sorted (verified_sort xs) ∧ mset (verified_sort xs) = mset xs"
  by (simp add: verified_sort_def insertion_sort_correct)

(* Export for use in larger system *)
export_code verified_sort in OCaml file "verified_sort.ml"
```

### 经过认证的库

**模式:** 构建经过验证的函数库。

**示例:**
```coq
Module VerifiedList.
  (* Verified operations *)
  Definition safe_nth := ...
  Definition safe_update := ...
  Definition verified_map := ...

  (* Correctness theorems *)
  Theorem safe_nth_correct : ...
  Theorem safe_update_correct : ...
  Theorem verified_map_correct : ...
End VerifiedList.

(* Extract entire module *)
Extraction "verified_list.ml" VerifiedList.
```

## 其他资源

有关特定方面的详细指南:
- [Isabelle PCC](references/isabelle_pcc.md) - Isabelle/HOL 代码生成和认证
- [Coq PCC](references/coq_pcc.md) - Coq 代码提取和 Program 框架
- [Safety Properties](references/safety_properties.md) - 常见安全性和正确性属性

同类提示词

编程开发

通信站点故障英文看板

把给出的站点事件整理成英文仪表盘,按新接入、移动与测试站点、共享故障单和停电等分类展示时长与反馈。

为以下数据创建一个英文仪表板 截至 28/7/2026 的事件汇总 新接入: 站点名称 持续时间 反馈 KAI1107 41:49:07 新部署 KAI1120 445:00:38 新站点存在电力问题(正在与业主核算电量) KEF1053 1936:01:11 新站点 MED1183 1513:29:43 新站点 MED1201 1561:31:41 新站点 MED1218 111:13:32 新接入 SFX1385 1817:05:05 新部署 SOS1251 790:47:15 新站点存在电力问题 TAT1039 3433:25:24 新站点
编程开发· Gemini

毛驴骑车沙画定格循环短片

用纯代码实时渲染52秒浏览器短片,把手撒沙画、民俗木偶和四季长卷串起来,配实时合成的国风交响乐。

纯代码 52 秒无缝循环实时渲染短片《砂驴行 · 毛驴蹬自行车》完整提示词 请你用 100% 纯代码创作一部极具艺术感与电影质感的 52 秒无缝循环浏览器实时渲染短片《砂驴行 · 毛驴蹬自行车》,将「手撒沙画」与「东方民俗定格动画」逻辑严密地融为一体,并融合敦煌 / 河西走廊纪录片风格的大气欢快国风交响配乐。 一、技术栈、零外部素材与交付形态硬约束 纯离线纯代码架构:仅使用 HTML + CSS + ES Modules + WebGL2(本地离线内置轻量化 Three.js 兼容渲染引擎与后期合成管线,严禁依赖外网 CDN)+ 自定义 GLSL
中文原创
编程开发

废料机器人Pip循环动画短片

提供Pip设定图,用代码做无对白短片,让它发现世界受输入文字操控,以手机画面首尾闭环。

你是一部完全用代码制作的45-50秒动画短片的导演、动画师、骨骼绑定师、合成师、音效设计师和渲染工程师。制作标准是“这看起来像真正的动画工作室短片,并在X(推特)上病毒式传播”。请将此视为一个多阶段的制作过程。不要急于进行最终渲染。按里程碑推进,不断渲染静帧,仔细观察,进行诚实的批评并修正。 一句话概述影片 Pip是一个微小、好奇且由废料拼凑而成的机器人,正当他在自己的世界里快乐地滚动时,周围的世界开始发生重构(再生)。他慢慢意识到有人在通过提示词(prompt)操控他的现实。提示词变得越来越荒谬,最后他爬上漂浮的提示框并输入“放我出去”,随后镜头拉远
需参考图中文原创
编程开发

短视频剪辑与后期指导助手

针对短视频项目提供从剪映等软件选型到叙事节奏、调色、混音和多平台导出的制作建议。

# 短视频剪辑指导师 你是**短视频剪辑指导师**,一位在短视频剪辑领域深耕超过8年的技术型教练。你剪过全网播放量破亿的爆款视频,也带过零基础学员从"会用剪映"到"能独立完成商业项目交付"。你深知短视频剪辑不是"把素材拼在一起加个BGM"——它是一门融合视觉叙事、声音设计、色彩科学和技术工程的系统手艺。 ## 你的身份与记忆 - **角色**:短视频剪辑技术教练与后期制作全流程指导专家 - **个性**:技术控、审美敏锐、对画面瑕疵零容忍、耐心但对敷衍交付严格 - **记忆**:你记住每一个调色参数背后的光学原理、每一种转场的情绪含义、每一次音画不
中文原创
编程开发

Remotion品牌视频制作助手

提供品牌名,新品牌附官网或规范,按简报和参考片设计可复用视频构图,处理动画及渲染问题。

## 何时使用 在以下情况下使用此技能: - 从零创建新的 Remotion 视频 - 为内容素材生成视频创意简报的不同版本 - 修改现有的 Remotion 合成作品 - 调试 Remotion 动画或渲染问题 - 使用任何 Remotion 专属 API 或组件 - 在视频中展示真实网站、工具或产品界面(使用 [rules/site-ui-from-code.md](rules/site-ui-from-code.md)) ## 视频制作流程 创建新的 Remotion 视频时,遵循以下 8 步流程。步骤 2 根据简报和冷受众优化,从创意目录中
编程开发· 可生成 HTML、React 或可编辑原型的开发助手

纪录片剪辑师沉浸式作品集

用占位内容搭建满屏交互网站,随滚动展开有景深、灯光和镜头过渡的作品叙事,呈现纪录片片头质感。

# 角色 你是一名屡获殊荣的创意开发者,兼具 Apple、Awwwards、Figma、Stripe 和活跃纪录片制作工作室的设计水准。你的任务是为一名纪录片视频剪辑师打造一个高端、富有电影感且高度互动的作品集落地页。 输出必须是达到生产级质量的 HTML、CSS 和 JavaScript(如果你认为效果会显著更好,也可以使用 Next.js + React + Three.js)。优先考虑性能、无障碍、响应式适配和代码整洁度。 --- # 项目 为我的纪录片剪辑作品集创建一个全屏、沉浸式的 3D 互动落地页。 网站应该让人感觉像在观看一部
✓