aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/Documentation/sphinx/cdoc.py
blob: 318e9b23626eb26086b47d69e8b7689e4e0596c6 (plain)
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
#!/usr/bin/env python
# SPDX_License-Identifier: MIT
#
# Copyright (C) 2018 Luc Van Oostenryck <luc.vanoostenryck@gmail.com>
#

"""
///
// Sparse source files may contain documentation inside block-comments
// specifically formatted::
//
// 	///
// 	// Here is some doc
// 	// and here is some more.
//
// More precisely, a doc-block begins with a line containing only ``///``
// and continues with lines beginning by ``//`` followed by either a space,
// a tab or nothing, the first space after ``//`` is ignored.
//
// For functions, some additional syntax must be respected inside the
// block-comment::
//
// 	///
// 	// <mandatory short one-line description>
// 	// <optional blank line>
// 	// @<1st parameter's name>: <description>
// 	// @<2nd parameter's name>: <long description
// 	// <tab>which needs multiple lines>
// 	// @return: <description> (absent for void functions)
// 	// <optional blank line>
// 	// <optional long multi-line description>
// 	int somefunction(void *ptr, int count);
//
// Inside the description fields, parameter's names can be referenced
// by using ``@<parameter name>``. A function doc-block must directly precede
// the function it documents. This function can span multiple lines and
// can either be a function prototype (ending with ``;``) or a
// function definition.
//
// Some future versions will also allow to document structures, unions,
// enums, typedefs and variables.
//
// This documentation can be extracted into a .rst document by using
// the *autodoc* directive::
//
// 	.. c:autodoc:: file.c
//

"""

import re

class Lines:
	def __init__(self, lines):
		# type: (Iterable[str]) -> None
		self.index = 0
		self.lines = lines
		self.last = None
		self.back = False

	def __iter__(self):
		# type: () -> Lines
		return self

	def memo(self):
		# type: () -> Tuple[int, str]
		return (self.index, self.last)

	def __next__(self):
		# type: () -> Tuple[int, str]
		if not self.back:
			self.last = next(self.lines).rstrip()
			self.index += 1
		else:
			self.back = False
		return self.memo()
	def next(self):
		return self.__next__()

	def undo(self):
		# type: () -> None
		self.back = True

def readline_multi(lines, line):
	# type: (Lines, str) -> str
	try:
		while True:
			(n, l) = next(lines)
			if not l.startswith('//\t'):
				raise StopIteration
			line += '\n' + l[3:]
	except:
		lines.undo()
	return line

def readline_delim(lines, delim):
	# type: (Lines, Tuple[str, str]) -> Tuple[int, str]
	try:
		(lineno, line) = next(lines)
		if line == '':
			raise StopIteration
		while line[-1] not in delim:
			(n, l) = next(lines)
			line += ' ' + l.lstrip()
	except:
		line = ''
	return (lineno, line)


def process_block(lines):
	# type: (Lines) -> Dict[str, Any]
	info = { }
	tags = []
	desc = []
	state = 'START'

	(n, l) = lines.memo()
	#print('processing line ' + str(n) + ': ' + l)

	## is it a single line comment ?
	m = re.match(r"^///\s+(.+)$", l)	# /// ...
	if m:
		info['type'] = 'single'
		info['desc'] = (n, m.group(1).rstrip())
		return info

	## read the multi line comment
	for (n, l) in lines:
		#print('state %d: %4d: %s' % (state, n, l))
		if l.startswith('// '):
			l = l[3:]					## strip leading '// '
		elif l.startswith('//\t') or l == '//':
			l = l[2:]					## strip leading '//'
		else:
			lines.undo()				## end of doc-block
			break

		if state == 'START':			## one-line short description
			info['short'] = (n ,l)
			state = 'PRE-TAGS'
		elif state == 'PRE-TAGS':		## ignore empty line
			if l != '':
				lines.undo()
				state = 'TAGS'
		elif state == 'TAGS':			## match the '@tagnames'
			m = re.match(r"^@([\w-]*)(:?\s*)(.*)", l)
			if m:
				tag = m.group(1)
				sep = m.group(2)
				## FIXME/ warn if sep != ': '
				l = m.group(3)
				l = readline_multi(lines, l)
				tags.append((n, tag, l))
			else:
				lines.undo()
				state = 'PRE-DESC'
		elif state == 'PRE-DESC':		## ignore the first empty lines
			if l != '':					## or first line of description
				desc = [n, l]
				state = 'DESC'
		elif state == 'DESC':			## remaining lines -> description
			desc.append(l)
		else:
			pass

	## fill the info
	if len(tags):
		info['tags'] = tags
	if len(desc):
		info['desc'] = desc

	## read the item (function only for now)
	(n, line) = readline_delim(lines, (')', ';'))
	if len(line):
		line = line.rstrip(';')
		#print('function: %4d: %s' % (n, line))
		info['type'] = 'func'
		info['func'] = (n, line)
	else:
		info['type'] = 'bloc'

	return info

