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
use super::*;

pub struct Repl {
    current_path: Path,
    sim: Sim,
    circuit: Circuit,
    testbench: Testbench,
    readline: rustyline::DefaultEditor,
    watches: Vec<Watch>,
}

impl Repl {
    pub fn new(sim: Sim, circuit: Circuit, testbench: Testbench) -> Repl {
        let current_path = "top".into();
        let readline = rustyline::DefaultEditor::new().unwrap();

        Repl {
            current_path,
            sim,
            circuit,
            testbench,
            readline,
            watches: vec![],
        }
    }

    fn readline(&mut self) -> String {
        loop {
            let result = self.readline.readline(&format!("{}> ", self.current_path));
            match result {
                Ok(line) => {
                    self.readline.add_history_entry(line.as_str()).unwrap();
                    return line;
                },
                Err(rustyline::error::ReadlineError::Eof) => std::process::exit(0),
                Err(rustyline::error::ReadlineError::Interrupted) => (),
                Err(e) => panic!("{e:?}"),
            }
        }
    }

    pub fn run(&mut self) {
        // self.show();
        let commands = self.testbench.2.clone();
        for command in commands{
            self.exec_tb_command(command);
        }
    }

    fn exec_tb_command(&mut self, command: TestbenchCommand) {
        let verbose = true;
        match command {
            TestbenchCommand::Watch(Watch(path, fmt)) => {
                let abs_path = if path.is_absolute() {
                    path
                } else {
                    self.current_path.join(path)
                };

                if self.circuit.component(abs_path.clone()).is_some() {
                    println!("Adding watch: {abs_path}");
                    self.watches.push(Watch(abs_path, fmt));
                } else {
                    println!("Can't watch: no such path: {abs_path}");
                }
            },
            TestbenchCommand::Cd(path) => {
                if let Some(path) = path {
                    if path == "..".into() { // HACK
                        self.current_path = self.current_path.parent();
                    } else {
                        let new_path = self.current_path.join(path);
                        if let Some(component) = self.circuit.component(new_path.clone()) {
                            if component.is_mod() {
                                self.current_path = new_path;
                            } else {
                                eprintln!("{new_path} is not a mod");
                            }
                        } else {
                            eprintln!("No such path: {new_path}");
                        }
                    }
                } else {
                    self.current_path = "top".into();
                }
            },
            TestbenchCommand::Peek(terminal) => {
                print!("PEEK {terminal} ");
                let value = self.sim.peek(terminal);
                if verbose {
                    println!("=> {value:?}");
                }
            },
            TestbenchCommand::Poke(terminal, value) => {
                if verbose {
                    println!("POKE {terminal} <= {value:?}");
                }
                self.sim.poke(terminal, value);
            },
            TestbenchCommand::Set(terminal, value) => {
                if verbose {
                    println!("SET {terminal} = {value:?}");
                }
                // TODO
                // self.sim.set(terminal, value);
                eprintln!("Not implemented");
            },
            TestbenchCommand::Clock => {
                if verbose {
                    println!("CLOCK");
                }
                self.sim.clock();
                self.show_watches();
            },
            TestbenchCommand::Reset => {
                if verbose {
                    println!("RESET");
                }
                self.sim.reset();
                self.show_watches();
            },
            TestbenchCommand::Run => {
                if verbose {
                    println!("RUN");
                }
                loop {
                    self.sim.clock();
                    self.show_watches();
                }
            },
            TestbenchCommand::Show => {
                self.show();
            },
            TestbenchCommand::Debug => {
                loop {
                    match parse_testbench_command(&self.readline()) {
                        Ok(command) => {
                            if let TestbenchCommand::Debug = command {
                                break;
                            } else if let TestbenchCommand::Show = command {
                                self.show();
                            } else {
                                self.exec_tb_command(command);
//                                self.show();
                            }
                        },
                        Err(err) => eprintln!("{err:?}"),
                    }
                }
            },
//            TestbenchCommand::Eval(e) => {
//                print!("EVAL {e:?}");
//                let result = e.rebase(self.current_path.clone()).eval(&self.sim);
//                println!("=> {result:?}");
//            },
//            TestbenchCommand::Assert(e) => {
//                let result = e.eval(&self.sim);
//                println!("ASSERT {e:?}");
//                if let Value::Word(1, 1) = result {
//                    // Do nothing.
//                } else {
//                    println!("Assertion failed");
//                    for path in e.paths() {
//                        println!("    {path} => {:?}", self.sim.peek(path.clone()));
//
//                    }
//                    panic!("");
//                }
//            },
        }
    }

    fn show(&self) {
        for (net_id, value) in self.sim.net_values() {
            let net = &self.sim.net(net_id);
            let terminals = net.terminals()
                .iter()
                .map(|t| t.to_string())
                .filter(|p| p.starts_with(&self.current_path.to_string()))
                .map(|p| p[self.current_path.to_string().len() + 1..].to_string())
                .collect::<Vec<String>>();

            if !terminals.is_empty() {
                print!("{:>4}    {:>5}   ", format!("#{net_id}"), format!("{value:?}"));
                println!("{}", terminals.join(" "));
            }
        }
    }

    fn show_watches(&self) {
        for Watch(path, format) in &self.watches {
            let value = self.sim.peek(&**path);
            match format {
                WatchFormat::Normal =>  println!("    {:>30}   {path}", format!("{value:?}")),
                WatchFormat::Hex =>     println!("    {:>30}   {path}", format!("{value:x}")),
                WatchFormat::Bin =>     println!("    {:>30}   {path}", format!("{value:b}")),
                WatchFormat::Bool =>    println!("    {:>30}   {path}", value.to_bool().unwrap()),
            }
        }
    }
}