image
VincentWei

天地间,浩然正气长存,为天地立心,为生民立命,为往圣继绝学,为万世开太平!

免责声明:网站内容仅供个人学习记录,禁做商业用途,转载请注明出处。

版权所有 © 2017-2020 NEUSNCP个人学习笔记 辽ICP备17017855号-2

Py2C++11 Agent Skill's Cooperator

VincentWei    2026年3月31日 23:10:59

C++11 智能编译器 Agent Skill 设计文档

版本: 1.0.0 日期: 2026-03-31 作者: weijl


目录

  1. 概述

  2. 系统架构

  3. 核心组件设计

  4. 工作流程

  5. 错误处理系统

  6. 自动化修复策略

  7. API设计

  8. 脚本工具设计

  9. 测试策略

  10. 性能优化

  11. 安全考虑

  12. 部署方案

  13. 未来扩展


1. 概述

1.1 项目背景

C++是一种强类型、静态编译的语言,编译时错误信息复杂且难以理解,特别是对于初学者,协助Py2C++ Agent,将其转化后的C++代码进行编译测试,autofix。传统的C++开发流程需要:

  1. 手动编写代码

  2. 编译并查看错误

  3. 理解错误信息

  4. 修复代码

  5. 重复步骤2-4直到成功

这个过程耗时且容易出错。C++11智能编译器Agent通过AI辅助自动化这个流程,大大提高开发效率。

1.2 目标与范围

主要目标

  • 自动化C++11代码编译流程

  • 智能分析编译错误

  • 自动修复常见错误

  • 运行测试验证代码正确性

  • 提供详细的错误报告和修复建议

适用范围

  • C++11标准代码

  • GCC 4.8.1+ / Clang 3.3+ 编译器

  • 单文件和简单多文件项目

  • 标准库和常用第三方库

不适用范围

  • C++14/17/20特性

  • 复杂的模板元编程

  • 大型多模块项目

  • 特定平台API

1.3 核心特性

特性 描述
智能编译 自动检测编译器,选择最优编译选项
错误分析 深度分析错误原因,分类处理
自动修复 自动修复常见语法和类型错误
测试验证 运行可执行文件,验证输出
迭代优化 多轮修复直到成功,最大10次
详细报告 提供JSON和文本格式的报告

2. 系统架构

2.1 整体架构图

┌─────────────────────────────────────────────────────────────────┐
│                      User Interface Layer                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │  CLI Tools   │  │   AI Agent   │  │   REST API   │         │
│  │  (Bash)      │  │  (LLM)       │  │  (HTTP)      │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│                     Core Processing Layer                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │  Compiler    │  │    Error     │  │     Auto     │         │
│  │  Engine      │←→│   Analyzer   │←→│    Fixer     │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
│         ↓                  ↓                  ↓                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │  Test        │  │   Report     │  │    Code      │         │
│  │  Runner      │  │   Generator  │  │   Modifier   │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│                     Infrastructure Layer                         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │  File System │  │   Process    │  │    Temp      │         │
│  │  Manager     │  │   Executor   │  │   Manager    │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │  Compiler    │  │   Logger     │  │    Config    │         │
│  │  Detection   │  │   System     │  │    Manager   │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│                      External Systems                            │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │     g++      │  │   clang++    │  │   LLM API    │         │
│  │  Compiler    │  │   Compiler   │  │  (Optional)  │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
└─────────────────────────────────────────────────────────────────┘

2.2 组件交互流程

用户代码输入
    ↓
[Compiler Engine] → 调用编译器 → 获取输出
    ↓
[Error Analyzer] → 解析错误 → 分类错误 → 生成修复建议
    ↓
[Auto Fixer] → 应用修复 → 更新代码
    ↓
    ├→ [成功] → [Test Runner] → 验证结果 → [完成]
    └→ [失败] → [重新编译] → 循环(最多10次)

2.3 数据流图

┌─────────┐    Source.cpp     ┌──────────────┐
│  User   │ ──────────────────→│ Code Parser  │
└─────────┘                    └──────────────┘
                                      │
                                      ↓ ParsedCode
                               ┌──────────────┐
                               │  Compiler    │
                               │  Executor    │
                               └──────────────┘
                                      │
                                      ↓ CompileResult
                               ┌──────────────┐
                               │    Error     │
                               │   Analyzer   │
                               └──────────────┘
                                      │
                                      ↓ ErrorReport
                               ┌──────────────┐
                               │     Auto     │
                               │    Fixer     │
                               └──────────────┘
                                      │
                                      ↓ FixedCode
                               ┌──────────────┐
                               │    Test      │
                               │   Runner     │
                               └──────────────┘
                                      │
                                      ↓ TestResult
                               ┌──────────────┐
                               │   Report     │
                               │  Generator   │
                               └──────────────┘
                                      │
                                      ↓ FinalReport
                               ┌──────────────┐
                               │    User      │
                               └──────────────┘

3. 核心组件设计

3.1 Compiler Engine

3.1.1 设计目标

  • 自动检测可用的C++编译器

  • 选择最优编译选项

  • 处理编译超时和异常

  • 捕获完整的编译输出

3.1.2 类设计

class CompilerEngine:
    """
    编译器引擎,负责调用本地C++编译器
    """
    
    # 支持的编译器列表
    SUPPORTED_COMPILERS = ['g++', 'clang++']
    
    # 默认编译选项
    DEFAULT_FLAGS = {
        'std': '-std=c++11',
        'warnings': ['-Wall', '-Wextra', '-Wpedantic'],
        'debug': '-g',
        'optimization': '-O0'
    }
    
    def __init__(self, config: CompilerConfig):
        """
        初始化编译器引擎
        
        Args:
            config: 编译器配置对象
        """
        self.compiler_path = self._detect_compiler()
        self.config = config
        self.temp_dir = tempfile.mkdtemp()
    
    def _detect_compiler(self) -> str:
        """
        自动检测可用的编译器
        
        Returns:
            编译器路径
            
        Raises:
            CompilerNotFoundError: 未找到支持的编译器
        """
        for compiler in self.SUPPORTED_COMPILERS:
            if self._is_compiler_available(compiler):
                return self._get_compiler_path(compiler)
        raise CompilerNotFoundError("No supported C++ compiler found")
    
    def compile(self, source_file: str, output_file: str, 
                extra_flags: List[str] = None) -> CompileResult:
        """
        编译C++源文件
        
        Args:
            source_file: 源文件路径
            output_file: 输出文件路径
            extra_flags: 额外的编译选项
            
        Returns:
            CompileResult对象,包含编译结果和输出
        """
        # 构建编译命令
        cmd = self._build_compile_command(source_file, output_file, extra_flags)
        
        # 执行编译
        try:
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=self.config.compile_timeout
            )
            
            return CompileResult(
                success=(result.returncode == 0),
                return_code=result.returncode,
                stdout=result.stdout,
                stderr=result.stderr,
                output_file=output_file if result.returncode == 0 else None
            )
        except subprocess.TimeoutExpired:
            raise CompileTimeoutError(f"Compilation timeout after {self.config.compile_timeout}s")
    
    def _build_compile_command(self, source: str, output: str, 
                               extra_flags: List[str]) -> List[str]:
        """构建完整的编译命令"""
        cmd = [self.compiler_path]
        
        # 添加标准选项
        cmd.append(self.DEFAULT_FLAGS['std'])
        cmd.extend(self.DEFAULT_FLAGS['warnings'])
        cmd.append(self.DEFAULT_FLAGS['debug'])
        cmd.append(self.DEFAULT_FLAGS['optimization'])
        
        # 添加额外选项
        if extra_flags:
            cmd.extend(extra_flags)
        
        # 添加输出选项
        cmd.extend(['-o', output, source])
        
        return cmd

