gen_sv.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import csv
  2. import sys
  3. from os import path
  4. def remove(datal, skipl):
  5. for skip in skipl:
  6. del datal[skip]
  7. return datal
  8. if __name__ == '__main__':
  9. if len(sys.argv) != 3:
  10. print(f"Invalid arguments, usage: {sys.argv[0]} [input csv] [output verilog]")
  11. sys.exit(1)
  12. if not path.exists(sys.argv[1]):
  13. print(f"Input csv does not exist: {sys.argv[1]}")
  14. sys.exit(1)
  15. if not path.exists(sys.argv[2]):
  16. print(f"Output verilog does not exist: {sys.argv[1]}")
  17. sys.exit(1)
  18. header = []
  19. casename = ''
  20. cases = dict()
  21. skip = set()
  22. with open(sys.argv[1]) as csv_file:
  23. csv_reader = csv.reader(csv_file, delimiter=',')
  24. line_count = 0
  25. for row in csv_reader:
  26. line_count += 1
  27. if line_count == 1:
  28. casename = row[0].strip() or 'case_name'
  29. header = row[1:]
  30. for i, head in enumerate(header):
  31. head = head.strip()
  32. if not head:
  33. skip.add(i)
  34. header[i] = head
  35. header = remove(header, skip)
  36. continue
  37. if row[0].strip():
  38. cases[row[0].strip()] = list(map(lambda x: x.strip(), remove(row[1:], skip)))
  39. for arr in cases.values():
  40. for i, v in enumerate(arr):
  41. if set(v) == {'x'}:
  42. arr[i] = f"{len(v)}'b{'_'.join([v[i:i+4] for i in range(0, len(v), 4)])}"
  43. max_header = max(map(lambda x: len(x), header))
  44. max_case = max(map(lambda x: len(x), cases.keys()))
  45. sv_data = []
  46. start_line = 0
  47. end_line = 0
  48. with open(sys.argv[2], 'r') as v_file:
  49. line_no = 0
  50. for line in v_file.readlines():
  51. sv_data.append(line)
  52. line_no += 1
  53. if line.strip().lower() == '// generated table':
  54. start_line = line_no
  55. elif line.strip().lower() == '// generated table end':
  56. end_line = line_no
  57. if start_line == 0 or end_line <= start_line:
  58. print(f"Failed to find 'generated table' comment in {sys.argv[2]}")
  59. sys.exit(1)
  60. idata = ['\talways_comb begin', f'\tcasez({casename})']
  61. for case, value in cases.items():
  62. idata.append(f'\t\t{case.ljust(max_case, " ")}: begin')
  63. for i, head in enumerate(header):
  64. idata.append(f'\t\t\t{head.ljust(max_header, " ")} = {value[i]};')
  65. idata.append('\t\tend')
  66. idata.append('\tendcase')
  67. idata.append('\tend')
  68. with open(sys.argv[2], 'w') as v_file:
  69. v_file.writelines(sv_data[:start_line])
  70. v_file.write("\n".join(idata).replace('\t', ' ')+"\n")
  71. v_file.writelines(sv_data[end_line-1:])