code-simplifier
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRTK Code Simplifier
RTK代码简化工具
Review and simplify Rust code in RTK while respecting the project's constraints.
在遵循项目约束的前提下,审查并简化RTK中的Rust代码。
Constraints (never simplify away)
约束条件(绝不能简化掉)
- regex — cannot be moved inside functions even if "simpler"
lazy_static! - on every
.context()— verbose but mandatory? - Fallback to raw command — never remove even if it looks like dead code
- Exit code propagation — never simplify to
Ok(()) - — never remove test modules
#[cfg(test)] mod tests
- 正则表达式——即使看起来“更简单”,也不能移到函数内部
lazy_static! - 每个都要搭配
?——虽然冗余但为强制性要求.context() - 回退到原始命令——即使看起来像死代码也绝不能移除
- 退出码传播——绝不能简化为
Ok(()) - ——绝不能移除测试模块
#[cfg(test)] mod tests
Simplification Patterns
简化模式
1. Iterator chains over manual loops
1. 用迭代器链替代手动循环
rust
// ❌ Verbose
let mut result = Vec::new();
for line in input.lines() {
let trimmed = line.trim();
if !trimmed.is_empty() && trimmed.starts_with("error") {
result.push(trimmed.to_string());
}
}
// ✅ Idiomatic
let result: Vec<String> = input.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty() && l.starts_with("error"))
.map(str::to_string)
.collect();rust
// ❌ 冗余写法
let mut result = Vec::new();
for line in input.lines() {
let trimmed = line.trim();
if !trimmed.is_empty() && trimmed.starts_with("error") {
result.push(trimmed.to_string());
}
}
// ✅ 惯用写法
let result: Vec<String> = input.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty() && l.starts_with("error"))
.map(str::to_string)
.collect();2. String building
2. 字符串构建
rust
// ❌ Verbose push loop
let mut out = String::new();
for (i, line) in lines.iter().enumerate() {
out.push_str(line);
if i < lines.len() - 1 {
out.push('\n');
}
}
// ✅ join
let out = lines.join("\n");rust
// ❌ 冗余的push循环
let mut out = String::new();
for (i, line) in lines.iter().enumerate() {
out.push_str(line);
if i < lines.len() - 1 {
out.push('\n');
}
}
// ✅ 使用join
let out = lines.join("\n");3. Option/Result chaining
3. Option/Result链式调用
rust
// ❌ Nested match
let result = match maybe_value {
Some(v) => match transform(v) {
Ok(r) => r,
Err(_) => default,
},
None => default,
};
// ✅ Chained
let result = maybe_value
.and_then(|v| transform(v).ok())
.unwrap_or(default);rust
// ❌ 嵌套match
let result = match maybe_value {
Some(v) => match transform(v) {
Ok(r) => r,
Err(_) => default,
},
None => default,
};
// ✅ 链式调用
let result = maybe_value
.and_then(|v| transform(v).ok())
.unwrap_or(default);4. Struct destructuring
4. 结构体解构
rust
// ❌ Repeated field access
fn process(args: &MyArgs) -> String {
format!("{} {}", args.command, args.subcommand)
}
// ✅ Destructure
fn process(&MyArgs { ref command, ref subcommand, .. }: &MyArgs) -> String {
format!("{} {}", command, subcommand)
}rust
// ❌ 重复的字段访问
fn process(args: &MyArgs) -> String {
format!("{} {}", args.command, args.subcommand)
}
// ✅ 解构写法
fn process(&MyArgs { ref command, ref subcommand, .. }: &MyArgs) -> String {
format!("{} {}", command, subcommand)
}5. Early returns over nesting
5. 提前返回替代嵌套判断
rust
// ❌ Deeply nested
fn filter(input: &str) -> Option<String> {
if !input.is_empty() {
if let Some(line) = input.lines().next() {
if line.starts_with("error") {
return Some(line.to_string());
}
}
}
None
}
// ✅ Early return
fn filter(input: &str) -> Option<String> {
if input.is_empty() { return None; }
let line = input.lines().next()?;
if !line.starts_with("error") { return None; }
Some(line.to_string())
}rust
// ❌ 深层嵌套
fn filter(input: &str) -> Option<String> {
if !input.is_empty() {
if let Some(line) = input.lines().next() {
if line.starts_with("error") {
return Some(line.to_string());
}
}
}
None
}
// ✅ 提前返回
fn filter(input: &str) -> Option<String> {
if input.is_empty() { return None; }
let line = input.lines().next()?;
if !line.starts_with("error") { return None; }
Some(line.to_string())
}6. Avoid redundant clones
6. 避免冗余克隆
rust
// ❌ Unnecessary clone
fn filter_output(input: &str) -> String {
let s = input.to_string(); // Pointless clone
s.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}
// ✅ Work with &str
fn filter_output(input: &str) -> String {
input.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}rust
// ❌ 不必要的clone
fn filter_output(input: &str) -> String {
let s = input.to_string(); // 无意义的克隆
s.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}
// ✅ 使用&str处理
fn filter_output(input: &str) -> String {
input.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}7. Use if let
for single-variant match
if let7. 对单变体匹配使用if let
if letrust
// ❌ Full match for one variant
match output {
Ok(s) => process(&s),
Err(_) => {},
}
// ✅ if let (but still handle errors in RTK — don't silently drop)
if let Ok(s) = output {
process(&s);
}
// Note: in RTK filters, always handle Err with eprintln! + fallbackrust
// ❌ 针对单个变体使用完整match
match output {
Ok(s) => process(&s),
Err(_) => {},
}
// ✅ 使用if let(但在RTK中仍需处理错误——不要静默忽略)
if let Ok(s) = output {
process(&s);
}
// 注意:在RTK过滤器中,必须用eprintln! + 回退来处理ErrRTK-Specific Checks
RTK专属检查
Run these after simplification:
bash
undefined简化完成后运行以下检查:
bash
undefinedVerify no regressions
验证无回归问题
cargo fmt --all && cargo clippy --all-targets && cargo test
cargo fmt --all && cargo clippy --all-targets && cargo test
Verify no new regex in functions
验证函数中无新增正则表达式
grep -n "Regex::new" src/<file>.rs
grep -n "Regex::new" src/<file>.rs
All should be inside lazy_static! blocks
所有正则表达式都应在lazy_static!块内
Verify no new unwrap in production
验证生产代码中无新增unwrap
grep -n ".unwrap()" src/<file>.rs
grep -n ".unwrap()" src/<file>.rs
Should only appear inside #[cfg(test)] blocks
仅应出现在#[cfg(test)]块内
undefinedundefinedWhat NOT to Simplify
不能简化的内容
- — the
lazy_static! { static ref RE: Regex = Regex::new(...).unwrap(); }here is acceptable, it's init-time.unwrap() - chains — verbose but required
.context("description")? - The fallback match arm — looks redundant but is the safety net
Err(e) => { eprintln!(...); raw_output } - at end of run() — looks like it could be
std::process::exit(code)but it isn'tOk(())
- ——此处的
lazy_static! { static ref RE: Regex = Regex::new(...).unwrap(); }是可接受的,属于初始化阶段.unwrap() - 链式调用——虽冗余但为必填项
.context("description")? - 回退匹配分支——看似冗余但为安全兜底
Err(e) => { eprintln!(...); raw_output } - run()末尾的——看似可替换为
std::process::exit(code)但实际不可行Ok(())