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 [--stdout|-o] [-d] [--debug=DEBUG_LEVEL] file1 [file2 [file3...]]`
26 # - `--stdout|-o`: output all on standard output instead of writing files in place
27 # - `-d`: enable debug mode (very verbose output)
28 # - `--debug=DEBUG_LEVEL`: set debug level to one of `DEBUG`, `INFO`, `WARNING`, `ERROR`,
31 # @author Dario Berzano, CERN
43 ## Brain-dead color output for terminal.
47 return self.color('\033[31m')
50 return self.color('\033[32m')
53 return self.color('\033[33m')
56 return self.color('\033[34m')
59 return self.color('\033[35m')
62 return self.color('\033[36m')
65 return c + self + '\033[m'
71 def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
73 self.first_line = first_line
74 self.first_col = first_col
75 self.last_line = last_line
76 self.last_col = last_col
80 def has_comment(self, line):
81 return line >= self.first_line and line <= self.last_line
84 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)
87 ## A data member comment.
90 def __init__(self, text, is_transient, array_size, first_line, first_col, func):
92 self.is_transient = is_transient
93 self.array_size = array_size
94 self.first_line = first_line
95 self.first_col = first_col
98 def has_comment(self, line):
99 return line == self.first_line
103 if self.is_transient:
108 if self.array_size is not None:
109 ars = '[%s] ' % self.array_size
113 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
116 ## A dummy comment that removes comment lines.
117 class RemoveComment(Comment):
119 def __init__(self, first_line, last_line):
120 self.first_line = first_line
121 self.last_line = last_line
122 self.func = '<remove>'
125 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
128 ## Parses method comments.
130 # @param cursor Current libclang parser cursor
131 # @param comments Array of comments: new ones will be appended there
132 def comment_method(cursor, comments):
134 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
135 # need to extract the first comment in the compound statement composing the method
137 in_compound_stmt = False
138 expect_comment = False
142 comment_function = cursor.spelling or cursor.displayname
143 comment_line_start = -1
144 comment_line_end = -1
145 comment_col_start = -1
149 for token in cursor.get_tokens():
151 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
152 if not in_compound_stmt:
153 in_compound_stmt = True
154 expect_comment = True
155 comment_line_end = -1
158 in_compound_stmt = False
161 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
162 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
168 extent = token.extent
169 line_start = extent.start.line
170 line_end = extent.end.line
172 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
175 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)):
176 comment_line_end = line_end
177 comment_col_end = extent.end.column
179 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
180 comment_indent = extent.start.column-1
182 if comment_line_start == -1:
183 comment_line_start = line_start
184 comment_col_start = extent.start.column
185 comment.extend( token.spelling.split('\n') )
187 # multiline comments are parsed in one go, therefore don't expect subsequent comments
188 if line_end - line_start > 0:
190 expect_comment = False
194 expect_comment = False
198 comment = refactor_comment( comment )
201 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
202 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
205 comment_line_start = -1
206 comment_line_end = -1
207 comment_col_start = -1
215 ## Parses comments to class data members.
217 # @param cursor Current libclang parser cursor
218 # @param comments Array of comments: new ones will be appended there
219 def comment_datamember(cursor, comments):
221 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
222 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
223 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
224 # definition is fully on one line, and we take the line number from cursor.location.
226 line_num = cursor.location.line
232 with open(str(cursor.location.file)) as fp:
235 cur_line = cur_line + 1
236 if cur_line == line_num:
241 assert found, 'A line that should exist was not found in file' % cursor.location.file
243 recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
244 recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
246 mcomm = re.search(recomm, raw)
248 member_name = cursor.spelling;
249 is_transient = mcomm.group(2) is not None
250 array_size = mcomm.group(4)
251 text = mcomm.group(5)
253 col_num = mcomm.start()+1;
255 if array_size is not None and prev is not None:
256 # ROOT arrays with comments already converted to Doxygen have the member description on the
258 mcomm_doxyary = re.search(recomm_doxyary, prev)
260 text = mcomm_doxyary.group(1)
261 comments.append(RemoveComment(line_num-1, line_num-1))
263 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
265 comments.append( MemberComment(
274 assert False, 'Regular expression does not match member comment'
277 ## Parses class description (beginning of file).
279 # The clang parser does not work in this case so we do it manually, but it is very simple: we keep
280 # the first consecutive sequence of single-line comments (//) we find - provided that it occurs
281 # before any other comment found so far in the file (the comments array is inspected to ensure
284 # Multi-line comments (/* ... */) are not considered as they are commonly used to display
287 # @param filename Name of the current file
288 # @param comments Array of comments: new ones will be appended there
289 def comment_classdesc(filename, comments):
291 recomm = r'^\s*///?\s*(.*?)\s*/*\s*$'
293 reclass_doxy = r'(?i)^\\class:?\s*(.*?)\s*$'
294 class_name_doxy = None
296 reauthor = r'(?i)\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
297 redate = r'(?i)\\?date:?\s*([0-9./-]+)'
308 with open(filename, 'r') as fp:
312 line_num = line_num + 1
314 if raw.strip() == '':
316 end_line = line_num - 1
319 mcomm = re.search(recomm, raw)
322 if start_line == -1 and len(comment_lines) == 0:
324 # First line. Check that we do not overlap with other comments
325 comment_overlaps = False
327 if c.has_comment(line_num):
328 comment_overlaps = True
332 # No need to look for other comments
335 start_line = line_num
339 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
341 class_name_doxy = mclass_doxy.group(1)
344 mauthor = re.search(reauthor, mcomm.group(1))
346 author = mauthor.group(1)
348 # Date specified in the standalone \date field has priority
349 date = mauthor.group(2)
352 mdate = re.search(redate, mcomm.group(1))
354 date = mdate.group(1)
358 comment_lines.append( mcomm.group(1) )
361 if len(comment_lines) > 0:
364 end_line = line_num - 1
367 if class_name_doxy is None:
369 # No \class specified: guess it from file name
370 reclass = r'^(.*/)?(.*?)(\..*)?$'
371 mclass = re.search( reclass, filename )
373 class_name_doxy = mclass.group(2)
375 assert False, 'Regexp unable to extract classname from file'
377 # Prepend \class specifier (and an empty line)
378 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
380 # Append author and date if they exist
381 comment_lines.append('')
383 if author is not None:
384 comment_lines.append( '\\author ' + author )
387 comment_lines.append( '\\date ' + date )
389 comment_lines = refactor_comment(comment_lines)
390 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
391 comments.append(Comment(
393 start_line, 1, end_line, 1,
398 ## Traverse the AST recursively starting from the current cursor.
400 # @param cursor A Clang parser cursor
401 # @param filename Name of the current file
402 # @param comments Array of comments: new ones will be appended there
403 # @param recursion Current recursion depth
404 def traverse_ast(cursor, filename, comments, recursion=0):
406 # libclang traverses included files as well: we do not want this behavior
407 if cursor.location.file is not None and str(cursor.location.file) != filename:
408 logging.debug("Skipping processing of included %s" % cursor.location.file)
411 text = cursor.spelling or cursor.displayname
412 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
415 for i in range(0, recursion):
416 indent = indent + ' '
418 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
420 # cursor ran into a C++ method
421 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
422 comment_method(cursor, comments)
424 elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
426 # cursor ran into a data member declaration
427 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
428 comment_datamember(cursor, comments)
432 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
434 for child_cursor in cursor.get_children():
435 traverse_ast(child_cursor, filename, comments, recursion+1)
438 comment_classdesc(filename, comments)
441 ## Strip some HTML tags from the given string. Returns clean string.
443 # @param s Input string
445 rehtml = r'(?i)</?(P|H[0-9]|BR)/?>'
446 return re.sub(rehtml, '', s)
449 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
451 # @param comment An array containing the lines of the original comment
452 def refactor_comment(comment, do_strip_html=True):
454 recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
455 regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
459 wait_first_non_blank = True
460 for line_comment in comment:
462 # Strip some HTML tags
464 line_comment = strip_html(line_comment)
466 mcomm = re.search( recomm, line_comment )
468 new_line_comment = mcomm.group(2)
469 mgarbage = re.search( regarbage, new_line_comment )
471 if new_line_comment == '' or mgarbage is not None:
474 if insert_blank and not wait_first_non_blank:
475 new_comment.append('')
477 wait_first_non_blank = False
478 new_comment.append( new_line_comment )
481 assert False, 'Comment regexp does not match'
486 ## Rewrites all comments from the given file handler.
488 # @param fhin The file handler to read from
489 # @param fhout The file handler to write to
490 # @param comments Array of comments
491 def rewrite_comments(fhin, fhout, comments):
503 line_num = line_num + 1
505 # Find current comment
509 if c.has_comment(line_num):
514 if isinstance(comm, MemberComment):
515 non_comment = line[ 0:comm.first_col-1 ]
517 if comm.array_size is not None:
519 mindent = re.search(rindent, line)
520 if comm.is_transient:
525 # Special case: we need multiple lines not to confuse ROOT's C++ parser
526 fhout.write('%s/// %s\n%s//%s[%s]\n' % (
536 if comm.is_transient:
541 fhout.write('%s//%s< %s\n' % (
547 elif isinstance(comm, RemoveComment):
548 # Do nothing: just skip line
551 elif prev_comm is None:
552 # Beginning of a new comment block of type Comment
555 # Extract the non-comment part and print it if it exists
556 non_comment = line[ 0:comm.first_col-1 ].rstrip()
557 if non_comment != '':
558 fhout.write( non_comment + '\n' )
564 # We have just exited a comment block of type Comment
567 # Dump revamped comment, if applicable
569 for i in range(0,prev_comm.indent):
570 text_indent = text_indent + ' '
572 for lc in prev_comm.lines:
573 fhout.write( "%s/// %s\n" % (text_indent, lc) );
577 line_out = line.rstrip('\n')
580 if line_out.strip() != '':
581 fhout.write( line_out + '\n' )
583 fhout.write( line_out + '\n' )
586 ## The main function.
588 # Return value is the executable's return value.
591 # Setup logging on stderr
592 log_level = logging.INFO
595 format='%(levelname)-8s %(funcName)-20s %(message)s',
599 # Parse command-line options
600 output_on_stdout = False
602 opts, args = getopt.getopt( argv, 'od', [ 'debug=', 'stdout' ] )
605 log_level = getattr( logging, a.upper(), None )
606 if not isinstance(log_level, int):
607 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
609 log_level = logging.DEBUG
610 elif o == '-o' or o == '--stdout':
611 logging.debug('Output on stdout instead of replacing original files')
612 output_on_stdout = True
614 assert False, 'Unhandled argument'
615 except getopt.GetoptError as e:
616 logging.fatal('Invalid arguments: %s' % e)
619 logging.getLogger('').setLevel(log_level)
621 # Attempt to load libclang from a list of known locations
622 libclang_locations = [
623 '/usr/lib/llvm-3.5/lib/libclang.so.1',
624 '/usr/lib/libclang.so',
625 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
627 libclang_found = False
629 for lib in libclang_locations:
630 if os.path.isfile(lib):
631 clang.cindex.Config.set_library_file(lib)
632 libclang_found = True
635 if not libclang_found:
636 logging.fatal('Cannot find libclang')
639 # Loop over all files
642 logging.info('Input file: %s' % Colt(fn).magenta())
643 index = clang.cindex.Index.create()
644 translation_unit = index.parse(fn, args=['-x', 'c++'])
647 traverse_ast( translation_unit.cursor, fn, comments )
650 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
652 if isinstance(c, MemberComment):
655 transient_text = Colt('transient ').yellow()
659 if c.array_size is not None:
660 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
666 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
669 Colt(c.lines[0]).cyan()
672 elif isinstance(c, RemoveComment):
674 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
679 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
680 "{%s}" % Colt(l).cyan()
686 with open(fn, 'r') as fhin:
687 rewrite_comments( fhin, sys.stdout, comments )
689 fn_back = fn + '.thtml2doxy_backup'
690 os.rename( fn, fn_back )
692 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
693 rewrite_comments( fhin, fhout, comments )
696 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
697 except (IOError,OSError) as e:
698 logging.error('File operation failed: %s' % e)
703 if __name__ == '__main__':
704 sys.exit( main( sys.argv[1:] ) )