1use std::collections::BTreeMap;
5
6use dive_ir::actions::ActionName;
7use dive_model::Model;
8
9#[derive(Clone, Debug)]
11pub struct ActionGroup {
12 pub id: usize,
14 pub name: String,
16 pub label: String,
18 pub location: dive_ir::Origin,
20 pub initial: bool,
22 pub bound_action_ids: Vec<usize>,
24}
25
26#[derive(Clone, Debug)]
28pub struct ActionFlow {
29 pub actions: Vec<ActionGroup>,
31 pub transitions: BTreeMap<(usize, usize), u64>,
33 groups: BTreeMap<usize, usize>,
34}
35
36impl ActionFlow {
37 pub fn new(model: &Model) -> Result<Self, dive_eval::EvalError> {
42 model
43 .evaluator
44 .validate_model_context(&model.ir, &model.names)?;
45 let mut flow = Self {
46 actions: Vec::new(),
47 transitions: BTreeMap::new(),
48 groups: BTreeMap::new(),
49 };
50 let mut locations = BTreeMap::new();
51 for (action, initial) in model
52 .init_actions
53 .iter()
54 .map(|a| (a, true))
55 .chain(model.actions.iter().map(|a| (a, false)))
56 {
57 model
58 .evaluator
59 .validate_predicate(&action.scope(), action.expr())?;
60 let origin = model.ir.node(action.expr()).origin;
61 let name = match action.name() {
62 ActionName::Def(def) => model
63 .ir
64 .defs()
65 .get(def.index())
66 .ok_or_else(|| {
67 dive_eval::EvalError::unsupported(
68 "basic simulation statistics require a valid action definition ID",
69 )
70 })?
71 .name
72 .clone(),
73 ActionName::Std(op) => op.name().to_owned(),
74 ActionName::Builtin(name) => name.to_owned(),
75 ActionName::Unnamed => "Action".to_owned(),
76 };
77 let key = (origin.file, origin.begin, origin.end);
80 let group = *locations.entry(key).or_insert_with(|| {
81 let id = flow.actions.len();
82 flow.actions.push(ActionGroup {
83 id,
84 name,
85 label: action.label().to_owned(),
86 location: origin,
87 initial,
88 bound_action_ids: Vec::new(),
89 });
90 id
91 });
92 flow.actions[group].bound_action_ids.push(action.id());
93 if flow.groups.insert(action.id(), group).is_some() {
94 return Err(dive_eval::EvalError::unsupported(
95 "basic simulation statistics require unique bound action IDs",
96 ));
97 }
98 }
99 Ok(flow)
100 }
101
102 pub fn record(&mut self, previous: usize, chosen: usize) -> Result<(), dive_eval::EvalError> {
107 let from = self.groups.get(&previous).copied().ok_or_else(|| {
111 dive_eval::EvalError::bug("simulation previous action is missing from its flow groups")
112 })?;
113 let to = self.groups.get(&chosen).copied().ok_or_else(|| {
114 dive_eval::EvalError::bug("simulation chosen action is missing from its flow groups")
115 })?;
116 let count = self.transitions.entry((from, to)).or_default();
117 *count = count.checked_add(1).ok_or_else(|| {
120 dive_eval::EvalError::resource_limit("simulation action-flow count overflow")
121 })?;
122 Ok(())
123 }
124}