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 ## A data member comment.
83 def __init__(self, text, is_transient, array_size, first_line, first_col, func):
85 self.is_transient = is_transient
86 self.array_size = array_size
87 self.first_line = first_line
88 self.first_col = first_col
91 def has_comment(self, line):
92 return line == self.first_line
101 if self.array_size is not None:
102 ars = '[%s] ' % self.array_size
106 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
109 ## A dummy comment that removes comment lines.
110 class RemoveComment(Comment):
112 def __init__(self, first_line, last_line):
113 self.first_line = first_line
114 self.last_line = last_line
115 self.func = '<remove>'
118 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
121 ## Parses method comments.
123 # @param cursor Current libclang parser cursor
124 # @param comments Array of comments: new ones will be appended there
125 def comment_method(cursor, comments):
127 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
128 # need to extract the first comment in the compound statement composing the method
130 in_compound_stmt = False
131 expect_comment = False
135 comment_function = cursor.spelling or cursor.displayname
136 comment_line_start = -1
137 comment_line_end = -1
138 comment_col_start = -1
142 for token in cursor.get_tokens():
144 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
145 if not in_compound_stmt:
146 in_compound_stmt = True
147 expect_comment = True
148 comment_line_end = -1
151 in_compound_stmt = False
154 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
155 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
161 extent = token.extent
162 line_start = extent.start.line
163 line_end = extent.end.line
165 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
168 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)):
169 comment_line_end = line_end
170 comment_col_end = extent.end.column
172 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
173 comment_indent = extent.start.column-1
175 if comment_line_start == -1:
176 comment_line_start = line_start
177 comment_col_start = extent.start.column
178 comment.extend( token.spelling.split('\n') )
180 # multiline comments are parsed in one go, therefore don't expect subsequent comments
181 if line_end - line_start > 0:
183 expect_comment = False
187 expect_comment = False
191 comment = refactor_comment( comment )
194 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
195 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
198 comment_line_start = -1
199 comment_line_end = -1
200 comment_col_start = -1
208 ## Parses comments to class data members.
210 # @param cursor Current libclang parser cursor
211 # @param comments Array of comments: new ones will be appended there
212 def comment_datamember(cursor, comments):
214 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
215 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
216 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
217 # definition is fully on one line, and we take the line number from cursor.location.
219 line_num = cursor.location.line
225 with open(str(cursor.location.file)) as fp:
228 cur_line = cur_line + 1
229 if cur_line == line_num:
234 assert found, 'A line that should exist was not found in file' % cursor.location.file
236 recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
237 recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
239 mcomm = re.search(recomm, raw)
241 member_name = cursor.spelling;
242 is_transient = mcomm.group(2) is not None
243 array_size = mcomm.group(4)
244 text = mcomm.group(5)
246 col_num = mcomm.start()+1;
248 if array_size is not None and prev is not None:
249 # ROOT arrays with comments already converted to Doxygen have the member description on the
251 mcomm_doxyary = re.search(recomm_doxyary, prev)
253 text = mcomm_doxyary.group(1)
254 comments.append(RemoveComment(line_num-1, line_num-1))
256 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
258 comments.append( MemberComment(
267 assert False, 'Regular expression does not match member comment'
270 ## Parses class description (beginning of file).
272 # The clang parser does not work in this case so we do it manually, but it is very simple: we keep
273 # the first consecutive sequence of single-line comments (//) we find - provided that it occurs
274 # before any other comment found so far in the file (the comments array is inspected to ensure
277 # Multi-line comments (/* ... */) are not considered as they are commonly used to display
280 # @param filename Name of the current file
281 # @param comments Array of comments: new ones will be appended there
282 def comment_classdesc(filename, comments):
284 recomm = r'^\s*///?\s*(.*?)\s*/*\s*$'
285 reclass_doxy = r'(?i)^\\class:?\s*(.*?)\s*$'
286 class_name_doxy = None
294 with open(filename, 'r') as fp:
298 line_num = line_num + 1
300 if raw.strip() == '':
302 end_line = line_num - 1
305 mcomm = re.search(recomm, raw)
308 if start_line == -1 and len(comment_lines) == 0:
310 # First line. Check that we do not overlap with other comments
311 comment_overlaps = False
313 if c.has_comment(line_num):
314 comment_overlaps = True
318 # No need to look for other comments
321 start_line = line_num
323 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
325 class_name_doxy = mclass_doxy.group(1)
327 comment_lines.append( mcomm.group(1) )
330 if len(comment_lines) > 0:
333 end_line = line_num - 1
336 if class_name_doxy is None:
338 # No \class specified: guess it from file name
339 reclass = r'^(.*/)?(.*?)(\..*)?$'
340 mclass = re.search( reclass, filename )
342 class_name_doxy = mclass.group(2)
344 assert False, 'Regexp unable to extract classname from file'
346 # Prepend \class specifier (and an empty line)
347 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
349 # Append author and date if they exist
350 comment_lines.append('')
352 if author is not None:
353 comment_lines.append( '\\author ' + author )
356 comment_lines.append( '\\date ' + date )
358 comment_lines = refactor_comment(comment_lines)
359 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
360 comments.append(Comment(
362 start_line, 1, end_line, 1,
367 ## Traverse the AST recursively starting from the current cursor.
369 # @param cursor A Clang parser cursor
370 # @param filename Name of the current file
371 # @param comments Array of comments: new ones will be appended there
372 # @param recursion Current recursion depth
373 def traverse_ast(cursor, filename, comments, recursion=0):
375 # libclang traverses included files as well: we do not want this behavior
376 if cursor.location.file is not None and str(cursor.location.file) != filename:
377 logging.debug("Skipping processing of included %s" % cursor.location.file)
380 text = cursor.spelling or cursor.displayname
381 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
384 for i in range(0, recursion):
385 indent = indent + ' '
387 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
389 # cursor ran into a C++ method
390 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
391 comment_method(cursor, comments)
393 elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
395 # cursor ran into a data member declaration
396 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
397 comment_datamember(cursor, comments)
401 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
403 for child_cursor in cursor.get_children():
404 traverse_ast(child_cursor, filename, comments, recursion+1)
407 comment_classdesc(filename, comments)
410 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
412 # @param comment An array containing the lines of the original comment
413 def refactor_comment(comment):
415 recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
416 regarbage = r'^[\s*=-_#]+$'
420 wait_first_non_blank = True
421 for line_comment in comment:
422 mcomm = re.search( recomm, line_comment )
424 new_line_comment = mcomm.group(2)
425 mgarbage = re.search( regarbage, new_line_comment )
427 if new_line_comment == '' or mgarbage is not None:
430 if insert_blank and not wait_first_non_blank:
431 new_comment.append('')
433 wait_first_non_blank = False
434 new_comment.append( new_line_comment )
437 assert False, 'Comment regexp does not match'
442 ## Rewrites all comments from the given file handler.
444 # @param fhin The file handler to read from
445 # @param fhout The file handler to write to
446 # @param comments Array of comments
447 def rewrite_comments(fhin, fhout, comments):
459 line_num = line_num + 1
461 # Find current comment
465 if c.has_comment(line_num):
470 if isinstance(comm, MemberComment):
471 non_comment = line[ 0:comm.first_col-1 ]
473 if comm.array_size is not None:
475 mindent = re.search(rindent, line)
476 if comm.is_transient:
481 # Special case: we need multiple lines not to confuse ROOT's C++ parser
482 fhout.write('%s/// %s\n%s//%s[%s]\n' % (
492 if comm.is_transient:
497 fhout.write('%s//%s< %s\n' % (
503 elif isinstance(comm, RemoveComment):
504 # Do nothing: just skip line
507 elif prev_comm is None:
508 # Beginning of a new comment block of type Comment
511 # Extract the non-comment part and print it if it exists
512 non_comment = line[ 0:comm.first_col-1 ].rstrip()
513 if non_comment != '':
514 fhout.write( non_comment + '\n' )
520 # We have just exited a comment block of type Comment
523 # Dump revamped comment, if applicable
525 for i in range(0,prev_comm.indent):
526 text_indent = text_indent + ' '
528 for lc in prev_comm.lines:
529 fhout.write( "%s/// %s\n" % (text_indent, lc) );
533 line_out = line.rstrip('\n')
536 if line_out.strip() != '':
537 fhout.write( line_out + '\n' )
539 fhout.write( line_out + '\n' )
542 ## The main function.
544 # Return value is the executable's return value.
547 # Setup logging on stderr
548 log_level = logging.INFO
551 format='%(levelname)-8s %(funcName)-20s %(message)s',
555 # Parse command-line options
556 output_on_stdout = False
558 opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
561 log_level = getattr( logging, a.upper(), None )
562 if not isinstance(log_level, int):
563 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
565 log_level = logging.DEBUG
566 elif o == '-o' or o == '--stdout':
567 logging.debug('Output on stdout instead of replacing original files')
568 output_on_stdout = True
570 assert False, 'Unhandled argument'
571 except getopt.GetoptError as e:
572 logging.fatal('Invalid arguments: %s' % e)
575 logging.getLogger('').setLevel(log_level)
577 # Attempt to load libclang from a list of known locations
578 libclang_locations = [
579 '/usr/lib/llvm-3.5/lib/libclang.so.1',
580 '/usr/lib/libclang.so',
581 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
583 libclang_found = False
585 for lib in libclang_locations:
586 if os.path.isfile(lib):
587 clang.cindex.Config.set_library_file(lib)
588 libclang_found = True
591 if not libclang_found:
592 logging.fatal('Cannot find libclang')
595 # Loop over all files
598 logging.info('Input file: %s' % Colt(fn).magenta())
599 index = clang.cindex.Index.create()
600 translation_unit = index.parse(fn, args=['-x', 'c++'])
603 traverse_ast( translation_unit.cursor, fn, comments )
606 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
608 if isinstance(c, MemberComment):
611 transient_text = Colt('transient ').yellow()
615 if c.array_size is not None:
616 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
622 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
625 Colt(c.lines[0]).cyan()
628 elif isinstance(c, RemoveComment):
630 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
635 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
636 "{%s}" % Colt(l).cyan()
642 with open(fn, 'r') as fhin:
643 rewrite_comments( fhin, sys.stdout, comments )
645 fn_back = fn + '.thtml2doxy_backup'
646 os.rename( fn, fn_back )
648 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
649 rewrite_comments( fhin, fhout, comments )
652 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
653 except (IOError,OSError) as e:
654 logging.error('File operation failed: %s' % e)
659 if __name__ == '__main__':
660 sys.exit( main( sys.argv[1:] ) )