3 ## @package thtml2doxy_clang
4 # Translates THtml C++ comments to Doxygen using libclang as parser.
6 # This code relies on Python bindings for libclang: libclang's interface is pretty unstable, and
7 # its Python bindings are unstable as well.
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.
12 # This code (expecially AST traversal) was inspired by:
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
22 # `thtml2doxy_clang file1 [file2 [file3...]]`
24 # @author Dario Berzano <dario.berzano@cern.ch>
36 ## Brain-dead color output for terminal.
40 return self.color('\033[31m')
43 return self.color('\033[32m')
46 return self.color('\033[33m')
49 return self.color('\033[34m')
52 return self.color('\033[35m')
55 return self.color('\033[36m')
58 return c + self + '\033[m'
64 def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
66 self.first_line = first_line
67 self.first_col = first_col
68 self.last_line = last_line
69 self.last_col = last_col
73 def has_comment(self, line):
74 return line >= self.first_line and line <= self.last_line
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)
80 ## Traverse the AST recursively starting from the current cursor.
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):
87 text = cursor.spelling or cursor.displayname
88 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
91 for i in range(0, recursion):
94 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD:
96 # cursor ran into a C++ method
97 logging.debug( "%s%s(%s)" % (indent, Colt(kind).magenta(), Colt(text).blue()) )
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
102 in_compound_stmt = False
103 expect_comment = False
107 comment_function = text
108 comment_line_start = -1
109 comment_line_end = -1
110 comment_col_start = -1
114 for token in cursor.get_tokens():
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
123 in_compound_stmt = False
126 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
127 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
133 extent = token.extent
134 line_start = extent.start.line
135 line_end = extent.end.line
137 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
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
144 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
145 comment_indent = extent.start.column-1
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') )
152 # multiline comments are parsed in one go, therefore don't expect subsequent comments
153 if line_end - line_start > 0:
155 expect_comment = False
159 expect_comment = False
163 comment = refactor_comment( comment )
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) )
170 comment_line_start = -1
171 comment_line_end = -1
172 comment_col_start = -1
181 logging.debug( "%s%s(%s)" % (indent, kind, text) )
183 for child_cursor in cursor.get_children():
184 traverse_ast(child_cursor, comments, recursion+1)
187 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
189 # @param comment An array containing the lines of the original comment
190 def refactor_comment(comment):
192 recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
196 wait_first_non_blank = True
197 for line_comment in comment:
198 mcomm = re.search( recomm, line_comment )
200 new_line_comment = mcomm.group(2)
201 if new_line_comment == '':
204 if insert_blank and not wait_first_non_blank:
205 new_comment.append('')
207 wait_first_non_blank = False
208 new_comment.append( new_line_comment )
210 assert False, 'Comment regexp does not match'
215 ## Rewrites all comments from the given file handler.
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):
227 if len(comments) > 0:
234 line_num = line_num + 1
236 if comm and comm.has_comment( line_num ):
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' )
253 for i in range(0,comments[cur_comment].indent):
254 text_indent = text_indent + ' '
256 for lc in comments[cur_comment].lines:
257 fhout.write( "%s/// %s\n" % (text_indent, lc) );
261 cur_comment = cur_comment + 1
262 if cur_comment < len(comments):
263 comm = comments[cur_comment]
267 line_out = line.rstrip('\n')
270 if line_out.strip() != '':
271 fhout.write( line_out + '\n' )
273 fhout.write( line_out + '\n' )
276 ## The main function.
278 # Return value is the executable's return value.
281 # Setup logging on stderr
282 log_level = logging.INFO
285 format='%(levelname)-8s %(funcName)-20s %(message)s',
289 # Parse command-line options
290 output_on_stdout = False
292 opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
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')
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
304 assert False, 'Unhandled argument'
305 except getopt.GetoptError as e:
306 logging.fatal('Invalid arguments: %s' % e)
309 logging.getLogger('').setLevel(log_level)
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'
317 libclang_found = False
319 for lib in libclang_locations:
320 if os.path.isfile(lib):
321 clang.cindex.Config.set_library_file(lib)
322 libclang_found = True
325 if not libclang_found:
326 logging.fatal('Cannot find libclang')
329 # Loop over all files
332 logging.info('Input file: %s' % Colt(fn).magenta())
333 index = clang.cindex.Index.create()
334 translation_unit = index.parse(fn, args=['-x', 'c++'])
337 traverse_ast( translation_unit.cursor, comments )
339 logging.debug("Comment found for %s:" % Colt(c.func).magenta())
342 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
343 "{%s}" % Colt(l).cyan()
349 with open(fn, 'r') as fhin:
350 rewrite_comments( fhin, sys.stdout, comments )
352 fn_back = fn + '.thtml2doxy_backup'
353 os.rename( fn, fn_back )
355 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
356 rewrite_comments( fhin, fhout, comments )
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)
366 if __name__ == '__main__':
367 sys.exit( main( sys.argv[1:] ) )