3.1.3 编译选项说明

选项 默认值 说明
-std=c++11 必需 指定C++11标准
-Wall 启用 启用所有常见警告
-Wextra 启用 启用额外警告
-Wpedantic 启用 严格遵循ISO C++标准
-g 启用 生成调试信息
-O0 默认 无优化,便于调试
-fsanitize=address 可选 地址检测(运行时)
-fsanitize=undefined 可选 未定义行为检测

3.2 Error Analyzer

3.2.1 设计目标

  • 解析编译器的错误输出

  • 分类错误类型

  • 提取错误位置和原因

  • 生成修复建议

3.2.2 错误分类体系

class ErrorType(Enum):
    """错误类型枚举"""
    
    # 语法错误
    SYNTAX_ERROR = "syntax_error"
    MISSING_SEMICOLON = "missing_semicolon"
    UNMATCHED_PARENTHESIS = "unmatched_parenthesis"
    UNMATCHED_BRACE = "unmatched_brace"
    
    # 声明错误
    DECLARATION_ERROR = "declaration_error"
    UNDECLARED_IDENTIFIER = "undeclared_identifier"
    REDEFINITION = "redefinition"
    
    # 类型错误
    TYPE_ERROR = "type_error"
    TYPE_MISMATCH = "type_mismatch"
    INVALID_CONVERSION = "invalid_conversion"
    
    # 链接错误
    LINKER_ERROR = "linker_error"
    UNDEFINED_REFERENCE = "undefined_reference"
    MULTIPLE_DEFINITION = "multiple_definition"
    
    # 模板错误
    TEMPLATE_ERROR = "template_error"
    TEMPLATE_ARGUMENT_ERROR = "template_argument_error"
    
    # 警告
    WARNING = "warning"
    
    # 其他
    OTHER = "other"

3.2.3 错误解析器设计

class ErrorAnalyzer:
    """
    编译错误分析器
    """
    
    # 错误模式定义
    ERROR_PATTERNS = {
        'missing_semicolon': {
            'pattern': r"expected ';' before '([^']+)'",
            'type': ErrorType.MISSING_SEMICOLON,
            'suggestion': lambda m: f"在 '{m.group(1)}' 前添加分号 ';'"
        },
        'undeclared_identifier': {
            'pattern': r"'([^']+)' was not declared in this scope",
            'type': ErrorType.UNDECLARED_IDENTIFIER,
            'suggestion': lambda m: self._suggest_declaration(m.group(1))
        },
        'type_mismatch': {
            'pattern': r"cannot convert '([^']+)' to '([^']+)'",
            'type': ErrorType.TYPE_MISMATCH,
            'suggestion': lambda m: f"无法将 '{m.group(1)}' 转换为 '{m.group(2)}'"
        },
        # ... 更多模式
    }
    
    def analyze(self, compile_output: str) -> ErrorReport:
        """
        分析编译输出,生成错误报告
        
        Args:
            compile_output: 编译器的输出文本
            
        Returns:
            ErrorReport对象,包含所有错误和警告
        """
        errors = []
        warnings = []
        
        # 按行解析
        for line in compile_output.split('\n'):
            parsed = self._parse_error_line(line)
            if parsed:
                if parsed.is_warning:
                    warnings.append(parsed)
                else:
                    errors.append(parsed)
        
        # 生成统计和建议
        return ErrorReport(
            errors=errors,
            warnings=warnings,
            statistics=self._generate_statistics(errors, warnings),
            suggestions=self._generate_suggestions(errors)
        )
    
    def _parse_error_line(self, line: str) -> Optional[CompileError]:
        """解析单行错误信息"""
        # 匹配格式: file:line:column: error: message
        match = re.match(
            r'([^:]+):(\d+):(?:(\d+):)? (error|warning): (.+)',
            line
        )
        
        if not match:
            return None
        
        file, line_num, col, level, message = match.groups()
        
        # 匹配错误模式
        error_type = ErrorType.OTHER
        suggestion = None
        
        for pattern_name, pattern_info in self.ERROR_PATTERNS.items():
            if re.search(pattern_info['pattern'], message):
                error_type = pattern_info['type']
                suggestion = pattern_info['suggestion'](match)
                break
        
        return CompileError(
            file=file,
            line=int(line_num),
            column=int(col) if col else 0,
            type=error_type,
            message=message,
            raw_line=line,
            suggestion=suggestion
        )
    
    def _suggest_declaration(self, identifier: str) -> str:
        """为未声明的标识符提供建议"""
        # 检查是否是标准库符号
        STD_SYMBOLS = {
            'cout': '#include <iostream> 和 std::cout',
            'cin': '#include <iostream> 和 std::cin',
            'string': '#include <string> 和 std::string',
            'vector': '#include <vector> 和 std::vector',
            'map': '#include <map> 和 std::map',
            # ... 更多符号
        }
        
        if identifier in STD_SYMBOLS:
            return f"可能需要 {STD_SYMBOLS[identifier]}"
        
        return f"检查 '{identifier}' 是否已声明或拼写正确"

3.3 Auto Fixer

3.3.1 设计目标

  • 自动修复常见错误

  • 保持代码风格

  • 避免引入新错误

  • 记录所有修改

3.3.2 修复策略设计

