NAC_Blockchain/cnnl-compiler/src/metadata/mod.rs

83 lines
2.5 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 元数据导出模块
//!
//! 导出条款依赖图、复杂度指标等
use serde::{Deserialize, Serialize};
/// 条款元数据
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClauseMetadata {
pub id: String,
pub level: String,
pub title: String,
pub parameter_count: usize,
pub predicate_count: usize,
pub obligation_count: usize,
pub dependencies: Vec<String>,
pub complexity: ComplexityMetrics,
}
/// 复杂度指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityMetrics {
/// McCabe复杂度
pub cyclomatic_complexity: usize,
/// 条款耦合度
pub coupling: usize,
/// 条款内聚度
pub cohesion: f64,
}
/// 元数据导出器
pub struct MetadataExporter;
impl MetadataExporter {
pub fn new() -> Self {
Self
}
pub fn export(&self, ast: &crate::parser::Program) -> Result<Vec<ClauseMetadata>, String> {
let mut metadata = Vec::new();
for clause in &ast.clauses {
metadata.push(ClauseMetadata {
id: clause.id.clone(),
level: clause.level.to_string(),
title: clause.title.clone(),
parameter_count: clause.parameters.len(),
predicate_count: clause.predicates.len(),
obligation_count: clause.obligations.len(),
dependencies: clause.depends_on.clone(),
complexity: ComplexityMetrics {
// 计算McCabe循环复杂度
// 公式M = E - N + 2P
// E = 边数(决策点)
// N = 节点数(语句数)
// P = 连通分量数通常为1
// 简化计算1 + 谓词数 + 义务数
cyclomatic_complexity: 1 + clause.predicates.len() + clause.obligations.len(),
// 耦合度:依赖的条款数
coupling: clause.depends_on.len(),
// 内聚度:根据参数、谓词、义务的关联性计算
// 简化版本:如果有参数且有义务,认为内聚度较高
cohesion: if clause.parameters.is_empty() || clause.obligations.is_empty() {
0.5
} else {
1.0
},
},
});
}
Ok(metadata)
}
}
impl Default for MetadataExporter {
fn default() -> Self {
Self::new()
}
}