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):
72 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
74 self.first_line = first_line
75 self.first_col = first_col
76 self.last_line = last_line
77 self.last_col = last_col
81 def has_comment(self, line):
82 return line >= self.first_line and line <= self.last_line
85 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)
88 ## A data member comment.
91 def __init__(self, text, is_transient, array_size, first_line, first_col, func):
92 assert first_line > 0, 'Wrong line number'
94 self.is_transient = is_transient
95 self.array_size = array_size
96 self.first_line = first_line
97 self.first_col = first_col
100 def has_comment(self, line):
101 return line == self.first_line
105 if self.is_transient:
110 if self.array_size is not None:
111 ars = '[%s] ' % self.array_size
115 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
118 ## A dummy comment that removes comment lines.
119 class RemoveComment(Comment):
121 def __init__(self, first_line, last_line):
122 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
123 self.first_line = first_line
124 self.last_line = last_line
125 self.func = '<remove>'
128 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
131 ## Parses method comments.
133 # @param cursor Current libclang parser cursor
134 # @param comments Array of comments: new ones will be appended there
135 def comment_method(cursor, comments):
137 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
138 # need to extract the first comment in the compound statement composing the method
140 in_compound_stmt = False
141 expect_comment = False
145 comment_function = cursor.spelling or cursor.displayname
146 comment_line_start = -1
147 comment_line_end = -1
148 comment_col_start = -1
152 for token in cursor.get_tokens():
154 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
155 if not in_compound_stmt:
156 in_compound_stmt = True
157 expect_comment = True
158 comment_line_end = -1
161 in_compound_stmt = False
164 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
165 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
171 extent = token.extent
172 line_start = extent.start.line
173 line_end = extent.end.line
175 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
178 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)):
179 comment_line_end = line_end
180 comment_col_end = extent.end.column
182 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
183 comment_indent = extent.start.column-1
185 if comment_line_start == -1:
186 comment_line_start = line_start
187 comment_col_start = extent.start.column
188 comment.extend( token.spelling.split('\n') )
190 # multiline comments are parsed in one go, therefore don't expect subsequent comments
191 if line_end - line_start > 0:
193 expect_comment = False
197 expect_comment = False
201 if comment_line_start > 0:
203 comment = refactor_comment( comment )
206 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
207 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
209 logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
210 comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
211 #comments.append(RemoveComment(comment_line_start, comment_line_end))
214 logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
217 comment_line_start = -1
218 comment_line_end = -1
219 comment_col_start = -1
227 ## Parses comments to class data members.
229 # @param cursor Current libclang parser cursor
230 # @param comments Array of comments: new ones will be appended there
231 def comment_datamember(cursor, comments):
233 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
234 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
235 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
236 # definition is fully on one line, and we take the line number from cursor.location.
238 line_num = cursor.location.line
244 with open(str(cursor.location.file)) as fp:
247 cur_line = cur_line + 1
248 if cur_line == line_num:
253 assert found, 'A line that should exist was not found in file' % cursor.location.file
255 recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
256 recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
258 mcomm = re.search(recomm, raw)
260 # If it does not match, we do not have a comment
261 member_name = cursor.spelling;
262 is_transient = mcomm.group(2) is not None
263 array_size = mcomm.group(4)
264 text = mcomm.group(5)
266 col_num = mcomm.start()+1;
268 if array_size is not None and prev is not None:
269 # ROOT arrays with comments already converted to Doxygen have the member description on the
271 mcomm_doxyary = re.search(recomm_doxyary, prev)
273 text = mcomm_doxyary.group(1)
274 comments.append(RemoveComment(line_num-1, line_num-1))
276 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
278 comments.append( MemberComment(
287 ## Parses class description (beginning of file).
289 # The clang parser does not work in this case so we do it manually, but it is very simple: we keep
290 # the first consecutive sequence of single-line comments (//) we find - provided that it occurs
291 # before any other comment found so far in the file (the comments array is inspected to ensure
294 # Multi-line comments (/* ... */) are not considered as they are commonly used to display
297 # @param filename Name of the current file
298 # @param comments Array of comments: new ones will be appended there
299 def comment_classdesc(filename, comments):
301 recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
303 reclass_doxy = r'(?i)^\s*\\class:?\s*(.*?)\s*$'
304 class_name_doxy = None
306 reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
307 redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
318 with open(filename, 'r') as fp:
322 line_num = line_num + 1
324 if raw.strip() == '' and start_line > 0:
328 stripped = strip_html(raw)
329 mcomm = re.search(recomm, stripped)
334 # First line. Check that we do not overlap with other comments
335 comment_overlaps = False
337 if c.has_comment(line_num):
338 comment_overlaps = True
342 # No need to look for other comments
345 start_line = line_num
350 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
352 class_name_doxy = mclass_doxy.group(1)
355 mauthor = re.search(reauthor, mcomm.group(1))
357 author = mauthor.group(1)
359 # Date specified in the standalone \date field has priority
360 date = mauthor.group(2)
363 mdate = re.search(redate, mcomm.group(1))
365 date = mdate.group(1)
369 comment_lines.append( mcomm.group(1) )
375 if class_name_doxy is None:
377 # No \class specified: guess it from file name
378 reclass = r'^(.*/)?(.*?)(\..*)?$'
379 mclass = re.search( reclass, filename )
381 class_name_doxy = mclass.group(2)
383 assert False, 'Regexp unable to extract classname from file'
387 # Prepend \class specifier (and an empty line)
388 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
390 # Append author and date if they exist
391 comment_lines.append('')
393 if author is not None:
394 comment_lines.append( '\\author ' + author )
397 comment_lines.append( '\\date ' + date )
399 comment_lines = refactor_comment(comment_lines, do_strip_html=False)
400 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
401 comments.append(Comment(
403 start_line, 1, end_line, 1,
409 logging.warning('No comment found for class %s' % Colt(class_name_doxy).magenta())
412 ## Traverse the AST recursively starting from the current cursor.
414 # @param cursor A Clang parser cursor
415 # @param filename Name of the current file
416 # @param comments Array of comments: new ones will be appended there
417 # @param recursion Current recursion depth
418 def traverse_ast(cursor, filename, comments, recursion=0):
420 # libclang traverses included files as well: we do not want this behavior
421 if cursor.location.file is not None and str(cursor.location.file) != filename:
422 logging.debug("Skipping processing of included %s" % cursor.location.file)
425 text = cursor.spelling or cursor.displayname
426 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
429 for i in range(0, recursion):
430 indent = indent + ' '
432 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
434 # cursor ran into a C++ method
435 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
436 comment_method(cursor, comments)
438 elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
440 # cursor ran into a data member declaration
441 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
442 comment_datamember(cursor, comments)
446 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
448 for child_cursor in cursor.get_children():
449 traverse_ast(child_cursor, filename, comments, recursion+1)
452 comment_classdesc(filename, comments)
455 ## Strip some HTML tags from the given string. Returns clean string.
457 # @param s Input string
459 rehtml = r'(?i)</?(P|H[0-9]|BR)/?>'
460 return re.sub(rehtml, '', s)
463 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
465 # @param comment An array containing the lines of the original comment
466 def refactor_comment(comment, do_strip_html=True):
468 recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
469 regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
471 reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
475 wait_first_non_blank = True
476 for line_comment in comment:
478 # Strip some HTML tags
480 line_comment = strip_html(line_comment)
482 mcomm = re.search( recomm, line_comment )
484 new_line_comment = mcomm.group(2)
485 mgarbage = re.search( regarbage, new_line_comment )
487 if new_line_comment == '' or mgarbage is not None:
490 if insert_blank and not wait_first_non_blank:
491 new_comment.append('')
493 wait_first_non_blank = False
495 # Postprocessing: LaTeX formulas in ROOT format
496 # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
497 # There can be several ROOT LaTeX forumlas per line
499 minline_latex = re.search( reinline_latex, new_line_comment )
501 new_line_comment = '%s\\f$%s\\f$%s' % \
502 ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
503 minline_latex.group(3) )
507 new_comment.append( new_line_comment )
510 assert False, 'Comment regexp does not match'
515 ## Rewrites all comments from the given file handler.
517 # @param fhin The file handler to read from
518 # @param fhout The file handler to write to
519 # @param comments Array of comments
520 def rewrite_comments(fhin, fhout, comments):
532 line_num = line_num + 1
534 # Find current comment
538 if c.has_comment(line_num):
543 if isinstance(comm, MemberComment):
544 non_comment = line[ 0:comm.first_col-1 ]
546 if comm.array_size is not None:
548 mindent = re.search(rindent, line)
549 if comm.is_transient:
554 # Special case: we need multiple lines not to confuse ROOT's C++ parser
555 fhout.write('%s/// %s\n%s//%s[%s]\n' % (
565 if comm.is_transient:
570 fhout.write('%s//%s< %s\n' % (
576 elif isinstance(comm, RemoveComment):
577 # Do nothing: just skip line
580 elif prev_comm is None:
581 # Beginning of a new comment block of type Comment
584 # Extract the non-comment part and print it if it exists
585 non_comment = line[ 0:comm.first_col-1 ].rstrip()
586 if non_comment != '':
587 fhout.write( non_comment + '\n' )
593 # We have just exited a comment block of type Comment
596 # Dump revamped comment, if applicable
598 for i in range(0,prev_comm.indent):
599 text_indent = text_indent + ' '
601 for lc in prev_comm.lines:
602 fhout.write( "%s/// %s\n" % (text_indent, lc) );
606 line_out = line.rstrip('\n')
609 if line_out.strip() != '':
610 fhout.write( line_out + '\n' )
612 fhout.write( line_out + '\n' )
615 ## The main function.
617 # Return value is the executable's return value.
620 # Setup logging on stderr
621 log_level = logging.INFO
624 format='%(levelname)-8s %(funcName)-20s %(message)s',
628 # Parse command-line options
629 output_on_stdout = False
632 opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
635 log_level = getattr( logging, a.upper(), None )
636 if not isinstance(log_level, int):
637 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
639 log_level = logging.DEBUG
640 elif o == '-o' or o == '--stdout':
641 output_on_stdout = True
644 include_flags.extend( [ '-I', a ] )
646 logging.fatal('Include directory not found: %s' % Colt(a).magenta())
649 assert False, 'Unhandled argument'
650 except getopt.GetoptError as e:
651 logging.fatal('Invalid arguments: %s' % e)
654 logging.getLogger('').setLevel(log_level)
656 # Attempt to load libclang from a list of known locations
657 libclang_locations = [
658 '/usr/lib/llvm-3.5/lib/libclang.so.1',
659 '/usr/lib/libclang.so',
660 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
662 libclang_found = False
664 for lib in libclang_locations:
665 if os.path.isfile(lib):
666 clang.cindex.Config.set_library_file(lib)
667 libclang_found = True
670 if not libclang_found:
671 logging.fatal('Cannot find libclang')
674 # Loop over all files
677 logging.info('Input file: %s' % Colt(fn).magenta())
678 index = clang.cindex.Index.create()
679 clang_args = [ '-x', 'c++' ]
680 clang_args.extend( include_flags )
681 translation_unit = index.parse(fn, args=clang_args)
684 traverse_ast( translation_unit.cursor, fn, comments )
687 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
689 if isinstance(c, MemberComment):
692 transient_text = Colt('transient ').yellow()
696 if c.array_size is not None:
697 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
703 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
706 Colt(c.lines[0]).cyan()
709 elif isinstance(c, RemoveComment):
711 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
716 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
717 "{%s}" % Colt(l).cyan()
723 with open(fn, 'r') as fhin:
724 rewrite_comments( fhin, sys.stdout, comments )
726 fn_back = fn + '.thtml2doxy_backup'
727 os.rename( fn, fn_back )
729 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
730 rewrite_comments( fhin, fhout, comments )
733 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
734 except (IOError,OSError) as e:
735 logging.error('File operation failed: %s' % e)
740 if __name__ == '__main__':
741 sys.exit( main( sys.argv[1:] ) )