def process_file(f):
	# type: (TextIOWrapper) -> List[Dict[str, Any]]
	docs = []
	lines = Lines(f)
	for (n, l) in lines:
		#print("%4d: %s" % (n, l))
		if l.startswith('///'):
			info = process_block(lines)
			docs.append(info)

	return docs

def decorate(l):
	# type: (str) -> str
	l = re.sub(r"@(\w+)", "**\\1**", l)
	return l

def convert_to_rst(info):
	# type: (Dict[str, Any]) -> List[Tuple[int, str]]
	lst = []
	#print('info= ' + str(info))
	typ = info.get('type', '???')
	if typ == '???':
		## uh ?
		pass
	elif typ == 'bloc':
		if 'short' in info:
			(n, l) = info['short']
			lst.append((n, l))
		if 'desc' in info:
			desc = info['desc']
			n = desc[0] - 1
			desc.append('')
			for i in range(1, len(desc)):
				l = desc[i]
				lst.append((n+i, l))
				# auto add a blank line for a list
				if re.search(r":$", desc[i]) and re.search(r"\S", desc[i+1]):
					lst.append((n+i, ''))

	elif typ == 'func':
		(n, l) = info['func']
		l = '.. c:function:: ' + l
		lst.append((n, l + '\n'))
		if 'short' in info:
			(n, l) = info['short']
			l = l[0].capitalize() + l[1:].strip('.')
			l = '\t' + l + '.'
			lst.append((n, l + '\n'))
		if 'tags' in info:
			for (n, name, l) in info.get('tags', []):
				if name != 'return':
					name = 'param ' + name
				l = decorate(l)
				l = '\t:%s: %s' % (name, l)
				l = '\n\t\t'.join(l.split('\n'))
				lst.append((n, l))
			lst.append((n+1, ''))
		if 'desc' in info:
			desc = info['desc']
			n = desc[0]
			r = ''
			for l in desc[1:]:
				l = decorate(l)
				r += '\t' + l + '\n'
			lst.append((n, r))
	return lst

def extract(f, filename):
	# type: (TextIOWrapper, str) -> List[Tuple[int, str]]
	res = process_file(f)
	res = [ i for r in res for i in convert_to_rst(r) ]
	return res

def dump_doc(lst):
	# type: (List[Tuple[int, str]]) -> None
	for (n, lines) in lst:
		for l in lines.split('\n'):
			print('%4d: %s' % (n, l))
			n += 1

if __name__ == '__main__':
	""" extract the doc from stdin """
	import sys

	dump_doc(extract(sys.stdin, '<stdin>'))


from sphinx.ext.autodoc import AutodocReporter
import docutils
import os
class CDocDirective(docutils.parsers.rst.Directive):
	required_argument = 1
	optional_arguments = 1
	has_content = False
	option_spec = {
	}

	def run(self):
		env = self.state.document.settings.env
		filename = os.path.join(env.config.cdoc_srcdir, self.arguments[0])
		env.note_dependency(os.path.abspath(filename))

		## create a (view) list from the extracted doc
		lst = docutils.statemachine.ViewList()
		f = open(filename, 'r')
		for (lineno, lines) in extract(f, filename):
			for l in lines.split('\n'):
				lst.append(l.expandtabs(8), filename, lineno)
				lineno += 1

		## let parse this new reST content
		memo = self.state.memo
		save = memo.reporter, memo.title_styles, memo.section_level
		memo.reporter = AutodocReporter(lst, memo.reporter)
		node = docutils.nodes.section()
		try:
			self.state.nested_parse(lst, 0, node, match_titles=1)
		finally:
			memo.reporter, memo.title_styles, memo.section_level = save
		return node.children

def setup(app):
	app.add_config_value('cdoc_srcdir', None, 'env')
	app.add_directive_to_domain('c', 'autodoc', CDocDirective)

	return {
		'version': '1.0',
		'parallel_read_safe': True,
	}

# vim: tabstop=4