doxy: optionally output conversion to stdout
[u/mrichter/AliRoot.git] / doxygen / thtml2doxy_clang.py
CommitLineData
a4057fc9 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
28import sys
29import os
30import re
62671ba0 31import logging
32import getopt
a4057fc9 33import clang.cindex
34
35
36## Brain-dead color output for terminal.
37class 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
10f6b9f8 61## Comment.
62class Comment:
63
72604c43 64 def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
10f6b9f8 65 self.lines = lines
66 self.first_line = first_line
9220af47 67 self.first_col = first_col
10f6b9f8 68 self.last_line = last_line
9220af47 69 self.last_col = last_col
72604c43 70 self.indent = indent
10f6b9f8 71 self.func = func
72
72604c43 73 def has_comment(self, line):
74 return line >= self.first_line and line <= self.last_line
75
10f6b9f8 76 def __str__(self):
9220af47 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)
10f6b9f8 78
79
a4057fc9 80## Traverse the AST recursively starting from the current cursor.
81#
82# @param cursor A Clang parser cursor
10f6b9f8 83# @param comments Array of comments found (of class Comment)
a4057fc9 84# @param recursion Current recursion depth
10f6b9f8 85def traverse_ast(cursor, comments, recursion=0):
a4057fc9 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
62671ba0 97 logging.debug( "%s%s(%s)" % (indent, Colt(kind).magenta(), Colt(text).blue()) )
a4057fc9 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
533918c9 104 emit_comment = False
105
106 comment = []
107 comment_function = text
108 comment_line_start = -1
109 comment_line_end = -1
9220af47 110 comment_col_start = -1
111 comment_col_end = -1
72604c43 112 comment_indent = -1
a4057fc9 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
533918c9 120 comment_line_end = -1
a4057fc9 121 else:
122 if in_compound_stmt:
123 in_compound_stmt = False
533918c9 124 emit_comment = True
a4057fc9 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
9a13b5a2 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
533918c9 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
9220af47 142 comment_col_end = extent.end.column
4e465d49 143
72604c43 144 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
145 comment_indent = extent.start.column-1
146
533918c9 147 if comment_line_start == -1:
148 comment_line_start = line_start
9220af47 149 comment_col_start = extent.start.column
9eb7bab8 150 comment.extend( token.spelling.split('\n') )
a4057fc9 151
78aaad66 152 # multiline comments are parsed in one go, therefore don't expect subsequent comments
153 if line_end - line_start > 0:
533918c9 154 emit_comment = True
78aaad66 155 expect_comment = False
156
a4057fc9 157 else:
533918c9 158 emit_comment = True
a4057fc9 159 expect_comment = False
160
533918c9 161 if emit_comment:
162
9eb7bab8 163 comment = refactor_comment( comment )
533918c9 164
165 if len(comment) > 0:
10f6b9f8 166 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
72604c43 167 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
a4057fc9 168
533918c9 169 comment = []
170 comment_line_start = -1
171 comment_line_end = -1
9220af47 172 comment_col_start = -1
173 comment_col_end = -1
72604c43 174 comment_indent = -1
533918c9 175
176 emit_comment = False
177 break
a4057fc9 178
179 else:
180
62671ba0 181 logging.debug( "%s%s(%s)" % (indent, kind, text) )
a4057fc9 182
4e465d49 183 for child_cursor in cursor.get_children():
10f6b9f8 184 traverse_ast(child_cursor, comments, recursion+1)
a4057fc9 185
533918c9 186
4e465d49 187## Remove garbage from comments and convert special tags from THtml to Doxygen.
188#
9eb7bab8 189# @param comment An array containing the lines of the original comment
4e465d49 190def refactor_comment(comment):
a4057fc9 191
9eb7bab8 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
4e465d49 203 else:
9eb7bab8 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'
4e465d49 211
212 return new_comment
a4057fc9 213
214
72604c43 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
220def 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
a4057fc9 276## The main function.
277#
62671ba0 278# Return value is the executable's return value.
a4057fc9 279def main(argv):
280
62671ba0 281 # Setup logging on stderr
72604c43 282 log_level = logging.INFO
62671ba0 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
43ee56ee 290 output_on_stdout = False
62671ba0 291 try:
43ee56ee 292 opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
62671ba0 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
43ee56ee 300 elif o == '-o' or o == '--stdout':
301 logging.debug('Output on stdout instead of replacing original files')
302 output_on_stdout = True
62671ba0 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
a4057fc9 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:
62671ba0 326 logging.fatal('Cannot find libclang')
a4057fc9 327 return 1
328
329 # Loop over all files
62671ba0 330 for fn in args:
a4057fc9 331
533918c9 332 logging.info('Input file: %s' % Colt(fn).magenta())
a4057fc9 333 index = clang.cindex.Index.create()
334 translation_unit = index.parse(fn, args=['-x', 'c++'])
10f6b9f8 335
336 comments = []
337 traverse_ast( translation_unit.cursor, comments )
338 for c in comments:
72604c43 339 logging.debug("Comment found for %s:" % Colt(c.func).magenta())
10f6b9f8 340 for l in c.lines:
72604c43 341 logging.debug(
9220af47 342 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
10f6b9f8 343 "{%s}" % Colt(l).cyan()
344 )
a4057fc9 345
72604c43 346 try:
347
43ee56ee 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 )
72604c43 354
43ee56ee 355 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
356 rewrite_comments( fhin, fhout, comments )
72604c43 357
43ee56ee 358 os.remove( fn_back )
359 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
72604c43 360 except (IOError,OSError) as e:
361 logging.error('File operation failed: %s' % e)
362
a4057fc9 363 return 0
364
365
366if __name__ == '__main__':
62671ba0 367 sys.exit( main( sys.argv[1:] ) )