class AutoFixer:
    """
    自动修复器,负责修复常见的编译错误
    """
    
    def __init__(self):
        self.fixes_applied = []
        self.code_lines = []
    
    def fix(self, code: str, errors: List[CompileError]) -> FixResult:
        """
        自动修复代码中的错误
        
        Args:
            code: 原始代码
            errors: 错误列表
            
        Returns:
            FixResult对象,包含修复后的代码和修改记录
        """
        self.code_lines = code.split('\n')
        self.fixes_applied = []
        
        # 按行号分组错误
        errors_by_line = self._group_errors_by_line(errors)
        
        # 按优先级处理错误
        for line_num, line_errors in sorted(errors_by_line.items()):
            for error in line_errors:
                self._apply_fix(error)
        
        fixed_code = '\n'.join(self.code_lines)
        
        return FixResult(
            original_code=code,
            fixed_code=fixed_code,
            fixes_applied=self.fixes_applied
        )
    
    def _apply_fix(self, error: CompileError):
        """应用单个修复"""
        line_idx = error.line - 1  # 转为0-based索引
        
        if error.type == ErrorType.MISSING_SEMICOLON:
            self._fix_missing_semicolon(line_idx, error)
        elif error.type == ErrorType.UNDECLARED_IDENTIFIER:
            self._fix_undeclared_identifier(line_idx, error)
        elif error.type == ErrorType.TYPE_MISMATCH:
            self._fix_type_mismatch(line_idx, error)
        # ... 更多修复类型
    
    def _fix_missing_semicolon(self, line_idx: int, error: CompileError):
        """修复缺失的分号"""
        line = self.code_lines[line_idx]
        fixed_line = line.rstrip() + ';'
        self.code_lines[line_idx] = fixed_line
        
        self.fixes_applied.append(FixRecord(
            line=line_idx + 1,
            type='add_semicolon',
            original=line,
            fixed=fixed_line,
            description='添加缺失的分号'
        ))
    
    def _fix_undeclared_identifier(self, line_idx: int, error: CompileError):
        """修复未声明的标识符"""
        identifier = self._extract_identifier(error.message)
        
        # 检查是否需要添加std::前缀
        if self._is_std_symbol(identifier):
            line = self.code_lines[line_idx]
            fixed_line = self._add_std_prefix(line, identifier)
            
            if fixed_line != line:
                self.code_lines[line_idx] = fixed_line
                self.fixes_applied.append(FixRecord(
                    line=line_idx + 1,
                    type='add_std_prefix',
                    original=line,
                    fixed=fixed_line,
                    description=f"添加 std:: 前缀到 {identifier}"
                ))
                return
        
        # 检查是否需要添加头文件
        header = self._get_required_header(identifier)
        if header:
            self._add_header(header)
            self.fixes_applied.append(FixRecord(
                line=0,  # 头文件在第0行
                type='add_header',
                original='',
                fixed=f'#include {header}',
                description=f"添加头文件 {header}"
            ))
    
    def _is_std_symbol(self, identifier: str) -> bool:
        """检查是否是标准库符号"""
        STD_SYMBOLS = {
            'cout', 'cin', 'cerr', 'endl',
            'string', 'vector', 'map', 'set',
            'shared_ptr', 'unique_ptr', 'make_shared',
            # ... 更多
        }
        return identifier in STD_SYMBOLS
    
    def _get_required_header(self, identifier: str) -> Optional[str]:
        """获取标识符所需的头文件"""
        HEADER_MAP = {
            'cout': '<iostream>',
            'cin': '<iostream>',
            'string': '<string>',
            'vector': '<vector>',
            'map': '<map>',
            'set': '<set>',
            'shared_ptr': '<memory>',
            'unique_ptr': '<memory>',
            # ... 更多
        }
        return HEADER_MAP.get(identifier)

3.3.3 修复优先级

优先级 1: 头文件缺失 (影响后续所有符号解析)
优先级 2: 命名空间问题 (std::前缀)
优先级 3: 语法错误 (分号、括号等)
优先级 4: 类型错误 (类型转换)
优先级 5: 逻辑错误 (需要人工介入)

3.4 Test Runner

3.4.1 设计目标

  • 运行编译后的可执行文件

  • 捕获标准输出和错误

  • 处理超时和异常

  • 验证测试结果

3.4.2 测试框架设计

class TestRunner:
    """
    测试运行器,负责运行和验证测试
    """
    
    def __init__(self, config: TestConfig):
        self.config = config
    
    def run_tests(self, executable: str, 
                  test_cases: List[TestCase] = None) -> TestResult:
        """
        运行测试
        
        Args:
            executable: 可执行文件路径
            test_cases: 测试用例列表(可选)
            
        Returns:
            TestResult对象,包含测试结果
        """
        results = []
        
        if test_cases:
            # 运行指定的测试用例
            for test_case in test_cases:
                result = self._run_single_test(executable, test_case)
                results.append(result)
        else:
            # 直接运行可执行文件
            result = self._run_executable(executable)
            results.append(result)
        
        return TestResult(
            total=len(results),
            passed=sum(1 for r in results if r.passed),
            failed=sum(1 for r in results if not r.passed),
            results=results
        )
    
    def _run_executable(self, executable: str) -> SingleTestResult:
        """运行单个可执行文件"""
        try:
            result = subprocess.run(
                [executable],
                capture_output=True,
                text=True,
                timeout=self.config.test_timeout
            )
            
            return SingleTestResult(
                name='main',
                passed=(result.returncode == 0),
                return_code=result.returncode,
                stdout=result.stdout,
                stderr=result.stderr,
                duration=0  # TODO: 添加计时
            )
        except subprocess.TimeoutExpired:
            return SingleTestResult(
                name='main',
                passed=False,
                error='Timeout',
                error_message=f'Test timed out after {self.config.test_timeout}s'
            )
        except Exception as e:
            return SingleTestResult(
                name='main',
                passed=False,
                error='Exception',
                error_message=str(e)
            )

4. 工作流程

4.1 主流程图

开始
  │
  ↓
[接收代码]
  │
  ↓
[预处理代码] ← 添加必要信息
  │
  ↓
┌─────────────┐
│  编译循环   │ ← 最大10次迭代
└─────────────┘
  │
  ├──→ [编译成功] ──→ [运行测试] ──→ [生成报告] ──→ 结束
  │                         │
  │                         ↓
  │                    [测试失败] ──→ [分析错误] ──┐
  │                                                │
  ↓                                                │
[编译失败]                                          │
  │                                                │
  ↓                                                │
[分析错误]                                          │
  │                                                │
  ↓                                                │
[生成修复]                                          │
  │                                                │
  ↓                                                │
[应用修复] ─────────────────────────────────────────┘
  │
  ↓
[检查迭代次数]
  │
  ├──→ 未超过 ──→ 重新编译
  │
  └──→ 已超过 ──→ [失败报告] ──→ 结束

4.2 状态机设计

class CompilerState(Enum):
    """编译器状态"""
    IDLE = "idle"                    # 空闲
    PREPARING = "preparing"          # 准备中
    COMPILING = "compiling"          # 编译中
    ANALYZING = "analyzing"          # 分析中
    FIXING = "fixing"                # 修复中
    TESTING = "testing"              # 测试中
    COMPLETED = "completed"          # 完成
    FAILED = "failed"                # 失败

class CompilerStateMachine:
    """
    编译器状态机,管理整个编译流程
    """
    
    TRANSITIONS = {
        CompilerState.IDLE: [CompilerState.PREPARING],
        CompilerState.PREPARING: [CompilerState.COMPILING, CompilerState.FAILED],
        CompilerState.COMPILING: [CompilerState.ANALYZING, CompilerState.TESTING, CompilerState.FAILED],
        CompilerState.ANALYZING: [CompilerState.FIXING, CompilerState.FAILED],
        CompilerState.FIXING: [CompilerState.COMPILING, CompilerState.FAILED],
        CompilerState.TESTING: [CompilerState.COMPLETED, CompilerState.ANALYZING, CompilerState.FAILED],
        CompilerState.COMPLETED: [CompilerState.IDLE],
        CompilerState.FAILED: [CompilerState.IDLE],
    }
    
    def __init__(self):
        self.state = CompilerState.IDLE
        self.iteration_count = 0
        self.max_iterations = 10
    
    def transition(self, new_state: CompilerState):
        """状态转换"""
        if new_state not in self.TRANSITIONS[self.state]:
            raise InvalidStateTransition(
                f"Cannot transition from {self.state} to {new_state}"
            )
        
        self.state = new_state
        
        # 计数编译迭代
        if new_state == CompilerState.COMPILING:
            self.iteration_count += 1
            if self.iteration_count > self.max_iterations:
                raise MaxIterationsExceeded(
                    f"Exceeded maximum iterations ({self.max_iterations})"
                )

4.3 详细步骤

步骤1: 代码预处理

def preprocess_code(code: str) -> str:
    """
    预处理代码,添加必要信息
    
    1. 检测编码
    2. 规范化换行符
    3. 添加必要的注释
    4. 检测代码风格
    """
    # 规范化换行符
    code = code.replace('\r\n', '\n').replace('\r', '\n')
    
    # 检测是否缺少必要的结构
    if 'int main' not in code:
        # 提示可能需要main函数
        pass
    
    return code

