neo_solidity/optimizer/
types.rs

1/// Yul AST optimizer with configurable optimization levels
2pub struct Optimizer {
3    level: u8,
4    stats: OptimizationStats,
5    /// Maximum function size for inlining (in AST nodes)
6    inline_threshold: usize,
7    /// Track which optimizations are enabled
8    enabled_passes: OptimizationPasses,
9}
10
11/// Statistics collected during optimization
12#[derive(Debug, Clone, Default)]
13pub struct OptimizationStats {
14    pub eliminated_instructions: u32,
15    pub inlined_functions: u32,
16    pub folded_constants: u32,
17    /// Number of optimization passes run
18    pub passes_run: u32,
19    /// Total AST nodes before optimization
20    pub nodes_before: usize,
21    /// Total AST nodes after optimization
22    pub nodes_after: usize,
23}
24
25impl OptimizationStats {
26    /// Calculate the reduction percentage
27    pub fn reduction_percent(&self) -> f64 {
28        if self.nodes_before == 0 {
29            return 0.0;
30        }
31        let reduced = self.nodes_before.saturating_sub(self.nodes_after);
32        (reduced as f64 / self.nodes_before as f64) * 100.0
33    }
34
35    /// Merge stats from another optimization pass
36    pub fn merge(&mut self, other: &OptimizationStats) {
37        self.eliminated_instructions += other.eliminated_instructions;
38        self.inlined_functions += other.inlined_functions;
39        self.folded_constants += other.folded_constants;
40        self.passes_run += other.passes_run;
41    }
42}
43
44/// Bitflags for enabled optimization passes
45#[derive(Debug, Clone, Copy, Default)]
46pub struct OptimizationPasses {
47    pub constant_folding: bool,
48    pub dead_code_elimination: bool,
49    pub function_inlining: bool,
50    pub common_subexpression: bool,
51}
52
53impl OptimizationPasses {
54    /// Create passes for a given optimization level
55    pub fn for_level(level: u8) -> Self {
56        match level {
57            0 => Self::default(),
58            1 => Self {
59                constant_folding: true,
60                ..Default::default()
61            },
62            2 => Self {
63                constant_folding: true,
64                dead_code_elimination: true,
65                ..Default::default()
66            },
67            _ => Self {
68                constant_folding: true,
69                dead_code_elimination: true,
70                function_inlining: true,
71                common_subexpression: true,
72            },
73        }
74    }
75}
76
77/// Represents a function that can be inlined
78#[allow(dead_code)]
79struct InlineCandidate {
80    /// Parameter names in order
81    params: Vec<String>,
82    /// Function body to inline
83    body: AstNode,
84    /// Estimated cost of inlining (for future use)
85    cost: usize,
86}
87