Skip to main content

cure_engine/
cost.rs

1//! 成本模型:默认节点权重表。
2//!
3//! 目标是给“改写后是否更简单”一个可比较的量:语句与临时变量比表达式贵,
4//! 字面量/变量引用最便宜。语言可经 `Lang::cost_weight` 覆盖。
5
6use crate::kind::NodeKind;
7use crate::lang::Lang;
8
9pub fn default_weight(kind: NodeKind) -> u64 {
10    use NodeKind::*;
11    match kind {
12        Literal | VarRef | Paren | This | Empty => 1,
13        Binary | Unary | Break | Continue => 3,
14        Member | Index | ExprStmt => 3,
15        Block | ArrayLit | Ternary | Cast => 4,
16        Return | Yield | Call => 4,
17        If | While | DoWhile | Throw | New => 6,
18        Assign => 8,
19        For | ForEach => 8,
20        VarDecl => 12,
21        Switch | Case | Try | Catch => 10,
22        Synchronized | Assert | Label | InstanceOf | Lambda | MethodRef | NewArray => 6,
23        Raw => 20,
24        Custom(_) => 5,
25    }
26}
27
28/// 迭代式子树成本(防爆栈)。
29pub fn subtree_cost<L: Lang>(lang: &L, id: L::Id) -> u64 {
30    let mut total = 0u64;
31    let mut stack = vec![id];
32    while let Some(n) = stack.pop() {
33        total += lang.cost_weight(lang.kind(n));
34        for &c in lang.children(n) {
35            stack.push(c);
36        }
37    }
38    total
39}