cairo_lang_sierra/simulation/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use std::collections::HashMap;

use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use itertools::izip;
use thiserror::Error;

use self::value::CoreValue;
use crate::edit_state::{put_results, take_args, EditStateError};
use crate::extensions::core::{CoreConcreteLibfunc, CoreLibfunc, CoreType};
use crate::ids::{FunctionId, VarId};
use crate::program::{Program, Statement, StatementIdx};
use crate::program_registry::{ProgramRegistry, ProgramRegistryError};

pub mod core;
#[cfg(test)]
mod test;
pub mod value;

/// Error occurring while simulating a libfunc.
#[derive(Error, Debug, Eq, PartialEq)]
pub enum LibfuncSimulationError {
    #[error("Expected different number of arguments")]
    WrongNumberOfArgs,
    #[error("Expected a different type of an argument")]
    WrongArgType,
    #[error("Could not resolve requested symbol value")]
    UnresolvedStatementGasInfo,
    #[error("Error occurred during user function call")]
    FunctionSimulationError(FunctionId, Box<SimulationError>),
}

/// Error occurring while simulating a program function.
#[derive(Error, Debug, Eq, PartialEq)]
pub enum SimulationError {
    #[error("error from the program registry")]
    ProgramRegistryError(#[from] Box<ProgramRegistryError>),
    #[error("error from editing a variable state")]
    EditStateError(EditStateError, StatementIdx),
    #[error("error from simulating a libfunc")]
    LibfuncSimulationError(LibfuncSimulationError, StatementIdx),
    #[error("jumped out of bounds during simulation")]
    StatementOutOfBounds(StatementIdx),
    #[error("unexpected number of arguments to function")]
    FunctionArgumentCountMismatch { function_id: FunctionId, expected: usize, actual: usize },
    #[error("identifiers left at function return")]
    FunctionDidNotConsumeAllArgs(FunctionId, StatementIdx),
}

/// Runs a function from the program with the given inputs.
pub fn run(
    program: &Program,
    statement_gas_info: &HashMap<StatementIdx, i64>,
    function_id: &FunctionId,
    inputs: Vec<CoreValue>,
) -> Result<Vec<CoreValue>, SimulationError> {
    let context = SimulationContext {
        program,
        statement_gas_info,
        registry: &ProgramRegistry::new(program)?,
    };
    context.simulate_function(function_id, inputs)
}

/// Helper class for running the simulation.
struct SimulationContext<'a> {
    pub program: &'a Program,
    pub statement_gas_info: &'a HashMap<StatementIdx, i64>,
    pub registry: &'a ProgramRegistry<CoreType, CoreLibfunc>,
}
impl SimulationContext<'_> {
    /// Simulates the run of a function, even recursively.
    fn simulate_function(
        &self,
        function_id: &FunctionId,
        inputs: Vec<CoreValue>,
    ) -> Result<Vec<CoreValue>, SimulationError> {
        let func = self.registry.get_function(function_id)?;
        let mut current_statement_id = func.entry_point;
        if func.params.len() != inputs.len() {
            return Err(SimulationError::FunctionArgumentCountMismatch {
                function_id: func.id.clone(),
                expected: func.params.len(),
                actual: inputs.len(),
            });
        }
        let mut state = OrderedHashMap::<VarId, CoreValue>::from_iter(
            izip!(func.params.iter(), inputs).map(|(param, input)| (param.id.clone(), input)),
        );
        loop {
            let statement = self
                .program
                .get_statement(&current_statement_id)
                .ok_or(SimulationError::StatementOutOfBounds(current_statement_id))?;
            match statement {
                Statement::Return(ids) => {
                    let (remaining, outputs) = take_args(state, ids.iter()).map_err(|error| {
                        SimulationError::EditStateError(error, current_statement_id)
                    })?;
                    return if remaining.is_empty() {
                        Ok(outputs)
                    } else {
                        Err(SimulationError::FunctionDidNotConsumeAllArgs(
                            func.id.clone(),
                            current_statement_id,
                        ))
                    };
                }
                Statement::Invocation(invocation) => {
                    let (remaining, inputs) =
                        take_args(state, invocation.args.iter()).map_err(|error| {
                            SimulationError::EditStateError(error, current_statement_id)
                        })?;
                    let libfunc = self.registry.get_libfunc(&invocation.libfunc_id)?;
                    let (outputs, chosen_branch) = self.simulate_libfunc(
                        &current_statement_id,
                        libfunc,
                        inputs,
                        current_statement_id,
                    )?;
                    let branch_info = &invocation.branches[chosen_branch];
                    state = put_results(remaining, izip!(branch_info.results.iter(), outputs))
                        .map_err(|error| {
                            SimulationError::EditStateError(error, current_statement_id)
                        })?;
                    current_statement_id = current_statement_id.next(&branch_info.target);
                }
            }
        }
    }
    /// Simulates the run of libfuncs. Returns the memory representations of the outputs given the
    /// inputs.
    fn simulate_libfunc(
        &self,
        idx: &StatementIdx,
        libfunc: &CoreConcreteLibfunc,
        inputs: Vec<CoreValue>,
        current_statement_id: StatementIdx,
    ) -> Result<(Vec<CoreValue>, usize), SimulationError> {
        core::simulate(
            libfunc,
            inputs,
            || self.statement_gas_info.get(idx).copied(),
            |function_id, inputs| {
                self.simulate_function(function_id, inputs).map_err(|error| {
                    LibfuncSimulationError::FunctionSimulationError(
                        function_id.clone(),
                        Box::new(error),
                    )
                })
            },
        )
        .map_err(|error| SimulationError::LibfuncSimulationError(error, current_statement_id))
    }
}