跳转到内容

代码质量

OpenOS 使用严格的代码质量标准来确保内核的正确性和可靠性。

kernel/src/main.rs
#![warn(missing_docs)]
#![warn(clippy::all, clippy::pedantic, clippy::nursery)]
#![allow(
clippy::module_inception,
dead_code,
unused_imports,
unused_variables,
clippy::missing_const_for_fn,
clippy::used_underscore_items
)]
规则说明
clippy::all所有默认警告
clippy::pedantic严格的代码风格
clippy::nursery实验性规则(可能变化)
missing_docs要求文档注释
dead_code允许未使用的代码(脚手架)
unused_imports允许未使用的导入
unused_variables允许未使用的变量
rustfmt.toml
edition = "2021"
max_width = 100
tab_spaces = 4
use_field_init_shorthand = true
use_try_shorthand = true
group_imports = "StdExternalCrate"
规则说明
max_width最大行宽 100 字符
tab_spaces使用 4 个空格缩进
group_imports导入分组:标准库、外部 crate、本地模块
/// 初始化堆分配器
///
/// # Arguments
///
/// * `heap_start` - 堆起始地址
/// * `heap_size` - 堆大小(字节)
///
/// # Safety
///
/// 此函数必须在启用分页后调用。
///
/// # Examples
///
/// ```rust
/// init_heap(0x4444_4444_0000, 100 * 1024);
/// ```
pub unsafe fn init_heap(heap_start: usize, heap_size: usize) {
// ...
}
//! # 内存管理模块
//!
//! 此模块提供内核的内存管理功能,包括:
//! - 堆分配器
//! - 帧分配器
//! - 虚拟内存管理
//!
//! ## Architecture
//!
//! 内存管理采用分层设计:
//! 1. 物理帧分配器 - 管理物理内存帧
//! 2. 堆分配器 - 管理内核堆
//! 3. 虚拟内存管理 - 管理页表和地址空间
/// 任务 ID
///
/// 每个任务在创建时分配一个唯一的 ID。
/// ID 是原子递增的 64 位整数。
///
/// # Examples
///
/// ```rust
/// let id = TaskId::new();
/// assert!(id.as_u64() > 0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct TaskId(u64);
/// 操作结果
pub type Result<T> = core::result::Result<T, Error>;
/// 错误类型
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
/// 无效参数
InvalidArgument,
/// 资源不足
OutOfMemory,
/// 权限不足
PermissionDenied,
/// 资源忙
Busy,
/// 未找到
NotFound,
/// 超时
Timeout,
/// 内部错误
Internal,
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::InvalidArgument => write!(f, "Invalid argument"),
Error::OutOfMemory => write!(f, "Out of memory"),
Error::PermissionDenied => write!(f, "Permission denied"),
Error::Busy => write!(f, "Resource busy"),
Error::NotFound => write!(f, "Not found"),
Error::Timeout => write!(f, "Timeout"),
Error::Internal => write!(f, "Internal error"),
}
}
}
fn read_file(path: &str) -> Result<Vec<u8>> {
let handle = open_file(path)?;
let data = read_from_handle(handle)?;
close_handle(handle)?;
Ok(data)
}
/// 安全地读取端口
///
/// # Safety
///
/// 调用者必须确保:
/// - 端口地址有效
/// - 端口未被其他代码使用
pub unsafe fn port_read(port: u16) -> u8 {
let mut port = Port::new(port);
port.read()
}
// 明确标记 unsafe 调用
let value = unsafe { port_read(0x60) };
fn access_buffer(buffer: &[u8], index: usize) -> Option<u8> {
if index < buffer.len() {
Some(buffer[index])
} else {
None
}
}
fn add_sizes(a: usize, b: usize) -> Option<usize> {
a.checked_add(b)
}
fn multiply_sizes(a: usize, b: usize) -> Option<usize> {
a.checked_mul(b)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_task_id_generation() {
let id1 = TaskId::new();
let id2 = TaskId::new();
assert_ne!(id1, id2);
assert!(id2.as_u64() > id1.as_u64());
}
#[test]
fn test_error_display() {
let error = Error::OutOfMemory;
assert_eq!(format!("{}", error), "Out of memory");
}
}
tests/integration_test.rs
#[test]
fn test_memory_allocation() {
init_heap(0x100000, 100 * 1024);
let x = Box::new(42);
assert_eq!(*x, 42);
let v = vec![1, 2, 3, 4, 5];
assert_eq!(v.len(), 5);
}
  • 代码是否正确实现了需求?
  • 是否处理了所有错误情况?
  • 是否有边界条件未处理?
  • 是否有内存泄漏?
  • 是否有资源泄漏?
  • unsafe 使用是否必要且安全?
  • 是否进行了边界检查?
  • 是否检查了整数溢出?
  • 是否验证了用户输入?
  • 是否检查了权限?
  • 是否符合 rustfmt 配置?
  • 是否通过了 clippy 检查?
  • 是否有足够的文档注释?
  • 命名是否清晰?
  • 代码是否易于理解?
  • 是否有不必要的分配?
  • 是否有不必要的复制?
  • 是否可以使用引用而非所有权?
  • 是否有可以优化的算法?
Terminal window
# 完整检查
make check
# 等同于:
cargo fmt --check
cargo clippy -- -D warnings
cargo build
.git/hooks/pre-commit
#!/bin/bash
# 检查格式
if ! cargo fmt --check; then
echo "Code formatting check failed"
exit 1
fi
# 检查 clippy
if ! cargo clippy -- -D warnings; then
echo "Clippy check failed"
exit 1
fi
# 运行测试
if ! cargo test; then
echo "Tests failed"
exit 1
fi

问题:unused variable 警告

// 使用下划线前缀
fn handler(_stack_frame: InterruptStackFrame) {
// ...
}

问题:dead code 警告

// 添加 #[allow(dead_code)]
#[allow(dead_code)]
fn future_function() {
// ...
}

问题:needless_return

// 不推荐
fn get_value() -> i32 {
return 42;
}
// 推荐
fn get_value() -> i32 {
42
}

问题:redundant_clone

// 不推荐
let s = String::from("hello");
let s2 = s.clone();
// 推荐
let s = String::from("hello");
let s2 = s;