步骤2: 编译执行

def execute_compilation(code: str, config: Config) -> CompileResult:
    """
    执行编译
    
    1. 创建临时文件
    2. 写入代码
    3. 调用编译器
    4. 捕获输出
    5. 清理临时文件
    """
    # 创建临时目录
    temp_dir = tempfile.mkdtemp(prefix='cpp_compile_')
    
    try:
        # 写入源文件
        source_file = os.path.join(temp_dir, 'source.cpp')
        with open(source_file, 'w', encoding='utf-8') as f:
            f.write(code)
        
        # 编译
        output_file = os.path.join(temp_dir, 'output')
        result = compiler.compile(source_file, output_file)
        
        return result
    finally:
        # 清理(保留输出文件用于测试)
        if not result.success:
            shutil.rmtree(temp_dir)

步骤3: 错误分析

def analyze_errors(compile_result: CompileResult) -> AnalysisReport:
    """
    分析编译错误
    
    1. 解析错误信息
    2. 分类错误
    3. 提取位置信息
    4. 生成修复建议
    """
    analyzer = ErrorAnalyzer()
    report = analyzer.analyze(compile_result.stderr)
    
    # 按严重程度排序
    report.errors.sort(key=lambda e: e.severity, reverse=True)
    
    return report

步骤4: 自动修复

def apply_fixes(code: str, report: AnalysisReport) -> FixResult:
    """
    应用自动修复
    
    1. 应用高优先级修复(头文件)
    2. 应用中优先级修复(命名空间)
    3. 应用低优先级修复(语法错误)
    4. 记录所有修改
    """
    fixer = AutoFixer()
    result = fixer.fix(code, report.errors)
    
    # 验证修复不会引入新问题
    # ...
    
    return result

步骤5: 测试验证

def run_tests(executable: str, config: TestConfig) -> TestResult:
    """
    运行测试
    
    1. 检查可执行文件
    2. 运行程序
    3. 捕获输出
    4. 验证结果
    """
    runner = TestRunner(config)
    result = runner.run_tests(executable)
    
    return result

5. 错误处理系统

5.1 异常层次结构

class CompilerError(Exception):
    """编译器基础异常"""
    pass

class CompilerNotFoundError(CompilerError):
    """编译器未找到"""
    pass

class CompileTimeoutError(CompilerError):
    """编译超时"""
    pass

class MaxIterationsExceeded(CompilerError):
    """超过最大迭代次数"""
    pass

class InvalidStateTransition(CompilerError):
    """无效的状态转换"""
    pass

class FixApplicationError(CompilerError):
    """修复应用失败"""
    pass

5.2 错误恢复策略

class ErrorRecoveryStrategy:
    """
    错误恢复策略
    """
    
    STRATEGIES = {
        'compiler_not_found': {
            'action': 'abort',
            'message': '未找到支持的C++编译器,请安装g++或clang++',
            'suggestion': '运行: apt-get install g++ 或 brew install gcc'
        },
        'compile_timeout': {
            'action': 'retry_with_simple_flags',
            'max_retries': 1,
            'message': '编译超时,尝试简化编译选项'
        },
        'max_iterations': {
            'action': 'report_and_abort',
            'message': '达到最大迭代次数,可能存在复杂的错误',
            'suggestion': '请检查错误报告,手动修复代码'
        },
        'test_failure': {
            'action': 'analyze_and_retry',
            'max_retries': 2,
            'message': '测试失败,分析错误并尝试修复'
        }
    }
    
    def recover(self, error: Exception, context: dict) -> RecoveryResult:
        """执行恢复策略"""
        error_type = type(error).__name__
        strategy = self.STRATEGIES.get(error_type, self.STRATEGIES['default'])
        
        if strategy['action'] == 'abort':
            return RecoveryResult(
                success=False,
                message=strategy['message'],
                suggestion=strategy.get('suggestion')
            )
        elif strategy['action'] == 'retry_with_simple_flags':
            # 尝试简化编译选项
            context['flags'] = ['-std=c++11']
            return RecoveryResult(success=True, context=context)
        
        # ... 更多策略

5.3 错误报告格式

{
  "status": "failed",
  "error": {
    "type": "compile_error",
    "message": "Compilation failed after 10 iterations",
    "details": [
      {
        "iteration": 1,
        "error_count": 5,
        "warning_count": 2,
        "fixed_count": 3,
        "remaining_errors": [
          {
            "line": 15,
            "column": 5,
            "type": "type_mismatch",
            "message": "cannot convert 'const char*' to 'int'",
            "suggestion": "使用 std::stoi() 转换字符串为整数"
          }
        ]
      }
    ]
  },
  "suggestions": [
    "检查类型转换",
    "确保函数参数类型匹配"
  ]
}

6. 自动化修复策略

6.1 头文件自动添加

class HeaderAutoInserter:
    """
    头文件自动添加器
    """
    
    # 符号到头文件的映射
    SYMBOL_HEADER_MAP = {
        # 输入输出
        'cout': '<iostream>',
        'cin': '<iostream>',
        'cerr': '<iostream>',
        'endl': '<iostream>',
        
        # 字符串
        'string': '<string>',
        'stoi': '<string>',
        'stod': '<string>',
        'to_string': '<string>',
        
        # 容器
        'vector': '<vector>',
        'map': '<map>',
        'set': '<set>',
        'unordered_map': '<unordered_map>',
        'unordered_set': '<unordered_set>',
        'array': '<array>',
        'deque': '<deque>',
        'list': '<list>',
        
        # 智能指针
        'shared_ptr': '<memory>',
        'unique_ptr': '<memory>',
        'make_shared': '<memory>',
        'make_unique': '<memory>',
        
        # 算法
        'sort': '<algorithm>',
        'find': '<algorithm>',
        'copy': '<algorithm>',
        'transform': '<algorithm>',
        
        # 数值
        'sqrt': '<cmath>',
        'pow': '<cmath>',
        'sin': '<cmath>',
        'cos': '<cmath>',
        'abs': '<cstdlib>',
        
        # 线程
        'thread': '<thread>',
        'mutex': '<mutex>',
        'lock_guard': '<mutex>',
        
        # 其他
        'function': '<functional>',
        'regex': '<regex>',
        'chrono': '<chrono>',
    }
    
    def detect_missing_headers(self, code: str, 
                               errors: List[CompileError]) -> List[str]:
        """
        检测缺失的头文件
        
        Args:
            code: 源代码
            errors: 错误列表
            
        Returns:
            缺失的头文件列表
        """
        # 从代码中提取使用的符号
        used_symbols = self._extract_symbols(code)
        
        # 从错误中提取未声明的符号
        undeclared_symbols = self._extract_undeclared_symbols(errors)
        
        # 合并并去重
        all_symbols = set(used_symbols) | set(undeclared_symbols)
        
        # 确定需要的头文件
        required_headers = set()
        for symbol in all_symbols:
            if symbol in self.SYMBOL_HEADER_MAP:
                required_headers.add(self.SYMBOL_HEADER_MAP[symbol])
        
        # 排除已有的头文件
        existing_headers = self._extract_existing_headers(code)
        missing_headers = required_headers - existing_headers
        
        return sorted(list(missing_headers))
    
    def insert_headers(self, code: str, headers: List[str]) -> str:
        """
        插入头文件
        
        Args:
            code: 源代码
            headers: 要插入的头文件列表
            
        Returns:
            修改后的代码
        """
        lines = code.split('\n')
        
        # 找到插入位置(在最后一个#include之后)
        insert_pos = 0
        for i, line in enumerate(lines):
            if line.strip().startswith('#include'):
                insert_pos = i + 1
        
        # 生成头文件行
        header_lines = [f'#include {h}' for h in headers]
        
        # 插入
        lines = lines[:insert_pos] + header_lines + lines[insert_pos:]
        
        return '\n'.join(lines)

