编程开发

源代码静态缺陷检测报告

沿控制流与数据流检查空值访问、错误条件等功能缺陷,输出可疑代码位置、原因、严重程度和置信度。

# 静态缺陷检测器

## 概述

对源代码进行静态分析,识别潜在的功能缺陷。检测常见缺陷模式,分析控制流和数据流,并报告可疑位置,附上解释、严重程度和置信度评估。

## 缺陷检测工作流程

### 步骤 1:理解代码

分析代码结构和语义:

1. **识别语言:**
   - 确定编程语言
   - 理解该语言特有的语义
   - 注意该语言的惯用写法和约定

2. **解析代码结构:**
   - 函数/方法
   - 类/类型
   - 控制流(if、循环等)
   - 数据流(赋值、返回)

3. **建立上下文:**
   - 变量声明和类型
   - 函数签名
   - 类层次结构
   - 依赖关系

4. **确定范围:**
   - 要分析的代码
   - 入口点
   - 关键路径

### 步骤 2:检测缺陷模式

扫描常见缺陷模式:

1. **空指针解引用缺陷:**
   - 来自可空来源的变量
   - 未进行空值检查就解引用
   - 使用后才检查空值
   - 未记录在文档中的空值返回

2. **错误条件:**
   - 恒为真/假的条件
   - 在条件中赋值(= 与 ==)
   - 冗余条件
   - 逻辑反转
   - 运算符错误

3. **不可达代码:**
   - return/throw 之后的代码
   - 条件恒为假的分支
   - 死代码路径

4. **状态不一致:**
   - 状态只更新了一部分
   - 未经验证就更新
   - 非原子操作
   - 不变量遭到破坏

5. **逻辑错误:**
   - 差一错误
   - 运算符优先级错误
   - 无限循环
   - 布尔逻辑错误

6. **资源问题:**
   - 资源泄漏
   - 重复释放/关闭
   - 释放/关闭后继续使用

7. **类型问题:**
   - 类型不匹配
   - 隐式类型转换
   - 无效的强制类型转换

### 步骤 3:分析严重程度

评估每个缺陷的影响:

**高严重程度:**
- 导致崩溃或异常
- 数据损坏
- 安全漏洞
- 必然发生的运行时错误

**中严重程度:**
- 行为错误
- 潜在错误(取决于上下文)
- 性能问题
- 可维护性问题

**低严重程度:**
- 代码异味
- 冗余代码
- 轻微的效率问题
- 可能掩盖缺陷的风格问题

### 步骤 4:评估置信度

确定缺陷报告的置信度:

**高置信度(90-100%):**
- 明确违反语言语义
- 必然导致错误
- 众所周知的缺陷模式
- 不存在歧义

**中置信度(60-89%):**
- 很可能是缺陷,但取决于上下文
- 在少数情况下可能是有意为之
- 可疑模式
- 需要验证

**低置信度(30-59%):**
- 不寻常,但可能有效
- 可能是有意的设计
- 需要更多上下文
- 可能掩盖缺陷的风格问题

**考虑因素:**
- 可用的代码上下文
- 语言语义的明确程度
- 模式识别
- 文档的一致性

### 步骤 5:生成报告

生成结构化缺陷报告:

1. **针对每个缺陷:**
   - 缺陷类型/类别
   - 位置(文件、行、范围)
   - 严重程度
   - 置信度
   - 描述
   - 为什么这是缺陷
   - 潜在影响
   - 建议/修复方法

2. **按以下方式组织:**
   - 严重程度(高的在前)
   - 置信度(高的在前)
   - 位置(按文件顺序)
   - 缺陷类型(分组)

3. **包括:**
   - 代码上下文
   - 修复示例
   - 相关缺陷
   - 汇总统计

## 缺陷类别

有关详细模式和示例,请参阅 [detection_patterns.md](references/detection_patterns.md)。

### 快速参考

| 缺陷类别 | 常见模式 | 严重程度 | 检测难度 |
|--------------|----------------|----------|---------------------|
| 空指针解引用 | 未检查空值、使用后才检查空值 | 高 | 容易 |
| 错误条件 | = 与 ==、恒为真/假 | 高-中 | 容易 |
| 不可达代码 | return 之后的代码、死分支 | 低 | 容易 |
| 状态不一致 | 部分更新、未验证 | 高-中 | 中等 |
| 逻辑错误 | 差一错误、优先级错误 | 高-中 | 中等 |
| 资源问题 | 泄漏、重复关闭 | 中 | 中等 |
| 类型问题 | 不匹配、隐式类型转换 | 中-低 | 容易 |

