Debian Codegraph @

easel/devkit/autodoc.py

raw symbols SCIP
1 #! /usr/bin/env python3
2
3 # autodoc.py
4 #
5 # Extract function documentation from a .c file and output it in a
6 # Markdown file. Assumes that the .c file uses function headers that
7 # conform to Easel code style.
8 #
9 # Usage: ./autodoc.py <.c file>
10 # Example: ./autodoc.py esl_module.c > esl_module_functions.md
11 #
12 #
13 # Replaces old Perl autodoc, which converted to LaTeX. I'm moving
14 # toward online developer documentation, and Markdown. This simplifies
15 # the conversion; we don't have to protect special LaTeX characters
16 # (#_$) for example.
17 #
18 # SRE, Sun 27 Jan 2019
19
20 import os
21 import sys
22 import re
23 import getopt
24
25 def process(text):
26 """
27 Remove the leading " * " prefixes from a Purpose, Returns, or Throws
28 multiiline block of text that we've just pulled out of the function header.
29
30 Convert <text> to `text` (Markdown code).
31 """
32 text = re.sub(r'^ \*[ \t]+(\S)', r'\1', text, flags=re.MULTILINE) # remove leading " * "
33 text = re.sub(r'^ \*', r'', text, flags=re.MULTILINE) # remove " *" alone
34 text = re.sub(r'<(\S|\S.*?\S)>', r'`\1`', text, flags=re.MULTILINE | re.DOTALL) # convert <text> to `text`
35 return text
36
37 def output_argtable(argtext):
38 print("| arg | description |")
39 print("|------|-------------|")
40 for m in re.finditer(r'^(\S+)\s*[:-]\s*(.+?)\s*$', argtext, flags=re.MULTILINE):
41 print("| `{0}` | {1} |".format(m.group(1), m.group(2)))
42 print("\n")
43
44 def main():
45 try: (opts, args) = getopt.getopt(sys.argv[1:], "t")
46 except: sys.exit("Usage: autodoc.py [-t] <.c file>")
47 if (len(args) != 1): sys.exit("Usage: autodoc.py [-t] <.c file>")
48
49 cfile = args[0]
50 do_table = False
51 for opt, arg in opts:
52 if opt == '-t': do_table = True
53
54 if not os.path.isfile(cfile): exit(".c file {0} not found".format(cfile))
55 fp = open(cfile)
56 text = fp.read()
57
58 if do_table:
59 print('| {0:30s} | {1:60s} |'.format('Function', 'Synopsis'))
60 print('|{0:-^32s}|{1:-^62s}|'.format('', ''))
61
62
63 # /* Function: ... */ ... } to a blank line. Grabs header + implementation(s)...
64 # vv vvvvvvvv vv vvv vvv v... or, grabs subheading line in a comment
65 for m in re.finditer(r'^(/\*\s+Function:.+?^ \*/)(.+?^\})\s*$^\s*$|^\s*\*#\s*\d+\..+?$\s*', text, flags=re.MULTILINE | re.DOTALL):
66 if m.group(0).startswith('/*'):
67 header = m.group(1) # comment header "/* Function: ... */"
68 impl = m.group(2) # implementation(s) "int myfunc(args){ }\nint func2(args){ }"
69
70 m = re.match(r'/\*\s+Function:\s*(.+)$', header, flags=re.MULTILINE) # Usually one function name, but could also be comma-delimited list
71 funcnames = [ a.lstrip().rstrip() for a in m.group(1).split(',') ]
72
73 m = re.search(r'^\s+\*\s+Synopsis:\s+(.+)$', header, flags=re.MULTILINE)
74 synopsis = process(m.group(1)) if m else None
75
76 m = re.search(r'^\s+\*\s+Args:\s+(.+?)(?:^ \*/|^ \* \S)', header, flags=re.MULTILINE | re.DOTALL)
77 argtext = process(m.group(1)) if m else None
78
79 m = re.search(r'^\s+\*\s+Purpose:\s+(.+?)(?:^ \*/|^ \* \S)', header, flags=re.MULTILINE | re.DOTALL)
80 purpose = process(m.group(1)) if m else None
81
82 m = re.search(r'^\s+\*\s+Returns:\s+(.+?)(?:^ \*/|^ \* \S)', header, flags=re.MULTILINE | re.DOTALL)
83 returns = process(m.group(1)) if m else None
84
85 m = re.search(r'^\s+\*\s+Throws:\s+(.+?)(?:^ \*/|^ \* \S)', header, flags=re.MULTILINE | re.DOTALL)
86 throws = process(m.group(1)) if m else None
87
88 # pull the call syntax (function name, arguments) out of the C implementation;
89 # <syntax> is a list of each documented function and its call syntax, "int foo(double bar)".
90 # nontrivial to do well with just regexps, without a real grammar parser,
91 # because we're covering the less common case where there's >1 function
92 # documented by a single header.
93 syntax = []
94 for fname in funcnames: # list of names like "esl_foo_Function()", with the (). Can also be esl_foo_{DFI}Function()", which needs expansion.
95 fname = fname.rstrip('()') # now just "esl_foo_Function" or "esl_foo_{DFI}Function()"
96 m = re.search(r'\{([DFILCWB]+)\}', fname) # "esl_foo_{DFI}Function()" case?
97 if m: # then expand it, one function name at a time
98 typelist = m.group(1) # "DFI" for example
99 for c in typelist:
100 expanded_fname = re.sub(r'\{([DFILCWB]+)\}', c, fname)
101 impl_pattern = r'^(\S+.+?)\s+' + expanded_fname + '\s*(\((?s:.+?)\))\s*\{'
102 m = re.search(impl_pattern, impl, flags=re.MULTILINE)
103 if m: syntax.append(m.group(1) + ' ' + expanded_fname + m.group(2))
104 else: exit("failed to parse out the syntax for {0}".format(expanded_fname))
105 else:
106 pattern1 = r'^(\S+.+?)\s+' + fname + '\s*(\((?s:.+?)\))\s*\{'
107 m = re.search(pattern1, impl, flags=re.MULTILINE)
108 if m: syntax.append(m.group(1) + ' ' + fname + m.group(2))
109 else: exit("failed to parse out the syntax for {0}".format(fname))
110
111 # Now we're done parsing one (or more) documented functions,
112 # and it's time to print whatever we're going to print.
113 #
114 # funcnames : list of one (or more) function names sharing the documentation
115 # synopsis : optional one-line description
116 # syntax : list of one (or more) "funcname(arg, arg)" call syntax
117 # purpose : optional documentation (Markdown format)
118 # argtext : optional argument table text (needs further processing)
119 # returns: : optional text about return status
120 # throws: : optional text about exceptions
121 #
122 if do_table:
123 if synopsis: print('| {0:30s} | {1:60s} |'.format('`{}`'.format(funcnames[0]), synopsis))
124 else: print('| {0:30s} | {1:60s} |'.format('`{}`'.format(funcnames[0]), ''))
125 else:
126 for a in funcnames: print("### `{0}`\n".format(a))
127 if synopsis: print("**{0}**\n".format(synopsis.rstrip()))
128 for s in syntax: print("`{0}`\n".format(s))
129 if argtext: output_argtable(argtext)
130 if purpose: print(purpose);
131 if returns: print("Returns: {0}".format(returns))
132 if throws: print("Throws: {0}".format(throws))
133 print("------")
134
135 else: # or, we're a section heading.
136 m = re.match('^\s*\*#\s*(\d+\..+)', m.group(0))
137 secheading = m.group(1)
138
139 if not do_table:
140 print("## {0}\n".format(secheading))
141
142
143 if __name__ == "__main__":
144 main()
145
146
147
148
149
150
151
152
153
154
155
156