6.2 命名空间修复

class NamespaceFixer:
    """
    命名空间修复器
    """
    
    # 需要std::前缀的符号
    STD_SYMBOLS = {
        'cout', 'cin', 'cerr', 'endl',
        'string', 'vector', 'map', 'set', 'array',
        'shared_ptr', 'unique_ptr', 'make_shared', 'make_unique',
        'sort', 'find', 'copy', 'transform',
        'min', 'max', 'swap', 'move',
        'thread', 'mutex', 'lock_guard',
        'function', 'regex', 'chrono',
        'stoi', 'stod', 'to_string',
        'begin', 'end', 'size', 'empty',
        # ... 更多
    }
    
    def fix_namespace_issues(self, code: str, 
                            errors: List[CompileError]) -> str:
        """
        修复命名空间问题
        
        Args:
            code: 源代码
            errors: 错误列表
            
        Returns:
            修复后的代码
        """
        lines = code.split('\n')
        
        for error in errors:
            if error.type != ErrorType.UNDECLARED_IDENTIFIER:
                continue
            
            symbol = self._extract_symbol(error.message)
            if symbol not in self.STD_SYMBOLS:
                continue
            
            # 修复该行的命名空间问题
            line_idx = error.line - 1
            lines[line_idx] = self._add_std_prefix(lines[line_idx], symbol)
        
        return '\n'.join(lines)
    
    def _add_std_prefix(self, line: str, symbol: str) -> str:
        """
        在行中添加std::前缀
        
        使用正则表达式精确匹配,避免误修改
        """
        # 匹配独立的符号(不在标识符中间)
        pattern = r'\b(' + symbol + r')\b(?!::)'
        
        def replace(match):
            # 检查前面是否已经有std::
            pos = match.start()
            prefix = line[:pos].rstrip()
            if prefix.endswith('std::') or prefix.endswith('::'):
                return match.group(0)
            return 'std::' + match.group(0)
        
        return re.sub(pattern, replace, line)

6.3 语法错误修复

class SyntaxFixer:
    """
    语法错误修复器
    """
    
    def fix_syntax_errors(self, code: str, 
                         errors: List[CompileError]) -> str:
        """
        修复语法错误
        
        Args:
            code: 源代码
            errors: 错误列表
            
        Returns:
            修复后的代码
        """
        lines = code.split('\n')
        
        for error in errors:
            if error.type == ErrorType.MISSING_SEMICOLON:
                lines = self._fix_missing_semicolon(lines, error)
            elif error.type == ErrorType.UNMATCHED_PARENTHESIS:
                lines = self._fix_unmatched_parenthesis(lines, error)
            elif error.type == ErrorType.UNMATCHED_BRACE:
                lines = self._fix_unmatched_brace(lines, error)
        
        return '\n'.join(lines)
    
    def _fix_missing_semicolon(self, lines: List[str], 
                               error: CompileError) -> List[str]:
        """修复缺失的分号"""
        line_idx = error.line - 1
        line = lines[line_idx]
        
        # 检查是否真的缺少分号
        # 避免在已经有分号的地方添加
        if line.rstrip().endswith(';'):
            return lines
        
        # 检查是否是特殊情况(如预处理指令、注释等)
        stripped = line.strip()
        if (stripped.startswith('#') or 
            stripped.startswith('//') or
            stripped.startswith('/*') or
            stripped.endswith('{') or
            stripped.endswith('}') or
            stripped.endswith(':')):
            return lines
        
        # 添加分号
        lines[line_idx] = line.rstrip() + ';'
        return lines

7. API设计

7.1 REST API设计

编译接口

POST /api/v1/compile
Content-Type: application/json

Request:
{
  "code": "#include <iostream>\nint main() { ... }",
  "options": {
    "compiler": "g++",
    "standard": "c++11",
    "optimization": "O0",
    "warnings": ["all", "extra"],
    "max_iterations": 10,
    "run_tests": true,
    "test_timeout": 10
  }
}

Response:
{
  "status": "success",
  "result": {
    "compilation": {
      "success": true,
      "iterations": 2,
      "warnings": [],
      "errors_fixed": [
        {
          "iteration": 1,
          "line": 5,
          "type": "missing_semicolon",
          "fix": "added semicolon"
        }
      ]
    },
    "testing": {
      "success": true,
      "output": "Hello, World!\n",
      "return_code": 0,
      "duration_ms": 12
    },
    "code": {
      "original": "...",
      "final": "..."
    }
  },
  "statistics": {
    "total_time_ms": 234,
    "compile_time_ms": 150,
    "test_time_ms": 84
  }
}

分析接口

POST /api/v1/analyze
Content-Type: application/json

Request:
{
  "code": "...",
  "compiler_output": "error: ..."
}

Response:
{
  "status": "success",
  "analysis": {
    "error_count": 3,
    "warning_count": 1,
    "errors": [
      {
        "line": 5,
        "column": 10,
        "type": "undeclared_identifier",
        "message": "'cout' was not declared",
        "suggestion": "Add #include <iostream> and use std::cout"
      }
    ],
    "suggestions": [
      "Add missing header files",
      "Use std:: namespace prefix"
    ]
  }
}

7.2 Python API设计

from cpp_compiler_agent import Compiler, CompilerConfig

# 创建编译器实例
config = CompilerConfig(
    standard='c++11',
    max_iterations=10,
    run_tests=True,
    test_timeout=10
)
compiler = Compiler(config)

# 编译代码
result = compiler.compile('''
#include <iostream>
int main() {
    cout << "Hello" << endl;
    return 0;
}
''')

# 检查结果
if result.success:
    print("编译成功!")
    print(f"修复了 {result.fixes_count} 个错误")
    print(f"输出: {result.test_output}")
else:
    print("编译失败!")
    for error in result.remaining_errors:
        print(f"  第{error.line}行: {error.message}")

# 获取修复后的代码
fixed_code = result.final_code

7.3 CLI设计

# 基本编译
cpp-compiler compile input.cpp -o output

# 详细模式
cpp-compiler compile input.cpp -o output --verbose

# 指定编译器
cpp-compiler compile input.cpp -o output --compiler clang++

# 禁用测试
cpp-compiler compile input.cpp -o output --no-test

# 设置最大迭代次数
cpp-compiler compile input.cpp -o output --max-iterations 5

# 输出JSON格式
cpp-compiler compile input.cpp -o output --format json

# 仅分析错误
cpp-compiler analyze input.cpp --errors-file errors.log

# 自动修复
cpp-compiler fix input.cpp -o fixed.cpp

8. 脚本工具设计

8.1 compile.sh 详细设计

#!/bin/bash
# compile.sh - C++11编译脚本

# 默认配置
COMPILER="g++"
CXX_STD="-std=c++11"
WARNINGS="-Wall -Wextra -Wpedantic"
DEBUG="-g"
OPTIMIZATION="-O0"
TIMEOUT=30

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 函数:检测编译器
detect_compiler() {
    for cmd in g++ clang++; do
        if command -v $cmd &> /dev/null; then
            echo $cmd
            return 0
        fi
    done
    return 1
}

