File size: 16,884 Bytes
7df9186 | 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 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | #!/usr/bin/python3
# Larry Doolittle, June 2015
# updates Sept 2015
# Lucas Russo, Feb 2022 (rest generation support and fixes to regex)
# convert to python3 Feb 2022
# Pull port information out of a Verilog program
# to build automatic documentation
# Demand that the input have one port per line, and the
# comment (if any) will be used for the documentation.
# e.g.,
# input signed [17:0] x, // Multiplicand, signed, time-interleaved real and imaginary
# HTML output needs hooks to put actual narrative in the file
# No signed/unsigned information for ports?
import re
import json
import os
# from: https://stackoverflow.com/questions/8234274/how-to-indent-the-contents-of-a-multi-line-string
try:
import textwrap
textwrap.indent
except AttributeError: # undefined function (wasn't added until Python 3.3)
def indent(text, amount, ch=" "):
padding = amount * ch
return "".join(padding+line for line in text.splitlines(True))
else:
def indent(text, amount, ch=" "):
return textwrap.indent(text, amount * ch)
class verilog_port():
def __init__(self, io, signed, msb, lsb, ident, desc):
self.io = io
self.signed = signed
self.msb = msb
self.lsb = lsb
self.ident = ident
self.desc = desc if desc else ""
def sign(self):
if self.signed:
return self.signed
return "unsigned"
def direction(self):
r = self.io
r = r[0].upper()+r[1:]
return r
def bits(self):
if self.msb == 0 and self.lsb == 0:
return ""
return "[{}:{}]".format(self.msb, self.lsb)
def xprint(self):
print("Port {}".format(self.ident))
print(" inout {}".format(self.io))
print(" signed {}".format(self.signed))
print(" range [{}:{}]".format(self.msb, self.lsb))
print(" desc {}".format(self.desc))
def table_row(self):
return "<tr><td><tt>{}</tt></td><td>{}</td><td>{}</td></tr>" \
.format(self.ident+self.bits(), self.direction(), self.desc)
def table_row_html(self):
self.table_row()
def table_row_rst(self):
return """* - {}
- {}
- {}""".format(self.ident+self.bits(), self.direction(), self.desc)
def parse_vline_port(ll):
# Try to match the most complex regex first, as it might be able to
# to match the simpler one by using the optional groups. Maybe use a non-greedy
# pattern?
m = re.search(r'^\s*(\(\*.*?\*\))?\s*\b(input|output|inout)\s+(wire|reg)?'
r'\s*(signed)?\s*\[([^:]+):([^]]+)\]\s*(\w+),?\s*(//\s*(.*))?', ll)
if m:
g = [m.group(i) for i in range(2, 10)]
# print(g)
return verilog_port(io=g[0], signed=g[2], msb=g[3], lsb=g[4], ident=g[5], desc=g[7])
m = re.search(r'^\s*(\(\*.*?\*\))?\s*\b(input|output|inout)\s+(wire|reg)?'
r'\s*(signed)?\s*(\w+),?\s*(//\s*(.*))?', ll)
if m:
g = [m.group(i) for i in range(2, 8)]
# print(g)
return verilog_port(io=g[0], signed=g[2], msb=0, lsb=0, ident=g[3], desc=g[5])
return None
class verilog_param():
def __init__(self, ident, default, desc):
self.ident = ident
self.default = default
self.desc = desc if desc else ""
def xprint(self):
print("Parameter {}".format(self.ident))
print(" default {}".format(self.default))
print(" desc {}".format(self.desc))
def table_row(self):
return "<tr><td><tt>{}</tt></td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>" \
.format(self.ident, "?", "?", self.default, self.desc)
def table_row_html(self):
self.table_row()
def table_row_rst(self):
return """* - {}
- {}
- {}
- {}
- {}""".format(self.ident, "?", "?", self.default, self.desc)
def parse_vline_param(ll):
m = re.search(r'^\s*\bparameter\s+(\w+)\s*=\s*(\w*)[,;]?\s*(//\s*(.*))?', ll)
if m:
g = [m.group(i) for i in range(1, 5)]
# print(g)
return verilog_param(ident=g[0], default=g[1], desc=g[3])
return None
class mod_comment():
def __init__(self, desc=None):
self.desc = desc if desc else ""
def description(self):
return self.desc
def xprint(self):
print(self.desc)
def desc_row_rst(self):
return self.desc
def parse_whole_line_comment_or_blank(ll):
m = re.search(r'^\s*\/[\/]+(.*)', ll)
if m:
g = [m.group(i) for i in range(1, 2)]
# print(g)
return mod_comment(desc=g[0])
m = re.search(r'(^\s*$)', ll)
if m:
g = [m.group(i) for i in range(1, 2)]
# print(g)
return mod_comment(desc=g[0])
return None
def parse_endmodule(ll):
m = re.search(r'^\s*\bendmodule.*', ll)
if m:
return True
return False
def make_html(fname, param_list, port_list):
fbase, fext = os.path.splitext(os.path.basename(fname))
hstring = open(fbase+'.html.in').read()
hdata = json.loads('{' + re.sub('\n', ' ', hstring) + '}')
# print("got it")
print('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">')
print('<html>')
print('<head>')
print(' <meta http-equiv="Content-Type" content="text/html;charset=utf-8">')
print(' <meta name=viewport content="width=device-width, initial-scale=1">')
print(' <title>' + hdata["title"] + '</title>')
print('</head>')
print('<body>')
print('<h1>' + fname + ": " + hdata["title"] + "</h1>")
print(hdata["intro_html"])
if True:
print("<h3>Pinout</h3><p>")
print("<img src=\"{}_block.png\" alt=\"schematic symbol\">\n"
.format(fbase))
if param_list:
print("<h3>Parameters</h3>")
print("<table border=1 cellspacing=0>")
print("<tr><th>Name</th><th>Min</th><th>Max</th><th>Default</th><th>Description</th></tr>")
for p in param_list:
print(p.table_row())
print("</table>\n")
if port_list:
print("<h3>Ports</h3>")
print("<table border=1 cellspacing=0>")
print("<tr><th>Signal</th><th>Direction</th><th>Description</th></tr>")
for p in port_list:
print(p.table_row())
print("</table>\n")
if True:
print("<h3>Implementation and use</h3><p>")
print("The <a href=\"https://en.wikipedia.org/wiki/Software_portability\">portable</a>")
print("<a href=\"https://en.wikipedia.org/wiki/Verilog\">Verilog</a>")
print("implementation in <a href=\"{}\">{}</a>".format(fname, fname))
print(hdata["implement_html"] + "\n")
if True:
print("<p>")
print("A <a href=\"https://gtkwave.sourceforge.net/\">GTKWave</a>-generated")
print("timing diagram showing {} is shown here:"
.format(hdata["timing_html"]))
print("<p><img src=\"{}_timing.png\" alt=\"timing diagram\">\n"
.format(fbase))
try:
cfile = open(fbase+"_check", 'r')
print("<h3>Regression test</h3>")
print("<p>")
print("Expected results of <tt>make {}_check</tt>:<pre>".format(fbase))
print(cfile.read()+"</pre>\n")
except FileNotFoundError:
pass
print("</body></html>")
def make_src_rst(fname):
fbase, fext = os.path.splitext(os.path.basename(fname))
print(".. _{}_source:".format(fbase))
print("")
print('{} Source File'.format(fbase))
print('{}'.format("".join(['='*(len(fbase)+12)])))
print("")
print(".. code-block:: verilog")
print(" :linenos:")
print("")
with open(fname, 'r') as ifile:
print(indent(ifile.read(), 3))
def make_rst(fname, param_list, port_list, mod_comment_list, with_timing=None):
fbase, fext = os.path.splitext(os.path.basename(fname))
print(".. _{}:".format(fbase))
print("")
print('{}'.format(fbase))
print('{}'.format("".join(['='*len(fbase)])))
print("")
if mod_comment_list:
description_txt = "Description"
print('{}'.format(description_txt))
print('{}'.format("".join(["\'"*len(description_txt)])))
print("")
for c in mod_comment_list:
# RST is sensitive with leading spaces, use line blocks
print("| " + c.desc_row_rst())
print("")
if True:
pinout_txt = "Pinout"
print('{}'.format(pinout_txt))
print('{}'.format("".join(["\'"*len(pinout_txt)])))
print("")
print(".. _fig:{}_block:".format(fbase))
print(".. figure:: {}_block.png".format(fbase))
print(" :alt: Schematic symbol")
print("")
if param_list:
param_txt = "Parameters"
print('{}'.format(param_txt))
print('{}'.format("".join(["\'"*len(param_txt)])))
print("")
print(".. list-table:: {}_param_table".format(fbase))
print(" :header-rows: 1")
print("")
print(indent("""* - Name
- Min
- Max
- Default
- Description""", 3))
for p in param_list:
print(indent(p.table_row_rst(), 3))
print("")
if port_list:
port_txt = "Ports"
print('{}'.format(port_txt))
print('{}'.format("".join(["\'"*len(port_txt)])))
print("")
print(".. list-table:: {}_port_table".format(fbase))
print(" :header-rows: 1")
print("")
print(indent("""* - Signal
- Direction
- Description""", 3))
for p in port_list:
print(indent(p.table_row_rst(), 3))
print("")
if True:
imp_txt = "Implementation and use"
print('{}'.format(imp_txt))
print('{}'.format("".join(["\'"*len(imp_txt)])))
print("")
print("The `portable`_ `Verilog`_")
print("implementation can be found in :ref:`{}_source`".format(fbase))
print("")
print(".. _`portable`: https://en.wikipedia.org/wiki/Software_portability")
print(".. _`Verilog`: https://en.wikipedia.org/wiki/Verilog")
print("")
if with_timing:
timing_txt = "Timing Diagram"
print('{}'.format(timing_txt))
print('{}'.format("".join(["\'"*len(timing_txt)])))
print("")
print("A `GTKWave`_-generated timing diagram is shown below:")
print("")
print(".. _`GTKWave`: https://gtkwave.sourceforge.net/")
print("")
print(".. _fig:{}_timing:".format(fbase))
print(".. figure:: {}_timing.png".format(fbase))
print(" :alt: Timing diagram")
print("")
def count_inout(port_list):
n_in, n_out = 0, 0
for p in port_list:
if p.io == "input":
n_in = n_in+1
elif p.io == "output":
n_out = n_out+1
else:
print("warning", p.io)
return n_in, n_out
def make_eps(port_list):
n_in, n_out = count_inout(port_list)
height = 24*max(n_in, n_out)
width = 192 # conceptually depends on length of port names
print("""%!PS-Adobe-3.0 EPSF-3.0
%%Title: symbol.eps
%%Creator: portfind.py
%%Pages: 1""")
print("%%BoundingBox:", "68 68 {} {}".format(112+width, 100+height)) # 244 220
print("""%%DocumentNeededResources: font Helvetica
%%EndComments
%%BeginProlog""")
print("""
/rshow { dup stringwidth pop neg 0 rmoveto show } def
/lpin { setlinewidth moveto gsave 7 -5 rmoveto show grestore -20 0 rlineto stroke } def
/rpin { setlinewidth moveto gsave -7 -5 rmoveto rshow grestore 20 0 rlineto stroke } def
/RT { % w h x y RT -
% draw a rectangle size w h at x y
moveto
dup 0 exch rlineto
exch 0 rlineto
neg 0 exch rlineto
closepath } def
/Helvetica findfont 15 scalefont setfont
""")
pitch = 24
y_offset = 72
y_center = y_offset + height/2
y_l = y_center+pitch*n_in/2
y_r = y_center+pitch*n_out/2
x_l = 90
for p in port_list:
if p.io == "input":
x = x_l
cmd = "lpin"
y = y_l
y_l = y_l - pitch
elif p.io == "output":
x = 90+width
cmd = "rpin"
y = y_r
y_r = y_r - pitch
if p.msb == 0 and p.lsb == 0:
w = 1 # single wire
else:
w = 3 # bus
print("({}) {} {} {} {}".format(p.ident, int(x), int(y), int(w), cmd))
print("1 setlinewidth {} {} {} {} RT stroke".format(width, height+24, x_l, y_offset))
print("""
showpage
%%Trailer
%%EOF""")
def svg_line(x0, y0, x1, y1, w):
print("<line x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\" stroke=\"blue\" stroke-width=\"{}\" />"
.format(x0, y0, x1, y1, w))
def svg_box(dx, dy, x0, y0):
svg_line(x0, y0, x0+dx, y0, 2)
svg_line(x0, y0+dy, x0+dx, y0+dy, 2)
svg_line(x0, y0, x0, y0+dy, 2)
svg_line(x0+dx, y0, x0+dx, y0+dy, 2)
def svg_port(ident, x, y, w, cmd):
# print("({}) {} {} {} {}".format((ident, x, y, w, cmd)
sgn = 1 if cmd == "lpin" else -1
svg_line(x, y, x-20*sgn, y, w)
align = "start" if cmd == "lpin" else "end"
print("<text x=\"{}\" y=\"{}\" font-family=\"Verdana, sans-serif\" "
"font-size=\"16\" text-anchor=\"{}\">{}</text>".format(x+7*sgn, y+5, align, ident))
def make_svg(port_list):
n_in, n_out = count_inout(port_list)
height = 24*max(n_in, n_out)
width = 192 # conceptually depends on length of port names
print('<?xml version="1.0" encoding="UTF-8" ?>')
print('<svg xmlns="http://www.w3.org/2000/svg" version="1.1">')
pitch = 24
y_offset = 72
y_center = y_offset + height/2
y_l = y_center+pitch*n_in/2
y_r = y_center+pitch*n_out/2
x_l = 90
for p in port_list:
if p.io == "input":
x = x_l
cmd = "lpin"
y = y_l
y_l = y_l - pitch
elif p.io == "output":
x = 90+width
cmd = "rpin"
y = y_r
y_r = y_r - pitch
if p.msb == 0 and p.lsb == 0:
w = 1 # single wire
else:
w = 3 # bus
svg_port(p.ident, x, y, w, cmd)
svg_box(width, height+24, x_l, y_offset)
print('</svg>')
def main():
import argparse
parser = argparse.ArgumentParser(description="Generate documentation from verilog files")
parser.add_argument("--gen-eps", default=False, action="store_true",
help="Generate .eps block diagram from verilog file")
parser.add_argument("--gen-svg", default=False, action="store_true",
help="Generate .svg block diagram from verilog file")
parser.add_argument("--gen-html", default=False, action="store_true",
help="Generate .html documentation from verilog file")
parser.add_argument("--gen-rst", default=False, action="store_true",
help="Generate .rst documentation from verilog file")
parser.add_argument("--gen-src-rst", default=False, action="store_true",
help="Generate .rst source file from verilog file")
parser.add_argument("--rst-with-timing", default=False, action="store_true",
help="Add timing diagram to .rst documentation (only affects .rst files)")
parser.add_argument("file", default="", help="Verilog input file")
cmd_args = parser.parse_args()
do_eps = cmd_args.gen_eps
do_svg = cmd_args.gen_svg
do_html = cmd_args.gen_html
do_rst = cmd_args.gen_rst
do_src_rst = cmd_args.gen_src_rst
rst_with_timing = cmd_args.rst_with_timing
fname = cmd_args.file
ifile = open(fname, 'r')
fdata = ifile.read()
port_list = []
param_list = []
mod_comment_list = []
try_mod_desc = True
for line in fdata.split('\n'):
# Avoid parsing more than 1 module per file. This confuses
# our current way of parsing with
if parse_endmodule(line.strip()):
break
if line.startswith("`timescale "): # a lot of modules start with this
continue # just ignore it
if try_mod_desc:
c = parse_whole_line_comment_or_blank(line.strip())
if c:
mod_comment_list.append(c)
else:
try_mod_desc = False
continue
else:
p = parse_vline_port(line.strip())
if p:
port_list.append(p)
else:
p = parse_vline_param(line.strip())
if p:
param_list.append(p)
if False:
for p in param_list+port_list:
p.xprint()
if do_eps:
make_eps(port_list)
elif do_svg:
make_svg(port_list)
elif do_html:
make_html(fname, param_list, port_list)
elif do_src_rst:
make_src_rst(fname)
elif do_rst:
make_rst(fname, param_list, port_list, mod_comment_list, rst_with_timing)
if __name__ == "__main__":
main()
|