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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288

use hashbrown::{HashMap, HashSet};
use crate::core::BlockRef;
use crate::*;

#[derive(Clone)]
pub struct Schedule {
  pub trigger_to_blocks: HashMap<(TableId,RegisterIndex,RegisterIndex),Vec<BlockGraph>>,
  pub input_to_blocks: HashMap<(TableId,RegisterIndex,RegisterIndex),Vec<BlockGraph>>,
  pub output_to_blocks: HashMap<(TableId,RegisterIndex,RegisterIndex),Vec<BlockGraph>>,
  pub trigger_to_output: HashMap<(TableId,RegisterIndex,RegisterIndex),HashSet<(TableId,RegisterIndex,RegisterIndex)>>,
  pub schedules: HashMap<(TableId,RegisterIndex,RegisterIndex),Vec<BlockGraph>>, // Block Graph is list of blocks that will trigger in order when the given register is set
  unscheduled_blocks: Vec<BlockRef>,
}

impl Schedule {

  pub fn new() -> Schedule {
    Schedule {
      trigger_to_blocks: HashMap::new(),
      input_to_blocks: HashMap::new(),
      output_to_blocks: HashMap::new(),
      trigger_to_output: HashMap::new(),
      schedules: HashMap::new(),
      unscheduled_blocks: Vec::new(),
    }
  }
 
  pub fn add_block(&mut self, block_ref: BlockRef) -> Result<(),MechError> {

    self.unscheduled_blocks.push(block_ref);

    Ok(())
  }


  pub fn schedule_blocks(&mut self) -> Result<(),MechError> {
    if  self.unscheduled_blocks.len() == 0 {
      return Ok(())
    }
    let ready_blocks: Vec<BlockRef> = self.unscheduled_blocks.drain_filter(|b| b.borrow().state == BlockState::Ready).collect();

    for block_ref in &ready_blocks {
      let mut graph = BlockGraph::new(block_ref.clone());
      let block_brrw = block_ref.borrow();

      // Map trigger registers to blocks
      for (trigger_table_id,row,col) in &block_brrw.triggers {
        let ref mut dependent_blocks = self.trigger_to_blocks.entry((*trigger_table_id,*row,*col)).or_insert(vec![]);
        dependent_blocks.push(graph.clone());
        let ref mut dependent_blocks = self.schedules.entry((*trigger_table_id,*row,*col)).or_insert(vec![]);
        dependent_blocks.push(graph.clone());

        for ((output_table_id,row,col),ref mut producing_blocks) in self.output_to_blocks.iter_mut() {
          if output_table_id == trigger_table_id {
            for ref mut pblock in producing_blocks.iter_mut() {
              pblock.add_child(&mut graph);
            }
          }
        }
      }

      // Map input registers to blocks
      for (input_table_id,row,col) in &block_brrw.input {
        let ref mut consuming_blocks = self.input_to_blocks.entry((*input_table_id,*row,*col)).or_insert(vec![]);
        consuming_blocks.push(graph.clone());
      }

      // Map output registers to blocks
      for (output_table_id,row,col) in &block_brrw.output {
        let ref mut producing_blocks = self.output_to_blocks.entry((*output_table_id,*row,*col)).or_insert(vec![]);
        producing_blocks.push(graph.clone());
        // Map block outputs to triggers
        if let Some(consuming_blocks) = self.trigger_to_blocks.get(&(*output_table_id,*row,*col)) {
          for block in consuming_blocks {
            graph.add_child(&block);
          }
        }
      }
    }
    // This collects all of the output that would be changed given a trigger
    // TODO I'd like to do this incrementally instead of redoing it
    // every time blocks are scheduled. But I'm short on time now and 
    // this is all I can think of to do without changing too much.
    for (register,block_graphs) in self.schedules.iter() {
      let (table_id,row_ix,col_ix) = register;
      let mut aggregate_output = HashSet::new();
      for graph in block_graphs {
        let mut node = &graph.root;
        let node_brrw = node.borrow();
        let mut output = node_brrw.aggregate_output();
        aggregate_output = aggregate_output.union(&mut output).cloned().collect();
      }
      self.trigger_to_output.insert(register.clone(),aggregate_output);
    }
    Ok(())
  }

  pub fn run_schedule(&mut self, register: &(TableId,RegisterIndex,RegisterIndex)) -> Result<(),MechError> {
    match self.schedules.get_mut(register) {
      Some(ref mut block_graphs) => {
        for ref mut block_graph in block_graphs.iter_mut() {
          block_graph.solve();
        }
        Ok(())
      }
      None => {
        Err(MechError{msg: "".to_string(), id: 5368, kind: MechErrorKind::GenericError(format!("No schedule assocaited with {:?}", register))})
      }
    }
  }
}