# 函数:检查C++11支持
check_cpp11_support() {
    local compiler=$1
    local temp_file=$(mktemp --suffix=.cpp)
    
    echo "int main() { return 0; }" > $temp_file
    
    if $compiler -std=c++11 -o /dev/null $temp_file 2>/dev/null; then
        rm -f $temp_file
        return 0
    fi
    
    rm -f $temp_file
    return 1
}

# 函数:编译代码
compile() {
    local source=$1
    local output=$2
    local extra_flags=$3
    
    # 构建命令
    local cmd="$COMPILER $CXX_STD $WARNINGS $DEBUG $OPTIMIZATION $extra_flags -o $output $source"
    
    # 执行编译
    local output_file=$(mktemp)
    local error_file=$(mktemp)
    
    timeout $TIMEOUT bash -c "$cmd" > $output_file 2> $error_file
    local exit_code=$?
    
    # 处理结果
    if [ $exit_code -eq 0 ]; then
        echo -e "${GREEN}✓ 编译成功${NC}"
        return 0
    elif [ $exit_code -eq 124 ]; then
        echo -e "${RED}✗ 编译超时${NC}"
        return 1
    else
        echo -e "${RED}✗ 编译失败${NC}"
        cat $error_file
        return 1
    fi
}

# 主函数
main() {
    local source_file=""
    local output_file=""
    local extra_flags=""
    
    # 解析参数
    while [ $# -gt 0 ]; do
        case $1 in
            -o)
                output_file=$2
                shift 2
                ;;
            -*)
                extra_flags="$extra_flags $1"
                shift
                ;;
            *)
                source_file=$1
                shift
                ;;
        esac
    done
    
    # 验证参数
    if [ -z "$source_file" ]; then
        echo "错误: 未指定源文件"
        exit 1
    fi
    
    # 检测编译器
    COMPILER=$(detect_compiler)
    if [ -z "$COMPILER" ]; then
        echo "错误: 未找到支持的编译器"
        exit 1
    fi
    
    # 设置默认输出文件
    if [ -z "$output_file" ]; then
        output_file="${source_file%.*}"
    fi
    
    # 执行编译
    compile "$source_file" "$output_file" "$extra_flags"
}

main "$@"

8.2 analyze_errors.py 详细设计

#!/usr/bin/env python3
"""
analyze_errors.py - 编译错误分析器

功能:
1. 解析编译器输出
2. 分类错误类型
3. 提取错误位置
4. 生成修复建议
5. 输出统计报告
"""

import re
import sys
import json
from typing import List, Dict, Optional
from dataclasses import dataclass, asdict
from enum import Enum

class ErrorType(Enum):
    """错误类型"""
    SYNTAX_ERROR = "syntax_error"
    DECLARATION_ERROR = "declaration_error"
    TYPE_ERROR = "type_error"
    LINKER_ERROR = "linker_error"
    WARNING = "warning"
    OTHER = "other"

@dataclass
class CompileError:
    """编译错误"""
    file: str
    line: int
    column: int
    type: ErrorType
    message: str
    suggestion: Optional[str] = None

class ErrorAnalyzer:
    """错误分析器"""
    
    def __init__(self):
        # 初始化错误模式
        self.patterns = self._init_patterns()
    
    def _init_patterns(self) -> Dict:
        """初始化错误模式"""
        return {
            'missing_semicolon': {
                'regex': r"expected ';' before '([^']+)'",
                'type': ErrorType.SYNTAX_ERROR,
                'suggest': lambda m: f"在 '{m.group(1)}' 前添加分号"
            },
            'undeclared': {
                'regex': r"'([^']+)' was not declared",
                'type': ErrorType.DECLARATION_ERROR,
                'suggest': lambda m: self._suggest_declaration(m.group(1))
            },
            # ... 更多模式
        }
    
    def analyze(self, output: str) -> Dict:
        """分析编译输出"""
        errors = []
        warnings = []
        
        for line in output.split('\n'):
            parsed = self._parse_line(line)
            if parsed:
                if parsed.type == ErrorType.WARNING:
                    warnings.append(parsed)
                else:
                    errors.append(parsed)
        
        return {
            'errors': [asdict(e) for e in errors],
            'warnings': [asdict(w) for w in warnings],
            'statistics': self._generate_stats(errors, warnings),
            'suggestions': self._generate_suggestions(errors)
        }
    
    def _parse_line(self, line: str) -> Optional[CompileError]:
        """解析单行错误"""
        # 匹配: file:line:column: error: message
        match = re.match(r'([^:]+):(\d+):(?:(\d+):)? (error|warning): (.+)', line)
        
        if not match:
            return None
        
        file, line_num, col, level, message = match.groups()
        
        # 确定错误类型
        error_type = ErrorType.OTHER
        suggestion = None
        
        for pattern_name, pattern_info in self.patterns.items():
            if re.search(pattern_info['regex'], message):
                error_type = pattern_info['type']
                m = re.search(pattern_info['regex'], message)
                suggestion = pattern_info['suggest'](m)
                break
        
        if level == 'warning':
            error_type = ErrorType.WARNING
        
        return CompileError(
            file=file,
            line=int(line_num),
            column=int(col) if col else 0,
            type=error_type,
            message=message,
            suggestion=suggestion
        )

def main():
    """主函数"""
    if len(sys.argv) > 1:
        with open(sys.argv[1], 'r') as f:
            output = f.read()
    else:
        output = sys.stdin.read()
    
    analyzer = ErrorAnalyzer()
    result = analyzer.analyze(output)
    
    if '--json' in sys.argv:
        print(json.dumps(result, indent=2))
    else:
        print_report(result)

def print_report(result: Dict):
    """打印文本报告"""
    print("=" * 60)
    print("C++11 编译错误分析报告")
    print("=" * 60)
    print(f"\n错误数: {len(result['errors'])}")
    print(f"警告数: {len(result['warnings'])}")
    
    if result['errors']:
        print("\n错误列表:")
        for i, error in enumerate(result['errors'], 1):
            print(f"\n{i}. 第{error['line']}行: {error['message']}")
            if error['suggestion']:
                print(f"   建议: {error['suggestion']}")
    
    if result['suggestions']:
        print("\n修复建议:")
        for i, suggestion in enumerate(result['suggestions'], 1):
            print(f"{i}. {suggestion}")

if __name__ == '__main__':
    main()

9. 测试策略

9.1 单元测试

import unittest
from cpp_compiler_agent import ErrorAnalyzer, AutoFixer

class TestErrorAnalyzer(unittest.TestCase):
    """错误分析器测试"""
    
    def setUp(self):
        self.analyzer = ErrorAnalyzer()
    
    def test_missing_semicolon(self):
        """测试缺失分号检测"""
        output = "test.cpp:5:5: error: expected ';' before 'return'"
        result = self.analyzer.analyze(output)
        
        self.assertEqual(len(result['errors']), 1)
        self.assertEqual(result['errors'][0]['line'], 5)
        self.assertIn('分号', result['errors'][0]['suggestion'])
    
    def test_undeclared_identifier(self):
        """测试未声明标识符检测"""
        output = "test.cpp:10:5: error: 'cout' was not declared"
        result = self.analyzer.analyze(output)
        
        self.assertEqual(len(result['errors']), 1)
        self.assertIn('iostream', result['errors'][0]['suggestion'])

