1use std::{fmt::Display};
2
3use crate::{
4 Cell, CellId, Const, ConstBit, ControlNet, Design, IoNet, IoValue, MemoryPortRelation, TargetOutput, Value,
5 ValueBit, ValueSlice, metadata::MetaItemId,
6};
7
8struct DisplayFn<'a, F: for<'b> Fn(&Design, &mut std::fmt::Formatter<'b>) -> std::fmt::Result>(&'a Design, F);
9
10impl<F: Fn(&Design, &mut std::fmt::Formatter) -> std::fmt::Result> Display for DisplayFn<'_, F> {
11 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
12 self.1(self.0, f)
13 }
14}
15
16impl Design {
17 fn find_cell_output(&self, net: ValueBit) -> Result<(Value, usize, usize), ConstBit> {
20 if let Some(val) = net.as_const() {
21 return Err(val);
22 }
23 let (cell_id, offset) = self.find_cell(net);
24 let cell_index = cell_id.debug_index();
25 match &*self.cell(cell_id) {
26 Cell::Other(instance) => {
27 for &range in instance.outputs.values() {
28 if range.contains(&offset) {
29 return Ok((
30 self.cell_output(cell_id).slice(range),
31 cell_index + range.start,
32 offset - range.start,
33 ));
34 }
35 }
36 unreachable!()
37 }
38 Cell::Target(target_cell) => {
39 let prototype = self.target_prototype(target_cell);
40 for &TargetOutput { range, .. } in &prototype.outputs {
41 if range.contains(&offset) {
42 return Ok((
43 self.cell_output(cell_id).slice(range),
44 cell_index + range.start,
45 offset - range.start,
46 ));
47 }
48 }
49 unreachable!()
50 }
51 Cell::Memory(memory) => {
52 let mut port_offset = 0;
53 for port in &memory.read_ports {
54 let port_range = port_offset..port_offset + port.data_len;
55 if port_range.contains(&offset) {
56 return Ok((
57 self.cell_output(cell_id).slice(port_range.clone()),
58 cell_index + port_range.start,
59 offset - port_range.start,
60 ));
61 }
62 port_offset += port.data_len;
63 }
64 unreachable!()
65 }
66 _ => Ok((self.cell_output(cell_id), cell_index, offset)),
67 }
68 }
69
70 pub(crate) fn write_string(f: &mut std::fmt::Formatter, str: &str) -> std::fmt::Result {
71 write!(f, "\"")?;
72 for byte in str.as_bytes() {
73 if (byte.is_ascii_graphic() || matches!(byte, b' ' | b'\t')) && !matches!(byte, b'\\' | b'"') {
74 write!(f, "{}", *byte as char)?;
75 } else {
76 assert!(byte.is_ascii());
77 write!(f, "\\{byte:02x}")?;
78 }
79 }
80 write!(f, "\"")?;
81 Ok(())
82 }
83
84 pub(crate) fn write_io_net(&self, f: &mut std::fmt::Formatter, io_net: IoNet) -> std::fmt::Result {
85 if io_net.is_floating() {
86 write!(f, "&_")
87 } else {
88 write!(f, "&")?;
89 match self.find_io(io_net) {
90 Some((name, offset)) => {
91 Design::write_string(f, name)?;
92 if self.get_io(name).unwrap().len() > 1 {
93 write!(f, "+{offset}")?;
94 }
95 Ok(())
96 }
97 None => write!(f, "??"),
98 }
99 }
100 }
101
102 pub(crate) fn write_io_value(&self, f: &mut std::fmt::Formatter, io_value: &IoValue) -> std::fmt::Result {
103 if io_value.is_empty() {
104 write!(f, "[]")
105 } else if io_value.len() == 1 {
106 self.write_io_net(f, io_value[0])
107 } else if io_value.iter().all(IoNet::is_floating) {
108 write!(f, "&_:{}", io_value.len())
109 } else {
110 if let Some((name, _offset)) = self.find_io(io_value[0])
111 && self.get_io(name).unwrap() == *io_value
112 {
113 write!(f, "&")?;
114 Design::write_string(f, name)?;
115 write!(f, ":{}", io_value.len())?;
116 return Ok(());
117 }
118 write!(f, "[")?;
119 for io_net in io_value.iter().rev() {
120 write!(f, " ")?;
121 self.write_io_net(f, io_net)?;
122 }
123 write!(f, " ]")
124 }
125 }
126
127 pub(crate) fn write_net(&self, f: &mut std::fmt::Formatter, net: ValueBit) -> std::fmt::Result {
128 let index = net.as_cell_index();
129 if !self.is_valid_cell_index(index) {
130 return write!(f, "%_{index}");
131 }
132 match self.find_cell_output(net) {
133 Ok((output, index, offset)) => {
134 if output.len() == 1 {
135 write!(f, "%{index}")
136 } else {
137 write!(f, "%{index}+{offset}")
138 }
139 }
140 Err(trit) => write!(f, "{trit}"),
141 }
142 }
143
144 pub(crate) fn write_control_net(&self, f: &mut std::fmt::Formatter, control_net: ControlNet) -> std::fmt::Result {
145 if control_net.is_negative() {
146 write!(f, "!")?;
147 };
148 self.write_net(f, control_net.net())
149 }
150
151 pub(crate) fn write_value(&self, f: &mut std::fmt::Formatter, value: &ValueSlice) -> std::fmt::Result {
152 enum Chunk {
153 Slice { cell_index: usize, offset: usize, width: usize, repeat: usize },
154 WholeGrainCell { cell_index: usize, width: usize, repeat: usize },
155 NewNet { net: ValueBit, repeat: usize },
156 Const(Const),
157 }
158 let mut index = 0;
159 let mut chunks = vec![];
160 while index < value.len() {
161 if !self.is_valid_cell_index(value[index].as_cell_index()) {
162 let mut repeat = 1;
165 while index + repeat < value.len() && value[index] == value[index + repeat] {
166 repeat += 1;
167 }
168 chunks.push(Chunk::NewNet { net: value[index], repeat });
169 index += repeat;
170 } else if let Ok((output, index_a, offset_a)) = self.find_cell_output(value[index]) {
171 let count = value[index..]
172 .iter()
173 .enumerate()
174 .take_while(|(addend, net)| {
175 if let Ok((_, index_b, offset_b)) = self.find_cell_output(*net) {
176 index_a == index_b && offset_a + *addend == offset_b
177 } else {
178 false
179 }
180 })
181 .count();
182 assert!(count != 0);
183 let mut repeat = 1;
184 while index + (repeat + 1) * count <= value.len()
185 && value[index..index + count] == value[index + repeat * count..index + (repeat + 1) * count]
186 {
187 repeat += 1;
188 }
189 if offset_a == 0 && output.len() == count {
190 chunks.push(Chunk::WholeGrainCell { cell_index: index_a, width: count, repeat });
191 } else {
192 chunks.push(Chunk::Slice { cell_index: index_a, offset: offset_a, width: count, repeat });
193 }
194 index += count * repeat;
195 } else {
196 let const_value = Const::from_iter(
197 value[index..].iter().take_while(|net| net.as_const().is_some()).map(|net| net.as_const().unwrap()),
198 );
199 assert!(!const_value.is_empty());
200 index += const_value.len();
201 chunks.push(Chunk::Const(const_value));
202 }
203 }
204 if chunks.is_empty() {
205 return write!(f, "[]");
206 }
207 let single_chunk = chunks.len() == 1;
208 if !single_chunk {
209 write!(f, "[")?;
210 }
211 for chunk in chunks.into_iter().rev() {
212 if !single_chunk {
213 write!(f, " ")?;
214 }
215 match chunk {
216 Chunk::Slice { cell_index, offset, width, repeat } => {
217 write!(f, "%{cell_index}+{offset}")?;
218 if width != 1 {
219 write!(f, ":{width}")?;
220 }
221 if repeat != 1 {
222 write!(f, "*{repeat}")?;
223 }
224 }
225 Chunk::WholeGrainCell { cell_index, width, repeat } => {
226 write!(f, "%{cell_index}")?;
227 if width != 1 {
228 write!(f, ":{width}")?;
229 }
230 if repeat != 1 {
231 write!(f, "*{repeat}")?;
232 }
233 }
234 Chunk::Const(const_value) => {
235 write!(f, "{const_value}")?;
236 }
237 Chunk::NewNet { net, repeat } => {
238 self.write_net(f, net)?;
239 if repeat != 1 {
240 write!(f, "*{repeat}")?;
241 }
242 }
243 }
244 }
245 if !single_chunk {
246 write!(f, " ]")?;
247 }
248 Ok(())
249 }
250
251 pub(crate) fn write_cell(
252 &self,
253 f: &mut std::fmt::Formatter,
254 prefix: &str,
255 index: usize,
256 cell: &Cell,
257 metadata: MetaItemId,
258 ) -> std::fmt::Result {
259 let newline = &format!("\n{prefix}");
260
261 let write_metadata = |f: &mut std::fmt::Formatter| -> std::fmt::Result {
262 if metadata != MetaItemId::NONE { write!(f, " {metadata}") } else { Ok(()) }
263 };
264
265 let write_control = |f: &mut std::fmt::Formatter, name: &str, control_net: ControlNet| -> std::fmt::Result {
266 write!(f, "{name}=")?;
267 self.write_control_net(f, control_net)
268 };
269
270 let write_common = |f: &mut std::fmt::Formatter, name: &str, args: &[&Value]| -> std::fmt::Result {
271 write!(f, "{name}")?;
272 for arg in args {
273 write!(f, " ")?;
274 self.write_value(f, arg)?;
275 }
276 Ok(())
277 };
278
279 let write_shift =
280 |f: &mut std::fmt::Formatter, name: &str, arg1: &Value, arg2: &Value, stride: u32| -> std::fmt::Result {
281 write!(f, "{name} ")?;
282 self.write_value(f, arg1)?;
283 write!(f, " ")?;
284 self.write_value(f, arg2)?;
285 write!(f, " #{stride}")?;
286 Ok(())
287 };
288
289 let write_cell_argument = |f: &mut std::fmt::Formatter, keyword: &str, name: &str| -> std::fmt::Result {
290 write!(f, " {keyword} ")?;
291 Design::write_string(f, name)?;
292 write!(f, " = ")?;
293 Ok(())
294 };
295
296 let single_output = match &cell {
297 Cell::Other(..) => false,
298 Cell::Target(target_cell) if self.target_prototype(target_cell).outputs.len() > 1 => false,
299 Cell::Memory(..) => false,
300 _ => true,
301 };
302 if single_output {
303 write!(f, "{prefix}%{index}:{width} = ", width = cell.output_len())?;
304 } else {
305 write!(f, "{prefix}%{index}:_ = ")?; }
307 match &cell {
308 Cell::Const(trit) => write!(f, "const {trit}")?,
309 Cell::Buf(arg) => write_common(f, "buf", &[arg])?,
310 Cell::Not(arg) => write_common(f, "not", &[arg])?,
311 Cell::And(arg1, arg2) => write_common(f, "and", &[arg1, arg2])?,
312 Cell::Or(arg1, arg2) => write_common(f, "or", &[arg1, arg2])?,
313 Cell::Xor(arg1, arg2) => write_common(f, "xor", &[arg1, arg2])?,
314 Cell::Mux(sel, vals) => {
315 write!(f, "mux ")?;
318 self.write_net(f, *sel)?;
319 write!(f, " ")?;
320 self.write_value(f, &vals[1])?;
321 write!(f, " ")?;
322 self.write_value(f, &vals[0])?;
323 }
324 Cell::Adc(arg1, arg2, arg3) => {
325 write!(f, "adc ")?;
326 self.write_value(f, arg1)?;
327 write!(f, " ")?;
328 self.write_value(f, arg2)?;
329 write!(f, " ")?;
330 self.write_net(f, *arg3)?;
331 }
332 Cell::Aig(arg1, arg2) => {
333 write!(f, "aig ")?;
334 self.write_control_net(f, *arg1)?;
335 write!(f, " ")?;
336 self.write_control_net(f, *arg2)?;
337 }
338
339 Cell::Eq(arg1, arg2) => write_common(f, "eq", &[arg1, arg2])?,
340 Cell::ULt(arg1, arg2) => write_common(f, "ult", &[arg1, arg2])?,
341 Cell::SLt(arg1, arg2) => write_common(f, "slt", &[arg1, arg2])?,
342
343 Cell::Shl(arg1, arg2, stride) => write_shift(f, "shl", arg1, arg2, *stride)?,
344 Cell::UShr(arg1, arg2, stride) => write_shift(f, "ushr", arg1, arg2, *stride)?,
345 Cell::SShr(arg1, arg2, stride) => write_shift(f, "sshr", arg1, arg2, *stride)?,
346 Cell::XShr(arg1, arg2, stride) => write_shift(f, "xshr", arg1, arg2, *stride)?,
347
348 Cell::Mul(arg1, arg2) => write_common(f, "mul", &[arg1, arg2])?,
349 Cell::UDiv(arg1, arg2) => write_common(f, "udiv", &[arg1, arg2])?,
350 Cell::UMod(arg1, arg2) => write_common(f, "umod", &[arg1, arg2])?,
351 Cell::SDivTrunc(arg1, arg2) => write_common(f, "sdiv_trunc", &[arg1, arg2])?,
352 Cell::SDivFloor(arg1, arg2) => write_common(f, "sdiv_floor", &[arg1, arg2])?,
353 Cell::SModTrunc(arg1, arg2) => write_common(f, "smod_trunc", &[arg1, arg2])?,
354 Cell::SModFloor(arg1, arg2) => write_common(f, "smod_floor", &[arg1, arg2])?,
355
356 Cell::Match(match_cell) => {
357 write!(f, "match")?;
358 if match_cell.enable != ValueBit::ONE {
359 write!(f, " en=")?;
360 self.write_net(f, match_cell.enable)?;
361 }
362 write!(f, " ")?;
363 self.write_value(f, &match_cell.value)?;
364 let multiline = match_cell
365 .patterns
366 .iter()
367 .map(|alternates| alternates.iter().map(|const_| const_.len()).sum::<usize>())
368 .sum::<usize>()
369 > 80;
370 write_metadata(f)?;
371 write!(f, " {{")?;
372 if multiline {
373 write!(f, "{newline}")?;
374 }
375 for alternates in &match_cell.patterns {
376 if multiline {
377 write!(f, " ")?;
378 } else {
379 write!(f, " ")?;
380 }
381 if alternates.len() == 1 {
382 let pattern = &alternates[0];
383 write!(f, "{pattern}")?;
384 } else {
385 write!(f, "(")?;
386 for (index, pattern) in alternates.iter().enumerate() {
387 if index > 0 {
388 write!(f, " ")?;
389 }
390 write!(f, "{pattern}")?;
391 }
392 write!(f, ")")?;
393 }
394 if multiline {
395 write!(f, "{newline}")?;
396 }
397 }
398 if !multiline {
399 write!(f, " ")?;
400 }
401 write!(f, "}}")?;
402 }
403 Cell::Assign(assign_cell) => {
404 write!(f, "assign")?;
405 if assign_cell.enable != ValueBit::ONE {
406 write!(f, " en=")?;
407 self.write_net(f, assign_cell.enable)?;
408 }
409 write!(f, " ")?;
410 self.write_value(f, &assign_cell.value)?;
411 write!(f, " ")?;
412 self.write_value(f, &assign_cell.update)?;
413 if assign_cell.offset != 0 {
414 write!(f, " at=#{}", assign_cell.offset)?;
415 }
416 }
417
418 Cell::Dff(flip_flop) => {
419 write_common(f, "dff", &[&flip_flop.data])?;
420 write_control(f, " clk", flip_flop.clock)?;
421 if flip_flop.has_clear() {
422 write_control(f, " clr", flip_flop.clear)?;
423 if flip_flop.clear_value != flip_flop.init_value {
424 write!(f, ",{}", flip_flop.clear_value)?;
425 }
426 }
427 if flip_flop.has_load() {
428 write_control(f, " load", flip_flop.load)?;
429 write!(f, ",")?;
430 self.write_value(f, &flip_flop.load_data)?;
431 }
432 if flip_flop.has_reset() {
433 write_control(f, " rst", flip_flop.reset)?;
434 if flip_flop.reset_value != flip_flop.init_value {
435 write!(f, ",{}", flip_flop.reset_value)?;
436 }
437 }
438 if flip_flop.has_enable() {
439 write_control(f, " en", flip_flop.enable)?;
440 }
441 if flip_flop.has_reset() && flip_flop.has_enable() {
442 if flip_flop.reset_over_enable {
443 write!(f, " rst/en")?;
444 } else {
445 write!(f, " en/rst")?;
446 }
447 }
448 if flip_flop.has_init_value() {
449 write!(f, " init={}", flip_flop.init_value)?;
450 }
451 }
452 Cell::Memory(memory) => {
453 write!(f, "memory depth=#{} width=#{}", memory.depth, memory.width)?;
454 write_metadata(f)?;
455 write!(f, " {{{newline}")?;
456 for write_port in &memory.write_ports {
457 write!(f, " write addr=")?;
458 self.write_value(f, &write_port.addr)?;
459 write!(f, " data=")?;
460 self.write_value(f, &write_port.data)?;
461 if !write_port.mask.is_ones() {
462 write!(f, " mask=")?;
463 self.write_value(f, &write_port.mask)?;
464 }
465 write_control(f, " clk", write_port.clock)?;
466 write!(f, "{newline}")?;
467 }
468 let mut port_offset = 0;
469 for read_port in &memory.read_ports {
470 write!(f, " %{}:{} = read addr=", index + port_offset, read_port.data_len)?;
471 self.write_value(f, &read_port.addr)?;
472 if let Some(ref flip_flop) = read_port.flip_flop {
473 write_control(f, " clk", flip_flop.clock)?;
474 if flip_flop.has_clear() {
475 write_control(f, " clr", flip_flop.clear)?;
476 if flip_flop.clear_value != flip_flop.init_value {
477 write!(f, ",{}", flip_flop.clear_value)?;
478 }
479 }
480 if flip_flop.has_reset() {
481 write_control(f, " rst", flip_flop.reset)?;
482 if flip_flop.reset_value != flip_flop.init_value {
483 write!(f, ",{}", flip_flop.reset_value)?;
484 }
485 }
486 if flip_flop.has_enable() {
487 write_control(f, " en", flip_flop.enable)?;
488 }
489 if flip_flop.has_reset() && flip_flop.has_enable() {
490 if flip_flop.reset_over_enable {
491 write!(f, " rst/en")?;
492 } else {
493 write!(f, " en/rst")?;
494 }
495 }
496 if flip_flop.has_init_value() {
497 write!(f, " init={}", flip_flop.init_value)?;
498 }
499 write!(f, " [")?;
500 for (index, relation) in flip_flop.relations.iter().enumerate() {
501 match relation {
502 MemoryPortRelation::Undefined => write!(f, "undef")?,
503 MemoryPortRelation::ReadBeforeWrite => write!(f, "rdfirst")?,
504 MemoryPortRelation::Transparent => write!(f, "trans")?,
505 }
506 if index < flip_flop.relations.len() - 1 {
507 write!(f, " ")?;
508 }
509 }
510 write!(f, "]")?;
511 }
512 write!(f, "{newline}")?;
513 port_offset += read_port.data_len;
514 }
515 let mut rows = Vec::new();
516 for index in 0..memory.depth {
517 rows.push(memory.init_value[(index * memory.width)..((index + 1) * memory.width)].to_owned());
518 }
519 let mut index = 0;
520 while index < rows.len() {
521 write!(f, " init {}", rows[index])?;
522 let mut repeats = 1;
523 while rows.get(index) == rows.get(index + repeats) {
524 repeats += 1;
525 }
526 if repeats > 1 {
527 write!(f, "*{repeats}")?;
528 }
529 write!(f, "{newline}")?;
530 index += repeats;
531 }
532 write!(f, "}}")?;
533 }
534 Cell::IoBuf(io_buffer) => {
535 write!(f, "iobuf ")?;
536 self.write_io_value(f, &io_buffer.io)?;
537 write!(f, " o=")?;
538 self.write_value(f, &io_buffer.output)?;
539 write_control(f, " en", io_buffer.enable)?;
540 }
541 Cell::Other(instance) => {
542 Design::write_string(f, instance.kind.as_str())?;
543 write_metadata(f)?;
544 write!(f, " {{{newline}")?;
545 for (name, value) in instance.params.iter() {
546 write_cell_argument(f, "param", name)?;
547 write!(f, "{value}{newline}")?;
548 }
549 for (name, value) in instance.inputs.iter() {
550 write_cell_argument(f, "input", name)?;
551 self.write_value(f, value)?;
552 write!(f, "{newline}")?;
553 }
554 for (name, range) in instance.outputs.iter() {
555 write!(f, " %{}:{} = output ", index + range.start, range.iter().len())?;
556 Design::write_string(f, name)?;
557 write!(f, "{newline}")?;
558 }
559 for (name, value) in instance.ios.iter() {
560 write_cell_argument(f, "io", name)?;
561 self.write_io_value(f, value)?;
562 write!(f, "{newline}")?;
563 }
564 write!(f, "}}")?;
565 }
566 Cell::Target(target_cell) => {
567 write!(f, "target ")?;
568 let prototype = self.target_prototype(target_cell);
569 Design::write_string(f, &target_cell.kind)?;
570 write_metadata(f)?;
571 write!(f, " {{{newline}")?;
572 for (param, value) in prototype.params.iter().zip(target_cell.params.iter()) {
573 write_cell_argument(f, "param", ¶m.name)?;
574 write!(f, "{value}{newline}")?;
575 }
576 for target_input in &prototype.inputs {
577 write_cell_argument(f, "input", &target_input.name)?;
578 self.write_value(f, &target_cell.inputs.slice(target_input.range))?;
579 write!(f, "{newline}")?;
580 }
581 if prototype.outputs.len() > 1 {
582 for target_output in &prototype.outputs {
583 write!(
584 f,
585 " %{}:{} = output ",
586 index + target_output.range.start,
587 target_output.range.iter().len()
588 )?;
589 Design::write_string(f, &target_output.name)?;
590 write!(f, "{newline}")?;
591 }
592 }
593 for target_io in &prototype.ios {
594 write_cell_argument(f, "io", &target_io.name)?;
595 self.write_io_value(f, &target_cell.ios.slice(target_io.range))?;
596 write!(f, "{newline}")?;
597 }
598 write!(f, "}}")?;
599 }
600
601 Cell::Input(name, _size) => {
602 write!(f, "input ")?;
603 Design::write_string(f, name)?;
604 }
605 Cell::Output(name, value) => {
606 write!(f, "output ")?;
607 Design::write_string(f, name)?;
608 write!(f, " ")?;
609 self.write_value(f, value)?;
610 }
611 Cell::Name(name, value) => {
612 write!(f, "name ")?;
613 Design::write_string(f, name)?;
614 write!(f, " ")?;
615 self.write_value(f, value)?;
616 }
617 Cell::Debug(name, value) => {
618 write!(f, "debug ")?;
619 Design::write_string(f, name)?;
620 write!(f, " ")?;
621 self.write_value(f, value)?;
622 }
623 }
624 match cell {
625 Cell::Match(..) | Cell::Memory(..) | Cell::Other(..) | Cell::Target(..) => (),
626 _ => write_metadata(f)?,
627 }
628 Ok(())
629 }
630
631 pub fn display_net(&self, net: impl Into<ValueBit>) -> impl Display + '_ {
632 let net = net.into();
633 DisplayFn(self, move |design: &Design, f| design.write_net(f, net))
634 }
635
636 pub fn display_control_net(&self, net: impl Into<ControlNet>) -> impl Display + '_ {
637 let net = net.into();
638 DisplayFn(self, move |design: &Design, f| design.write_control_net(f, net))
639 }
640
641 pub fn display_value<'a>(&'a self, value: impl AsRef<ValueSlice> + 'a) -> impl Display + 'a {
642 DisplayFn(self, move |design: &Design, f| design.write_value(f, value.as_ref()))
643 }
644
645 pub fn display_cell<'a>(&'a self, cell_id: CellId) -> impl Display + 'a {
646 DisplayFn(self, move |design: &Design, f| {
647 design.write_cell(f, "", cell_id.debug_index(), &self.cell(cell_id), self.cell_metadata(cell_id))
648 })
649 }
650}