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 ## Parses method comments.
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):
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
89 in_compound_stmt = False
90 expect_comment = False
94 comment_function = cursor.spelling or cursor.displayname
95 comment_line_start = -1
97 comment_col_start = -1
101 for token in cursor.get_tokens():
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
110 in_compound_stmt = False
113 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
114 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
120 extent = token.extent
121 line_start = extent.start.line
122 line_end = extent.end.line
124 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
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
131 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
132 comment_indent = extent.start.column-1
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') )
139 # multiline comments are parsed in one go, therefore don't expect subsequent comments
140 if line_end - line_start > 0:
142 expect_comment = False
146 expect_comment = False
150 comment = refactor_comment( comment )
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) )
157 comment_line_start = -1
158 comment_line_end = -1
159 comment_col_start = -1
167 ## Traverse the AST recursively starting from the current cursor.
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):
174 text = cursor.spelling or cursor.displayname
175 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
178 for i in range(0, recursion):
179 indent = indent + ' '
181 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
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)
189 logging.debug( "%5d %s%s(%s)" % (cursor.extent.start.line, indent, kind, text) )
191 for child_cursor in cursor.get_children():
192 traverse_ast(child_cursor, comments, recursion+1)
195 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
197 # @param comment An array containing the lines of the original comment
198 def refactor_comment(comment):
200 recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
204 wait_first_non_blank = True
205 for line_comment in comment:
206 mcomm = re.search( recomm, line_comment )
208 new_line_comment = mcomm.group(2)
209 if new_line_comment == '':
212 if insert_blank and not wait_first_non_blank:
213 new_comment.append('')
215 wait_first_non_blank = False
216 new_comment.append( new_line_comment )
218 assert False, 'Comment regexp does not match'
223 ## Rewrites all comments from the given file handler.
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):
235 if len(comments) > 0:
242 line_num = line_num + 1
244 if comm and comm.has_comment( line_num ):
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' )
261 for i in range(0,comments[cur_comment].indent):
262 text_indent = text_indent + ' '
264 for lc in comments[cur_comment].lines:
265 fhout.write( "%s/// %s\n" % (text_indent, lc) );
269 cur_comment = cur_comment + 1
270 if cur_comment < len(comments):
271 comm = comments[cur_comment]
275 line_out = line.rstrip('\n')
278 if line_out.strip() != '':
279 fhout.write( line_out + '\n' )
281 fhout.write( line_out + '\n' )
284 ## The main function.
286 # Return value is the executable's return value.
289 # Setup logging on stderr
290 log_level = logging.INFO
293 format='%(levelname)-8s %(funcName)-20s %(message)s',
297 # Parse command-line options
298 output_on_stdout = False
300 opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
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')
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
312 assert False, 'Unhandled argument'
313 except getopt.GetoptError as e:
314 logging.fatal('Invalid arguments: %s' % e)
317 logging.getLogger('').setLevel(log_level)
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'
325 libclang_found = False
327 for lib in libclang_locations:
328 if os.path.isfile(lib):
329 clang.cindex.Config.set_library_file(lib)
330 libclang_found = True
333 if not libclang_found:
334 logging.fatal('Cannot find libclang')
337 # Loop over all files
340 logging.info('Input file: %s' % Colt(fn).magenta())
341 index = clang.cindex.Index.create()
342 translation_unit = index.parse(fn, args=['-x', 'c++'])
345 traverse_ast( translation_unit.cursor, comments )
347 logging.debug("Comment found for %s:" % Colt(c.func).magenta())
350 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
351 "{%s}" % Colt(l).cyan()
357 with open(fn, 'r') as fhin:
358 rewrite_comments( fhin, sys.stdout, comments )
360 fn_back = fn + '.thtml2doxy_backup'
361 os.rename( fn, fn_back )
363 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
364 rewrite_comments( fhin, fhout, comments )
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)
374 if __name__ == '__main__':
375 sys.exit( main( sys.argv[1:] ) )