class TestAutoFixer(unittest.TestCase):
    """自动修复器测试"""
    
    def setUp(self):
        self.fixer = AutoFixer()
    
    def test_fix_missing_semicolon(self):
        """测试修复缺失分号"""
        code = "int x = 5"
        errors = [CompileError(line=1, type=ErrorType.MISSING_SEMICOLON)]
        
        result = self.fixer.fix(code, errors)
        
        self.assertEqual(result.fixed_code, "int x = 5;")
    
    def test_add_std_prefix(self):
        """测试添加std::前缀"""
        code = "cout << \"Hello\" << endl;"
        errors = [CompileError(line=1, message="'cout' was not declared")]
        
        result = self.fixer.fix(code, errors)
        
        self.assertIn("std::cout", result.fixed_code)
        self.assertIn("std::endl", result.fixed_code)

if __name__ == '__main__':
    unittest.main()

9.2 集成测试

class IntegrationTest(unittest.TestCase):
    """集成测试"""
    
    def test_full_compile_cycle(self):
        """测试完整编译周期"""
        code = '''
        #include <iostream>
        int main() {
            cout << "Hello" << endl;
            return 0;
        }
        '''
        
        compiler = Compiler()
        result = compiler.compile(code)
        
        self.assertTrue(result.success)
        self.assertEqual(result.iterations, 1)
        self.assertIn("std::cout", result.final_code)
    
    def test_complex_errors(self):
        """测试复杂错误场景"""
        code = '''
        int main() {
            vector<int> v = {1, 2, 3};
            for (auto x : v) {
                cout << x << endl;
            }
            return 0;
        }
        '''
        
        compiler = Compiler()
        result = compiler.compile(code)
        
        self.assertTrue(result.success)
        self.assertIn("#include <vector>", result.final_code)
        self.assertIn("#include <iostream>", result.final_code)

9.3 性能测试

import time
import statistics

class PerformanceTest:
    """性能测试"""
    
    def test_compilation_speed(self):
        """测试编译速度"""
        codes = [generate_test_code() for _ in range(100)]
        
        times = []
        for code in codes:
            start = time.time()
            compiler.compile(code)
            times.append(time.time() - start)
        
        print(f"平均编译时间: {statistics.mean(times):.3f}s")
        print(f"中位数: {statistics.median(times):.3f}s")
        print(f"标准差: {statistics.stdev(times):.3f}s")
    
    def test_fix_speed(self):
        """测试修复速度"""
        # 测试不同错误数量的修复速度
        for error_count in [1, 5, 10, 20]:
            code = generate_code_with_errors(error_count)
            
            start = time.time()
            result = fixer.fix(code)
            elapsed = time.time() - start
            
            print(f"{error_count}个错误修复时间: {elapsed:.3f}s")

10. 性能优化

10.1 编译缓存

class CompileCache:
    """
    编译缓存
    
    缓存编译结果,避免重复编译相同代码
    """
    
    def __init__(self, max_size: int = 100):
        self.cache = {}
        self.max_size = max_size
        self.hits = 0
        self.misses = 0
    
    def get(self, code: str) -> Optional[CompileResult]:
        """获取缓存结果"""
        key = self._hash_code(code)
        if key in self.cache:
            self.hits += 1
            return self.cache[key]
        self.misses += 1
        return None
    
    def set(self, code: str, result: CompileResult):
        """设置缓存"""
        if len(self.cache) >= self.max_size:
            self._evict_oldest()
        
        key = self._hash_code(code)
        self.cache[key] = {
            'result': result,
            'timestamp': time.time()
        }
    
    def _hash_code(self, code: str) -> str:
        """计算代码哈希"""
        import hashlib
        return hashlib.md5(code.encode()).hexdigest()
    
    def _evict_oldest(self):
        """淘汰最旧的缓存"""
        oldest_key = min(
            self.cache.keys(),
            key=lambda k: self.cache[k]['timestamp']
        )
        del self.cache[oldest_key]
    
    def get_stats(self) -> dict:
        """获取缓存统计"""
        total = self.hits + self.misses
        hit_rate = self.hits / total if total > 0 else 0
        return {
            'hits': self.hits,
            'misses': self.misses,
            'hit_rate': hit_rate,
            'size': len(self.cache)
        }

10.2 并行处理

from concurrent.futures import ThreadPoolExecutor, as_completed

class ParallelCompiler:
    """
    并行编译器
    
    支持并行编译多个文件
    """
    
    def __init__(self, max_workers: int = 4):
        self.executor = ThreadPoolExecutor(max_workers=max_workers)
    
    def compile_multiple(self, codes: List[str]) -> List[CompileResult]:
        """并行编译多个代码"""
        futures = {
            self.executor.submit(self._compile_single, code): i
            for i, code in enumerate(codes)
        }
        
        results = [None] * len(codes)
        for future in as_completed(futures):
            idx = futures[future]
            results[idx] = future.result()
        
        return results

10.3 增量编译

class IncrementalCompiler:
    """
    增量编译器
    
    只重新编译修改过的部分
    """
    
    def __init__(self):
        self.ast_cache = {}
        self.object_cache = {}
    
    def compile(self, code: str) -> CompileResult:
        """增量编译"""
        # 解析AST
        new_ast = self._parse_ast(code)
        
        # 检查是否完全相同
        if self._ast_equal(new_ast, self.ast_cache.get('current')):
            return self.object_cache.get('current')
        
        # 找出修改的部分
        diff = self._find_diff(new_ast, self.ast_cache.get('current'))
        
        # 只重新编译修改的部分
        # ...
        
        # 更新缓存
        self.ast_cache['current'] = new_ast

11. 安全考虑

11.1 代码注入防护

class SecurityChecker:
    """
    安全检查器
    
    检测恶意代码
    """
    
    FORBIDDEN_INCLUDES = [
        '<unistd.h>',  # 系统调用
        '<sys/socket.h>',  # 网络
        '<dlfcn.h>',  # 动态加载
    ]
    
    FORBIDDEN_FUNCTIONS = [
        'system', 'popen', 'exec',
        'fork', 'clone',
        'socket', 'connect',
    ]
    
    def check_code(self, code: str) -> SecurityReport:
        """检查代码安全性"""
        issues = []
        
        # 检查禁用的头文件
        for header in self.FORBIDDEN_INCLUDES:
            if header in code:
                issues.append(f"禁止的头文件: {header}")
        
        # 检查禁用的函数
        for func in self.FORBIDDEN_FUNCTIONS:
            if re.search(r'\b' + func + r'\s*\(', code):
                issues.append(f"禁止的函数: {func}")
        
        return SecurityReport(
            safe=(len(issues) == 0),
            issues=issues
        )

11.2 资源限制

