]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy_clang.py
doxy: optionally output conversion to stdout
[u/mrichter/AliRoot.git] / doxygen / thtml2doxy_clang.py
1 #!/usr/bin/env python
2
3 ## @package thtml2doxy_clang
4 #  Translates THtml C++ comments to Doxygen using libclang as parser.
5 #
6 #  This code relies on Python bindings for libclang: libclang's interface is pretty unstable, and
7 #  its Python bindings are unstable as well.
8 #
9 #  AST (Abstract Source Tree) traversal is performed entirely using libclang used as a C++ parser,
10 #  instead of attempting to write a parser ourselves.
11 #
12 #  This code (expecially AST traversal) was inspired by:
13 #
14 #   - [Implementing a code generator with libclang](http://szelei.me/code-generator/)
15 #     (this refers to API calls used here)
16 #   - [Parsing C++ in Python with Clang](http://eli.thegreenplace.net/2011/07/03/parsing-c-in-python-with-clang)
17 #     (outdated, API calls described there do not work anymore, but useful to understand some basic
18 #     concepts)
19 #
20 #  Usage:
21 #
22 #    `thtml2doxy_clang file1 [file2 [file3...]]`
23 #
24 #  @author Dario Berzano <dario.berzano@cern.ch>
25 #  @date 2014-12-05
26
27
28 import sys
29 import os
30 import re
31 import logging
32 import getopt
33 import clang.cindex
34
35
36 ## Brain-dead color output for terminal.
37 class Colt(str):
38
39   def red(self):
40     return self.color('\033[31m')
41
42   def green(self):
43     return self.color('\033[32m')
44
45   def yellow(self):
46     return self.color('\033[33m')
47
48   def blue(self):
49     return self.color('\033[34m')
50
51   def magenta(self):
52     return self.color('\033[35m')
53
54   def cyan(self):
55     return self.color('\033[36m')
56
57   def color(self, c):
58     return c + self + '\033[m'
59
60
61 ## Comment.
62 class Comment:
63
64   def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
65     self.lines = lines
66     self.first_line = first_line
67     self.first_col = first_col
68     self.last_line = last_line
69     self.last_col = last_col
70     self.indent = indent
71     self.func = func
72
73   def has_comment(self, line):
74     return line >= self.first_line and line <= self.last_line
75
76   def __str__(self):
77     return "<Comment for %s: [%d,%d:%d,%d] %s>" % (self.func, self.first_line, self.first_col, self.last_line, self.last_col, self.lines)
78
79
80 ## Traverse the AST recursively starting from the current cursor.
81 #
82 #  @param cursor    A Clang parser cursor
83 #  @param comments  Array of comments found (of class Comment)
84 #  @param recursion Current recursion depth
85 def traverse_ast(cursor, comments, recursion=0):
86
87   text = cursor.spelling or cursor.displayname
88   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
89
90   indent = ''
91   for i in range(0, recursion):
92     indent = indent + '  '
93
94   if cursor.kind == clang.cindex.CursorKind.CXX_METHOD:
95
96     # cursor ran into a C++ method
97     logging.debug( "%s%s(%s)" % (indent, Colt(kind).magenta(), Colt(text).blue()) )
98
99     # we are looking for the following structure: method -> compound statement -> comment, i.e. we
100     # need to extract the first comment in the compound statement composing the method
101
102     in_compound_stmt = False
103     expect_comment = False
104     emit_comment = False
105
106     comment = []
107     comment_function = text
108     comment_line_start = -1
109     comment_line_end = -1
110     comment_col_start = -1
111     comment_col_end = -1
112     comment_indent = -1
113
114     for token in cursor.get_tokens():
115
116       if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
117         if not in_compound_stmt:
118           in_compound_stmt = True
119           expect_comment = True
120           comment_line_end = -1
121       else:
122         if in_compound_stmt:
123           in_compound_stmt = False
124           emit_comment = True
125
126       # tkind = str(token.kind)[str(token.kind).index('.')+1:]
127       # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
128
129       if in_compound_stmt:
130
131         if expect_comment:
132
133           extent = token.extent
134           line_start = extent.start.line
135           line_end = extent.end.line
136
137           if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
138             pass
139
140           elif token.kind == clang.cindex.TokenKind.COMMENT and (comment_line_end == -1 or (line_start == comment_line_end+1 and line_end-line_start == 0)):
141             comment_line_end = line_end
142             comment_col_end = extent.end.column
143
144             if comment_indent == -1 or (extent.start.column-1) < comment_indent:
145               comment_indent = extent.start.column-1
146
147             if comment_line_start == -1:
148               comment_line_start = line_start
149               comment_col_start = extent.start.column
150             comment.extend( token.spelling.split('\n') )
151
152             # multiline comments are parsed in one go, therefore don't expect subsequent comments
153             if line_end - line_start > 0:
154               emit_comment = True
155               expect_comment = False
156
157           else:
158             emit_comment = True
159             expect_comment = False
160
161       if emit_comment:
162
163         comment = refactor_comment( comment )
164
165         if len(comment) > 0:
166           logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
167           comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
168
169         comment = []
170         comment_line_start = -1
171         comment_line_end = -1
172         comment_col_start = -1
173         comment_col_end = -1
174         comment_indent = -1
175
176         emit_comment = False
177         break
178
179   else:
180
181     logging.debug( "%s%s(%s)" % (indent, kind, text) )
182
183   for child_cursor in cursor.get_children():
184     traverse_ast(child_cursor, comments, recursion+1)
185
186
187 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
188 #
189 #  @param comment An array containing the lines of the original comment
190 def refactor_comment(comment):
191
192   recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
193
194   new_comment = []
195   insert_blank = False
196   wait_first_non_blank = True
197   for line_comment in comment:
198     mcomm = re.search( recomm, line_comment )
199     if mcomm:
200       new_line_comment = mcomm.group(2)
201       if new_line_comment == '':
202         insert_blank = True
203       else:
204         if insert_blank and not wait_first_non_blank:
205           new_comment.append('')
206           insert_blank = False
207         wait_first_non_blank = False
208         new_comment.append( new_line_comment )
209     else:
210       assert False, 'Comment regexp does not match'
211
212   return new_comment
213
214
215 ## Rewrites all comments from the given file handler.
216 #
217 #  @param fhin     The file handler to read from
218 #  @param fhout    The file handler to write to
219 #  @param comments Array of comments
220 def rewrite_comments(fhin, fhout, comments):
221
222   line_num = 0
223   cur_comment = 0
224   in_comment = False
225   skip_empty = False
226
227   if len(comments) > 0:
228     comm = comments[0]
229   else:
230     comm = None
231
232   for line in fhin:
233
234     line_num = line_num + 1
235
236     if comm and comm.has_comment( line_num ):
237
238       if not in_comment:
239         in_comment = True
240
241         # extract the non-comment part and print it if it exists
242         non_comment = line[ 0:comments[cur_comment].first_col-1 ].rstrip()
243         if non_comment != '':
244           fhout.write( non_comment + '\n' )
245
246     else:
247       if in_comment:
248
249         in_comment = False
250
251         # dumping comments
252         text_indent = ''
253         for i in range(0,comments[cur_comment].indent):
254           text_indent = text_indent + ' '
255
256         for lc in comments[cur_comment].lines:
257           fhout.write( "%s/// %s\n" % (text_indent, lc) );
258         fhout.write('\n')
259         skip_empty = True
260
261         cur_comment = cur_comment + 1
262         if cur_comment < len(comments):
263           comm = comments[cur_comment]
264         else:
265           comm = None
266
267       line_out = line.rstrip('\n')
268       if skip_empty:
269         skip_empty = False
270         if line_out.strip() != '':
271           fhout.write( line_out + '\n' )
272       else:
273         fhout.write( line_out + '\n' )
274
275
276 ## The main function.
277 #
278 #  Return value is the executable's return value.
279 def main(argv):
280
281   # Setup logging on stderr
282   log_level = logging.INFO
283   logging.basicConfig(
284     level=log_level,
285     format='%(levelname)-8s %(funcName)-20s %(message)s',
286     stream=sys.stderr
287   )
288
289   # Parse command-line options
290   output_on_stdout = False
291   try:
292     opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
293     for o, a in opts:
294       if o == '--debug':
295         log_level = getattr( logging, a.upper(), None )
296         if not isinstance(log_level, int):
297           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
298       elif o == '-d':
299         log_level = logging.DEBUG
300       elif o == '-o' or o == '--stdout':
301         logging.debug('Output on stdout instead of replacing original files')
302         output_on_stdout = True
303       else:
304         assert False, 'Unhandled argument'
305   except getopt.GetoptError as e:
306     logging.fatal('Invalid arguments: %s' % e)
307     return 1
308
309   logging.getLogger('').setLevel(log_level)
310
311   # Attempt to load libclang from a list of known locations
312   libclang_locations = [
313     '/usr/lib/llvm-3.5/lib/libclang.so.1',
314     '/usr/lib/libclang.so',
315     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
316   ]
317   libclang_found = False
318
319   for lib in libclang_locations:
320     if os.path.isfile(lib):
321       clang.cindex.Config.set_library_file(lib)
322       libclang_found = True
323       break
324
325   if not libclang_found:
326     logging.fatal('Cannot find libclang')
327     return 1
328
329   # Loop over all files
330   for fn in args:
331
332     logging.info('Input file: %s' % Colt(fn).magenta())
333     index = clang.cindex.Index.create()
334     translation_unit = index.parse(fn, args=['-x', 'c++'])
335
336     comments = []
337     traverse_ast( translation_unit.cursor, comments )
338     for c in comments:
339       logging.debug("Comment found for %s:" % Colt(c.func).magenta())
340       for l in c.lines:
341         logging.debug(
342           Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
343           "{%s}" % Colt(l).cyan()
344         )
345
346     try:
347
348       if output_on_stdout:
349         with open(fn, 'r') as fhin:
350           rewrite_comments( fhin, sys.stdout, comments )
351       else:
352         fn_back = fn + '.thtml2doxy_backup'
353         os.rename( fn, fn_back )
354
355         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
356           rewrite_comments( fhin, fhout, comments )
357
358         os.remove( fn_back )
359         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
360     except (IOError,OSError) as e:
361       logging.error('File operation failed: %s' % e)
362
363   return 0
364
365
366 if __name__ == '__main__':
367   sys.exit( main( sys.argv[1:] ) )