impl fmt::Debug for Schedule {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    let mut box_drawing = BoxPrinter::new();
    box_drawing.add_header("triggers");
    box_drawing.add_line(format!("{:#?}", &self.trigger_to_blocks));
    box_drawing.add_header("input");
    box_drawing.add_line(format!("{:#?}", &self.input_to_blocks));
    box_drawing.add_header("output");
    box_drawing.add_line(format!("{:#?}", &self.output_to_blocks));
    box_drawing.add_header("output schedule");
    box_drawing.add_line(format!("{:#?}", &self.trigger_to_output));
    box_drawing.add_header("schedules");
    box_drawing.add_line(format!("{:#?}", &self.schedules));
    if self.unscheduled_blocks.len() > 0 {
      box_drawing.add_header("unscheduled blocks");
      box_drawing.add_line(format!("{:#?}", &self.unscheduled_blocks.iter().map(|b| humanize(&b.borrow().id)).collect::<Vec<String>>()));
    }
    write!(f,"{:?}",box_drawing)?;
    Ok(())
  }
}


#[derive(Clone)]
pub struct Node {
  block: BlockRef,
  parents: Vec<Rc<RefCell<Node>>>,
  children: Vec<Rc<RefCell<Node>>>,
}

impl Node {

  pub fn new(block: BlockRef) -> Node {
    Node {
      block: block,
      parents: Vec::new(),
      children: Vec::new(),
    }
  }

  pub fn recompile(&self) -> Result<(),MechError> {
    {
      self.block.borrow_mut().recompile()?;
    }
    for child in &self.children {
      let mut child_brrw = child.borrow_mut();
      child_brrw.recompile()?;
    }
    Ok(())
  }

  pub fn triggers(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    self.block.borrow().triggers.clone()
  }

  pub fn input(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    self.block.borrow().input.clone()
  }

  pub fn output(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    self.block.borrow().output.clone()
  }

  pub fn aggregate_output(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    let mut aggregate_output = self.output();
    let mut child_output = self.output_recurse();
    aggregate_output = aggregate_output.union(&mut child_output).cloned().collect();
    aggregate_output
  }

  pub fn output_recurse(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    let mut aggregate_output = HashSet::new();
    for child in &self.children {
      let child_brrw = child.borrow();
      let mut output = child_brrw.output();
      let mut child_output = child_brrw.output_recurse();
      aggregate_output = aggregate_output.union(&mut output).cloned().collect();
      aggregate_output = aggregate_output.union(&mut child_output).cloned().collect();
    }
    aggregate_output
  }

  pub fn add_child(&mut self, child: Rc<RefCell<Node>>) {
    self.children.push(child);
  }

  pub fn add_parent(&mut self, parent: Rc<RefCell<Node>>) {
    self.parents.push(parent);
  }

  pub fn solve(&mut self) -> Result<(),MechError> {
    self.block.borrow_mut().solve()?;
    for ref mut child in &mut self.children {
      child.borrow_mut().solve()?;
    }
    Ok(())
  }

}

impl fmt::Debug for Node {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f,"[{}]",humanize(&self.block.borrow().id))?;
    for child in &self.children {
      write!(f,"->{:?}\n",&child.borrow())?;
    }
    Ok(())
  }
}

#[derive(Clone)]
pub struct BlockGraph {
  pub root: Rc<RefCell<Node>>,
}

impl BlockGraph {

  pub fn new(block: BlockRef) -> BlockGraph {
    let node = Rc::new(RefCell::new(Node::new(block)));
    BlockGraph {
      root: node,
    }
  }

  pub fn id(&self) -> u64 {
    self.root.borrow().block.borrow().id
  }

  pub fn recompile_blocks(&self) -> Result<(),MechError> {
    let root_brrw = self.root.borrow();
    root_brrw.recompile()?;
    Ok(())
  }

  pub fn triggers(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    self.root.borrow().triggers()
  }

  pub fn input(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    self.root.borrow().input()
  }

  pub fn output(&self) -> HashSet<(TableId,RegisterIndex,RegisterIndex)> {
    self.root.borrow().output()
  }

  pub fn add_child(&mut self, block: &BlockGraph) -> Result<(),MechError> {
    {
      let mut root_block = self.root.borrow_mut();
      let rc = block.root.clone();
      root_block.add_child(rc);
    }
    {
      let mut child_block = block.root.borrow_mut();
      child_block.add_parent(self.root.clone());
    }
    Ok(())
  }

  pub fn solve(&mut self) -> Result<(),MechError> {
    self.root.borrow_mut().solve()
  }


}

impl fmt::Debug for BlockGraph {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f,"{:?}",self.root.borrow())?;
    Ok(())
  }
}