class ResourceLimiter:
    """
    资源限制器
    
    限制编译器使用的资源
    """
    
    def __init__(self, config: ResourceConfig):
        self.config = config
    
    def limit_process(self):
        """限制当前进程资源"""
        import resource
        
        # 限制CPU时间
        resource.setrlimit(
            resource.RLIMIT_CPU,
            (self.config.max_cpu_time, self.config.max_cpu_time + 1)
        )
        
        # 限制内存
        resource.setrlimit(
            resource.RLIMIT_AS,
            (self.config.max_memory, self.config.max_memory)
        )
        
        # 限制文件大小
        resource.setrlimit(
            resource.RLIMIT_FSIZE,
            (self.config.max_file_size, self.config.max_file_size)
        )
    
    def run_with_limits(self, func, *args, **kwargs):
        """在资源限制下运行函数"""
        # 创建子进程
        pid = os.fork()
        
        if pid == 0:
            # 子进程:设置资源限制并执行
            self.limit_process()
            result = func(*args, **kwargs)
            os._exit(0 if result.success else 1)
        else:
            # 父进程:等待子进程
            _, status = os.waitpid(pid, 0)
            return status == 0

11.3 沙箱隔离

class Sandbox:
    """
    沙箱环境
    
    在隔离环境中编译和运行代码
    """
    
    def __init__(self):
        self.temp_dir = None
    
    def __enter__(self):
        """进入沙箱"""
        # 创建临时目录
        self.temp_dir = tempfile.mkdtemp(prefix='sandbox_')
        
        # 设置权限
        os.chmod(self.temp_dir, 0o700)
        
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """退出沙箱"""
        # 清理所有文件
        if self.temp_dir:
            shutil.rmtree(self.temp_dir, ignore_errors=True)
    
    def compile(self, code: str) -> CompileResult:
        """在沙箱中编译"""
        with self:
            # 写入源文件
            source_file = os.path.join(self.temp_dir, 'source.cpp')
            with open(source_file, 'w') as f:
                f.write(code)
            
            # 编译
            output_file = os.path.join(self.temp_dir, 'output')
            # ...

12. 部署方案

12.1 Docker部署

# Dockerfile
FROM ubuntu:22.04

# 安装依赖
RUN apt-get update && apt-get install -y \
    g++ \
    clang \
    python3 \
    python3-pip \
    && rm -rf /var/lib/apt/lists/*

# 安装Python依赖
COPY requirements.txt /app/
RUN pip3 install -r /app/requirements.txt

# 复制代码
COPY . /app/

# 设置工作目录
WORKDIR /app

# 暴露端口
EXPOSE 8080

# 启动服务
CMD ["python3", "server.py"]

12.2 Kubernetes部署

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cpp-compiler-agent
spec:
  replicas: 3
  selector:
    matchLabels:
      app: cpp-compiler-agent
  template:
    metadata:
      labels:
        app: cpp-compiler-agent
    spec:
      containers:
      - name: compiler
        image: cpp-compiler-agent:latest
        ports:
        - containerPort: 8080
        resources:
          limits:
            cpu: "2"
            memory: "4Gi"
          requests:
            cpu: "1"
            memory: "2Gi"
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5

12.3 配置管理

# config.yaml
compiler:
  default: g++
  timeout: 30
  max_iterations: 10
  
  flags:
    standard: c++11
    warnings:
      - Wall
      - Wextra
      - Wpedantic
    optimization: O0

testing:
  enabled: true
  timeout: 10
  max_output_size: 1048576  # 1MB

security:
  sandbox_enabled: true
  max_file_size: 10485760  # 10MB
  max_memory: 1073741824  # 1GB
  max_cpu_time: 60

logging:
  level: INFO
  file: /var/log/compiler.log
  max_size: 10485760
  backup_count: 5

13. 未来扩展

13.1 C++14/17/20支持

class ModernCppCompiler(Compiler):
    """
    现代C++编译器
    
    支持C++14/17/20标准
    """
    
    SUPPORTED_STANDARDS = ['c++11', 'c++14', 'c++17', 'c++20']
    
    def compile(self, code: str, standard: str = 'c++11') -> CompileResult:
        """
        编译代码
        
        Args:
            code: 源代码
            standard: C++标准 ('c++11', 'c++14', 'c++17', 'c++20')
        """
        # 检测代码使用的C++特性
        detected_standard = self._detect_standard(code)
        
        # 使用更高的标准
        use_standard = max(standard, detected_standard, key=self._standard_priority)
        
        # 使用对应的编译选项
        flags = [f'-std={use_standard}']
        
        # ...

13.2 跨平台支持

class CrossPlatformCompiler:
    """
    跨平台编译器
    
    支持不同平台的编译
    """
    
    PLATFORMS = {
        'linux': {
            'compiler': 'g++',
            'flags': ['-std=c++11', '-pthread'],
            'extension': ''
        },
        'windows': {
            'compiler': 'g++',
            'flags': ['-std=c++11', '-lws2_32'],
            'extension': '.exe'
        },
        'macos': {
            'compiler': 'clang++',
            'flags': ['-std=c++11', '-stdlib=libc++'],
            'extension': ''
        }
    }
    
    def compile_for_platform(self, code: str, platform: str) -> CompileResult:
        """为特定平台编译"""
        config = self.PLATFORMS[platform]
        # ...

13.3 静态分析集成

class StaticAnalyzer:
    """
    静态分析器
    
    集成静态分析工具
    """
    
    TOOLS = ['cppcheck', 'clang-tidy', 'scan-build']
    
    def analyze(self, code: str) -> AnalysisReport:
        """
        执行静态分析
        
        Returns:
            包含潜在问题的分析报告
        """
        results = []
        
        for tool in self.TOOLS:
            if self._is_tool_available(tool):
                result = self._run_tool(tool, code)
                results.append(result)
        
        return self._merge_results(results)

13.4 AI辅助优化

class AIOptimizer:
    """
    AI优化器
    
    使用LLM进行代码优化建议
    """
    
    def optimize(self, code: str) -> OptimizationReport:
        """
        分析代码并提供优化建议
        
        Returns:
            优化建议报告
        """
        # 分析代码结构
        structure = self._analyze_structure(code)
        
        # 识别优化机会
        opportunities = self._identify_opportunities(structure)
        
        # 使用LLM生成建议
        suggestions = []
        for opp in opportunities:
            suggestion = self._llm_optimize(opp)
            suggestions.append(suggestion)
        
        return OptimizationReport(
            original_code=code,
            suggestions=suggestions,
            estimated_improvement=self._estimate_improvement(suggestions)
        )

附录

A. 错误代码表

错误代码 类型 描述
E001 语法 缺失分号
E002 语法 括号不匹配
E003 声明 未声明的标识符
E004 声明 重复定义
E005 类型 类型不匹配
E006 类型 无效转换
E007 链接 未定义引用
E008 链接 多重定义
E009 模板 模板参数错误
E010 其他 编译超时

B. 配置选项参考

选项 类型 默认值 描述
compiler string auto 编译器选择
standard string c++11 C++标准
timeout int 30 编译超时(秒)
max_iterations int 10 最大迭代次数
warnings list [all, extra] 启用的警告
optimization string O0 优化级别
run_tests bool true 是否运行测试
test_timeout int 10 测试超时(秒)
sandbox bool true 是否启用沙箱

C. 性能基准

场景 平均时间 内存使用
简单代码(无错误) 50ms 10MB
简单代码(1-2错误) 200ms 15MB
中等代码(5-10错误) 1s 30MB
复杂代码(10+错误) 5s 50MB

D. 参考资料

  1. C++11标准文档

  2. GCC手册

  3. Clang文档

  4. CppReference

  5. C++ Core Guidelines


文档版本: 1.0.0 最后更新: 2026-03-31

最近更新: 2026年4月1日 11:33:24
浏览: 14

[[total]] 条评论

添加评论
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]楼
  2. 点击加载更多……
  3. 添加评论