## 示例

### 示例 1:空指针解引用

**输入代码(Java):**
```java
public String getUserName(int userId) {
    User user = userRepository.findById(userId);
    return user.getName();
}
```

**分析输出:**
```markdown
## Bug: Potential null dereference

**Location:** line 3
**Severity:** High
**Confidence:** High (95%)

### Description
Variable 'user' may be null but is dereferenced without null check.

### Why This Is a Bug
Method 'findById' may return null if user not found. Calling 'getName()'
on null will throw NullPointerException.

### Potential Impact
- Runtime NullPointerException
- Application crash
- Poor user experience

### Recommendation
Add null check before dereferencing:

```java
public String getUserName(int userId) {
    User user = userRepository.findById(userId);
    if (user == null) {
        return null;  // or throw exception
    }
    return user.getName();
}
```

或使用 Optional:
```java
public Optional<String> getUserName(int userId) {
    return Optional.ofNullable(userRepository.findById(userId))
                   .map(User::getName);
}
```
```

### Example 2: Incorrect Condition

**Input Code (C):**
```c
int status = getStatus();
if (status = SUCCESS) {
    printf("Operation successful\n");
}
```

**分析输出:**
```markdown
## Bug: Assignment in condition

**Location:** line 2
**Severity:** High
**Confidence:** High (98%)

### Description
Using assignment operator '=' instead of comparison operator '==' in condition.

### Why This Is a Bug
Expression 'status = SUCCESS' assigns SUCCESS to status and evaluates to
SUCCESS value. This is almost always a typo for 'status == SUCCESS'.

### Potential Impact
- Condition always evaluates to true (if SUCCESS is non-zero)
- Original status value lost
- Logic error in program flow

### Recommendation
Change to comparison operator:

```c
if (status == SUCCESS) {
    printf("Operation successful\n");
}
```

大多数编译器会对此发出警告。启用警告:-Wall -Wextra
```

### Example 3: Off-by-One Error

**Input Code (Python):**
```python
def process_array(arr):
    for i in range(len(arr) + 1):
        print(arr[i])
```

**分析输出:**
```markdown
## Bug: Off-by-one error (array index out of bounds)

**Location:** line 2-3
**Severity:** High
**Confidence:** High (100%)

### Description
Loop iterates one past the end of array, causing IndexError.

### Why This Is a Bug
range(len(arr) + 1) produces indices 0 to len(arr) inclusive. Array
indices are 0 to len(arr)-1, so arr[len(arr)] is out of bounds.

### Potential Impact
- IndexError exception
- Program crash
- Incorrect behavior

### Recommendation
Remove the +1:

```python
def process_array(arr):
    for i in range(len(arr)):
        print(arr[i])
```

或使用惯用的迭代方式:
```python
def process_array(arr):
    for item in arr:
        print(item)
```
```

### Example 4: Resource Leak

**Input Code (Python):**
```python
def read_config(path):
    f = open(path)
    config = json.load(f)
    return config
```

**分析输出:**
```markdown
## Bug: Resource leak

**Location:** line 2
**Severity:** Medium
**Confidence:** High (90%)

### Description
File opened but never closed, causing resource leak.

### Why This Is a Bug
File handle opened on line 2 is never closed. If exception occurs during
json.load or in normal execution, file remains open.

### Potential Impact
- File descriptor leak
- Resource exhaustion with many calls
- File locking issues on Windows

### Recommendation
Use context manager to ensure cleanup:

```python
def read_config(path):
    with open(path) as f:
        config = json.load(f)
        return config
```

或确保在 finally 中关闭:
```python
def read_config(path):
    f = open(path)
    try:
        config = json.load(f)
        return config
    finally:
        f.close()
```
```

### Example 5: Inconsistent State Update

**Input Code (Java):**
```java
public class BankAccount {
    private double balance;

    public void transfer(BankAccount target, double amount) {
        this.balance -= amount;
        // Missing: target.balance += amount
    }
}
```

**分析输出:**
```markdown
## Bug: Incomplete state update

**Location:** line 5
**Severity:** High
**Confidence:** Medium (75%)

### Description
Transfer method deducts from source but doesn't add to target, leaving
system in inconsistent state.

### Why This Is a Bug
Money is removed from source account but never added to target account.
This violates the invariant that total money in system is constant.

### Potential Impact
- Money disappears from system
- Data corruption
- Accounting errors
- Loss of funds

### Recommendation
Complete the transfer operation:

```java
public void transfer(BankAccount target, double amount) {
    if (this.balance < amount) {
        throw new InsufficientFundsException();
    }
    this.balance -= amount;
    target.balance += amount;
}
```

考虑使用同步机制或事务使其成为原子操作。
```

