]> git.uio.no Git - u/mrichter/AliRoot.git/blob - doxygen/thtml2doxy_clang.py
doxy: also consider ctor/dtor
[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 ## Parses method comments.
81 #
82 #  @param cursor   Current libclang parser cursor
83 #  @param comments Array of comments: new ones will be appended there
84 def comment_method(cursor, comments):
85
86   # we are looking for the following structure: method -> compound statement -> comment, i.e. we
87   # need to extract the first comment in the compound statement composing the method
88
89   in_compound_stmt = False
90   expect_comment = False
91   emit_comment = False
92
93   comment = []
94   comment_function = cursor.spelling or cursor.displayname
95   comment_line_start = -1
96   comment_line_end = -1
97   comment_col_start = -1
98   comment_col_end = -1
99   comment_indent = -1
100
101   for token in cursor.get_tokens():
102
103     if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
104       if not in_compound_stmt:
105         in_compound_stmt = True
106         expect_comment = True
107         comment_line_end = -1
108     else:
109       if in_compound_stmt:
110         in_compound_stmt = False
111         emit_comment = True
112
113     # tkind = str(token.kind)[str(token.kind).index('.')+1:]
114     # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
115
116     if in_compound_stmt:
117
118       if expect_comment:
119
120         extent = token.extent
121         line_start = extent.start.line
122         line_end = extent.end.line
123
124         if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
125           pass
126
127         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)):
128           comment_line_end = line_end
129           comment_col_end = extent.end.column
130
131           if comment_indent == -1 or (extent.start.column-1) < comment_indent:
132             comment_indent = extent.start.column-1
133
134           if comment_line_start == -1:
135             comment_line_start = line_start
136             comment_col_start = extent.start.column
137           comment.extend( token.spelling.split('\n') )
138
139           # multiline comments are parsed in one go, therefore don't expect subsequent comments
140           if line_end - line_start > 0:
141             emit_comment = True
142             expect_comment = False
143
144         else:
145           emit_comment = True
146           expect_comment = False
147
148     if emit_comment:
149
150       comment = refactor_comment( comment )
151
152       if len(comment) > 0:
153         logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
154         comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
155
156       comment = []
157       comment_line_start = -1
158       comment_line_end = -1
159       comment_col_start = -1
160       comment_col_end = -1
161       comment_indent = -1
162
163       emit_comment = False
164       break
165
166
167 ## Traverse the AST recursively starting from the current cursor.
168 #
169 #  @param cursor    A Clang parser cursor
170 #  @param comments  Array of comments: new ones will be appended there
171 #  @param recursion Current recursion depth
172 def traverse_ast(cursor, comments, recursion=0):
173
174   text = cursor.spelling or cursor.displayname
175   kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
176
177   indent = ''
178   for i in range(0, recursion):
179     indent = indent + '  '
180
181   if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
182
183     # cursor ran into a C++ method
184     logging.debug( "%5d %s%s(%s)" % (cursor.extent.start.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
185     comment_method(cursor, comments)
186
187   else:
188
189     logging.debug( "%5d %s%s(%s)" % (cursor.extent.start.line, indent, kind, text) )
190
191   for child_cursor in cursor.get_children():
192     traverse_ast(child_cursor, comments, recursion+1)
193
194
195 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
196 #
197 #  @param comment An array containing the lines of the original comment
198 def refactor_comment(comment):
199
200   recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
201
202   new_comment = []
203   insert_blank = False
204   wait_first_non_blank = True
205   for line_comment in comment:
206     mcomm = re.search( recomm, line_comment )
207     if mcomm:
208       new_line_comment = mcomm.group(2)
209       if new_line_comment == '':
210         insert_blank = True
211       else:
212         if insert_blank and not wait_first_non_blank:
213           new_comment.append('')
214           insert_blank = False
215         wait_first_non_blank = False
216         new_comment.append( new_line_comment )
217     else:
218       assert False, 'Comment regexp does not match'
219
220   return new_comment
221
222
223 ## Rewrites all comments from the given file handler.
224 #
225 #  @param fhin     The file handler to read from
226 #  @param fhout    The file handler to write to
227 #  @param comments Array of comments
228 def rewrite_comments(fhin, fhout, comments):
229
230   line_num = 0
231   cur_comment = 0
232   in_comment = False
233   skip_empty = False
234
235   if len(comments) > 0:
236     comm = comments[0]
237   else:
238     comm = None
239
240   for line in fhin:
241
242     line_num = line_num + 1
243
244     if comm and comm.has_comment( line_num ):
245
246       if not in_comment:
247         in_comment = True
248
249         # extract the non-comment part and print it if it exists
250         non_comment = line[ 0:comments[cur_comment].first_col-1 ].rstrip()
251         if non_comment != '':
252           fhout.write( non_comment + '\n' )
253
254     else:
255       if in_comment:
256
257         in_comment = False
258
259         # dumping comments
260         text_indent = ''
261         for i in range(0,comments[cur_comment].indent):
262           text_indent = text_indent + ' '
263
264         for lc in comments[cur_comment].lines:
265           fhout.write( "%s/// %s\n" % (text_indent, lc) );
266         fhout.write('\n')
267         skip_empty = True
268
269         cur_comment = cur_comment + 1
270         if cur_comment < len(comments):
271           comm = comments[cur_comment]
272         else:
273           comm = None
274
275       line_out = line.rstrip('\n')
276       if skip_empty:
277         skip_empty = False
278         if line_out.strip() != '':
279           fhout.write( line_out + '\n' )
280       else:
281         fhout.write( line_out + '\n' )
282
283
284 ## The main function.
285 #
286 #  Return value is the executable's return value.
287 def main(argv):
288
289   # Setup logging on stderr
290   log_level = logging.INFO
291   logging.basicConfig(
292     level=log_level,
293     format='%(levelname)-8s %(funcName)-20s %(message)s',
294     stream=sys.stderr
295   )
296
297   # Parse command-line options
298   output_on_stdout = False
299   try:
300     opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
301     for o, a in opts:
302       if o == '--debug':
303         log_level = getattr( logging, a.upper(), None )
304         if not isinstance(log_level, int):
305           raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
306       elif o == '-d':
307         log_level = logging.DEBUG
308       elif o == '-o' or o == '--stdout':
309         logging.debug('Output on stdout instead of replacing original files')
310         output_on_stdout = True
311       else:
312         assert False, 'Unhandled argument'
313   except getopt.GetoptError as e:
314     logging.fatal('Invalid arguments: %s' % e)
315     return 1
316
317   logging.getLogger('').setLevel(log_level)
318
319   # Attempt to load libclang from a list of known locations
320   libclang_locations = [
321     '/usr/lib/llvm-3.5/lib/libclang.so.1',
322     '/usr/lib/libclang.so',
323     '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
324   ]
325   libclang_found = False
326
327   for lib in libclang_locations:
328     if os.path.isfile(lib):
329       clang.cindex.Config.set_library_file(lib)
330       libclang_found = True
331       break
332
333   if not libclang_found:
334     logging.fatal('Cannot find libclang')
335     return 1
336
337   # Loop over all files
338   for fn in args:
339
340     logging.info('Input file: %s' % Colt(fn).magenta())
341     index = clang.cindex.Index.create()
342     translation_unit = index.parse(fn, args=['-x', 'c++'])
343
344     comments = []
345     traverse_ast( translation_unit.cursor, comments )
346     for c in comments:
347       logging.debug("Comment found for %s:" % Colt(c.func).magenta())
348       for l in c.lines:
349         logging.debug(
350           Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
351           "{%s}" % Colt(l).cyan()
352         )
353
354     try:
355
356       if output_on_stdout:
357         with open(fn, 'r') as fhin:
358           rewrite_comments( fhin, sys.stdout, comments )
359       else:
360         fn_back = fn + '.thtml2doxy_backup'
361         os.rename( fn, fn_back )
362
363         with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
364           rewrite_comments( fhin, fhout, comments )
365
366         os.remove( fn_back )
367         logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
368     except (IOError,OSError) as e:
369       logging.error('File operation failed: %s' % e)
370
371   return 0
372
373
374 if __name__ == '__main__':
375   sys.exit( main( sys.argv[1:] ) )