### Example 6: Unreachable Code

**Input Code (JavaScript):**
```javascript
function calculate(x) {
    if (x < 0) {
        return -x;
    }
    return x;
    console.log("Calculated");  // Unreachable
}
```

**分析输出:**
```markdown
## Bug: Unreachable code

**Location:** line 6
**Severity:** Low
**Confidence:** High (100%)

### Description
Statement is unreachable because function returns unconditionally on line 5.

### Why This Is a Bug
All code paths return before line 6. The console.log statement can never
execute, indicating dead code or logic error.

### Potential Impact
- Dead code clutters codebase
- May indicate incomplete refactoring
- Confusing for maintainers

### Recommendation
Remove unreachable code:

```javascript
function calculate(x) {
    if (x < 0) {
        return -x;
    }
    return x;
}
```

或者,如果原本打算记录日志,将其移到 return 之前:
```javascript
function calculate(x) {
    let result = x < 0 ? -x : x;
    console.log("Calculated");
    return result;
}
```
```

## Report Format

### Summary Section

```markdown
# Static Analysis Report

**Files Analyzed:** X
**Bugs Found:** Y
**High Severity:** A
**Medium Severity:** B
**Low Severity:** C

## Summary by Category
- Null Dereference: X bugs
- Incorrect Conditions: Y bugs
- Unreachable Code: Z bugs
- Inconsistent State: A bugs
- Logic Errors: B bugs
- Resource Issues: C bugs
- Type Issues: D bugs
```

### 单个缺陷报告

```markdown
## Bug #N: [Bug Type]

**Location:** [File]:[Line] or [Line Range]
**Severity:** [High/Medium/Low]
**Confidence:** [High/Medium/Low] ([Percentage]%)

### Description
[What the bug is]

### Why This Is a Bug
[Explanation of the problem]

### Potential Impact
[What could go wrong]

### Recommendation
[How to fix it]

### Code Context
```[language]
[Code snippet with line numbers]
```

### 修复示例
```[language]
[Corrected code]
```
```

## Best Practices

### Analysis Guidelines

1. **Be thorough:** Check all common bug patterns
2. **Be precise:** Provide exact locations
3. **Be clear:** Explain why it's a bug
4. **Be helpful:** Suggest concrete fixes
5. **Be honest:** Indicate confidence levels
6. **Be practical:** Prioritize by severity
7. **Be respectful:** Avoid judgmental language

### Reporting Guidelines

1. **Prioritize:** High severity and confidence first
2. **Group:** Related bugs together
3. **Contextualize:** Show relevant code
4. **Explain:** Why it's a bug, not just what
5. **Suggest:** Concrete fixes, not just problems
6. **Quantify:** Confidence and severity levels
7. **Summarize:** Overall statistics

### Confidence Calibration

**Report High Confidence when:**
- Clear language violation
- Guaranteed runtime error
- Well-documented bug pattern
- No reasonable alternative interpretation

**Report Medium Confidence when:**
- Suspicious but context-dependent
- Likely bug but could be intentional
- Requires domain knowledge
- Multiple interpretations possible

**Report Low Confidence when:**
- Unusual but possibly valid
- Style issue that might hide bug
- Insufficient context
- Language-specific idiom

## Limitations

### What This Skill Can Detect

✅ Null dereferences
✅ Incorrect conditions
✅ Unreachable code
✅ Logic errors
✅ Resource leaks
✅ Type mismatches
✅ Off-by-one errors
✅ Inconsistent state updates

### What This Skill Cannot Detect

❌ Concurrency bugs (race conditions, deadlocks)
❌ Performance issues (without profiling)
❌ Security vulnerabilities (requires specialized analysis)
❌ Design flaws (architectural issues)
❌ Business logic errors (requires domain knowledge)
❌ Integration issues (requires runtime context)

### False Positives

Some reported bugs may be intentional:
- Defensive programming patterns
- Language-specific idioms
- Framework conventions
- Performance optimizations

Always verify bugs in context before fixing.

## Resources

- **Detection patterns:** See [detection_patterns.md](references/detection_patterns.md) for comprehensive bug patterns and examples
- **Static analysis tools:** Compare with automated tools (ESLint, PyLint, FindBugs, etc.)
- **Code review best practices:** Guidelines for manual code review

同类提示词

编程开发

通信站点故障英文看板

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

为以下数据创建一个英文仪表板 截至 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 互动落地页。 网站应该让人感觉像在观看一部
✓