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
44 ## Brain-dead color output for terminal.
48 return self.color('\033[31m')
51 return self.color('\033[32m')
54 return self.color('\033[33m')
57 return self.color('\033[34m')
60 return self.color('\033[35m')
63 return self.color('\033[36m')
66 return c + self + '\033[m'
72 def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func):
73 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
75 self.first_line = first_line
76 self.first_col = first_col
77 self.last_line = last_line
78 self.last_col = last_col
82 def has_comment(self, line):
83 return line >= self.first_line and line <= self.last_line
86 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)
89 ## A data member comment.
92 def __init__(self, text, comment_flag, array_size, first_line, first_col, func):
93 assert first_line > 0, 'Wrong line number'
94 assert comment_flag is None or comment_flag == '!' or comment_flag in [ '!', '||', '->' ]
96 self.comment_flag = comment_flag
97 self.array_size = array_size
98 self.first_line = first_line
99 self.first_col = first_col
102 def is_transient(self):
103 return self.comment_flag == '!'
105 def is_dontsplit(self):
106 return self.comment_flag == '||'
109 return self.comment_flag == '->'
111 def has_comment(self, line):
112 return line == self.first_line
116 if self.is_transient():
118 elif self.is_dontsplit():
125 if self.array_size is not None:
126 ars = '[%s] ' % self.array_size
130 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
133 ## A dummy comment that removes comment lines.
134 class RemoveComment(Comment):
136 def __init__(self, first_line, last_line):
137 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
138 self.first_line = first_line
139 self.last_line = last_line
140 self.func = '<remove>'
143 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
146 ## Parses method comments.
148 # @param cursor Current libclang parser cursor
149 # @param comments Array of comments: new ones will be appended there
150 def comment_method(cursor, comments):
152 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
153 # need to extract the first comment in the compound statement composing the method
155 in_compound_stmt = False
156 expect_comment = False
160 comment_function = cursor.spelling or cursor.displayname
161 comment_line_start = -1
162 comment_line_end = -1
163 comment_col_start = -1
167 for token in cursor.get_tokens():
169 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
170 if not in_compound_stmt:
171 in_compound_stmt = True
172 expect_comment = True
173 comment_line_end = -1
176 in_compound_stmt = False
179 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
180 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
186 extent = token.extent
187 line_start = extent.start.line
188 line_end = extent.end.line
190 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
193 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)):
194 comment_line_end = line_end
195 comment_col_end = extent.end.column
197 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
198 comment_indent = extent.start.column-1
200 if comment_line_start == -1:
201 comment_line_start = line_start
202 comment_col_start = extent.start.column
203 comment.extend( token.spelling.split('\n') )
205 # multiline comments are parsed in one go, therefore don't expect subsequent comments
206 if line_end - line_start > 0:
208 expect_comment = False
212 expect_comment = False
216 if comment_line_start > 0:
218 comment = refactor_comment( comment, infilename=str(cursor.location.file) )
221 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
222 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
224 logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
225 comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
226 #comments.append(RemoveComment(comment_line_start, comment_line_end))
229 logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
232 comment_line_start = -1
233 comment_line_end = -1
234 comment_col_start = -1
242 ## Parses comments to class data members.
244 # @param cursor Current libclang parser cursor
245 # @param comments Array of comments: new ones will be appended there
246 def comment_datamember(cursor, comments):
248 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
249 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
250 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
251 # definition is fully on one line, and we take the line number from cursor.location.
253 line_num = cursor.location.line
258 # Huge overkill: current line saved in "raw", previous in "prev"
259 with open(str(cursor.location.file)) as fp:
262 cur_line = cur_line + 1
263 if cur_line == line_num:
268 assert found, 'A line that should exist was not found in file' % cursor.location.file
270 recomm = r'(//(!|\|\||->)|///?)(\[([0-9,]+)\])?<?\s*(.*?)\s*$'
271 recomm_prevline = r'^\s*///\s*(.*?)\s*$'
273 mcomm = re.search(recomm, raw)
275 # If it does not match, we do not have a comment
276 member_name = cursor.spelling;
277 comment_flag = mcomm.group(2)
278 array_size = mcomm.group(4)
279 text = mcomm.group(5)
281 col_num = mcomm.start()+1;
283 if array_size is not None and prev is not None:
284 # ROOT arrays with comments already converted to Doxygen have the member description on the
286 mcomm_prevline = re.search(recomm_prevline, prev)
288 text = mcomm_prevline.group(1)
289 comments.append(RemoveComment(line_num-1, line_num-1))
291 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
293 comments.append( MemberComment(
302 ## Parses class description (beginning of file).
304 # The clang parser does not work in this case so we do it manually, but it is very simple: we keep
305 # the first consecutive sequence of single-line comments (//) we find - provided that it occurs
306 # before any other comment found so far in the file (the comments array is inspected to ensure
309 # Multi-line comments (/* ... */) are not considered as they are commonly used to display
312 # @param filename Name of the current file
313 # @param comments Array of comments: new ones will be appended there
314 def comment_classdesc(filename, comments):
316 recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
318 reclass_doxy = r'(?i)^\s*\\(class|file):?\s*([^.]*)'
319 class_name_doxy = None
321 reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
322 redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
333 is_macro = filename.endswith('.C')
335 with open(filename, 'r') as fp:
339 line_num = line_num + 1
341 if raw.strip() == '' and start_line > 0:
345 stripped = strip_html(raw)
346 mcomm = re.search(recomm, stripped)
351 # First line. Check that we do not overlap with other comments
352 comment_overlaps = False
354 if c.has_comment(line_num):
355 comment_overlaps = True
359 # No need to look for other comments
362 start_line = line_num
367 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
369 class_name_doxy = mclass_doxy.group(2)
372 mauthor = re.search(reauthor, mcomm.group(1))
374 author = mauthor.group(1)
376 # Date specified in the standalone \date field has priority
377 date = mauthor.group(3)
380 mdate = re.search(redate, mcomm.group(1))
382 date = mdate.group(1)
386 comment_lines.append( mcomm.group(1) )
392 if class_name_doxy is None:
394 # No \class specified: guess it from file name
395 reclass = r'^(.*/)?(.*?)(\..*)?$'
396 mclass = re.search( reclass, filename )
398 class_name_doxy = mclass.group(2)
400 assert False, 'Regexp unable to extract classname from file'
404 # Prepend \class or \file specifier (and an empty line)
406 comment_lines[:0] = [ '\\file ' + class_name_doxy + '.C' ]
408 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
410 # Append author and date if they exist
411 comment_lines.append('')
413 if author is not None:
414 comment_lines.append( '\\author ' + author )
417 comment_lines.append( '\\date ' + date )
419 comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
420 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
421 comments.append(Comment(
423 start_line, 1, end_line, 1,
429 logging.warning('No comment found for class %s' % Colt(class_name_doxy).magenta())
432 ## Traverse the AST recursively starting from the current cursor.
434 # @param cursor A Clang parser cursor
435 # @param filename Name of the current file
436 # @param comments Array of comments: new ones will be appended there
437 # @param recursion Current recursion depth
438 def traverse_ast(cursor, filename, comments, recursion=0):
440 # libclang traverses included files as well: we do not want this behavior
441 if cursor.location.file is not None and str(cursor.location.file) != filename:
442 logging.debug("Skipping processing of included %s" % cursor.location.file)
445 text = cursor.spelling or cursor.displayname
446 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
448 is_macro = filename.endswith('.C')
451 for i in range(0, recursion):
452 indent = indent + ' '
454 if cursor.kind in [ clang.cindex.CursorKind.CXX_METHOD, clang.cindex.CursorKind.CONSTRUCTOR,
455 clang.cindex.CursorKind.DESTRUCTOR ]:
457 # cursor ran into a C++ method
458 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
459 comment_method(cursor, comments)
461 elif not is_macro and cursor.kind in [ clang.cindex.CursorKind.FIELD_DECL, clang.cindex.CursorKind.VAR_DECL ]:
463 # cursor ran into a data member declaration
464 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
465 comment_datamember(cursor, comments)
469 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
471 for child_cursor in cursor.get_children():
472 traverse_ast(child_cursor, filename, comments, recursion+1)
475 comment_classdesc(filename, comments)
478 ## Strip some HTML tags from the given string. Returns clean string.
480 # @param s Input string
482 rehtml = r'(?i)</?(P|BR)/?>'
483 return re.sub(rehtml, '', s)
486 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
488 # @param comment An array containing the lines of the original comment
489 def refactor_comment(comment, do_strip_html=True, infilename=None):
491 recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
492 regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
494 # Support for LaTeX blocks spanning on multiple lines
495 relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
499 # Support for LaTeX blocks on a single line
500 reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
502 # Match <pre> (to turn it into the ~~~ Markdown syntax)
503 reblock = r'(?i)^(\s*)</?PRE>\s*$'
505 # Macro blocks for pictures generation
508 remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
512 wait_first_non_blank = True
513 for line_comment in comment:
515 # Check if we are in a macro block
516 mmacro = re.search(remacro, line_comment)
522 outimg = write_macro(infilename, current_macro) + '.png'
526 new_comment.append( '![Picture from ROOT macro](%s)' % (outimg) )
528 logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
535 current_macro.append( line_comment )
538 # Strip some HTML tags
540 line_comment = strip_html(line_comment)
542 mcomm = re.search( recomm, line_comment )
544 new_line_comment = mcomm.group(2)
545 mgarbage = re.search( regarbage, new_line_comment )
547 if new_line_comment == '' or mgarbage is not None:
550 if insert_blank and not wait_first_non_blank:
551 new_comment.append('')
553 wait_first_non_blank = False
555 # Postprocessing: LaTeX formulas in ROOT format
556 # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
557 # There can be several ROOT LaTeX forumlas per line
559 minline_latex = re.search( reinline_latex, new_line_comment )
561 new_line_comment = '%s\\f$%s\\f$%s' % \
562 ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
563 minline_latex.group(3) )
567 # ROOT LaTeX: do we have a Begin/End_LaTeX block?
568 # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
569 # block here left without a corresponding ending block
570 mlatex = re.search( relatex, new_line_comment )
573 # before and after parts have been already stripped
574 l_before = mlatex.group(2)
575 l_after = mlatex.group(4)
576 is_begin = mlatex.group(3).upper() == 'BEGIN' # if not, END
585 # Begin of LaTeX part
588 if l_before == '' and l_after == '':
590 # Opening tag alone: mark the beginning of a block: \f[ ... \f]
592 new_comment.append( '\\f[' )
595 # Mark the beginning of inline: \f$ ... \f$
598 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
608 # Closing a LaTeX block
610 new_comment.append( l_before.replace('#', '\\') )
611 new_comment.append( '\\f]' )
613 new_comment.append( l_after )
617 # Closing a LaTeX inline
619 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
622 # Prevent appending lines (we have already done that)
623 new_line_comment = None
625 # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
626 # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
627 if new_line_comment is not None and not in_latex:
629 mblock = re.search( reblock, new_line_comment )
631 new_comment.append( mblock.group(1)+'~~~' )
632 new_line_comment = None
634 if new_line_comment is not None:
636 new_line_comment = new_line_comment.replace('#', '\\')
637 new_comment.append( new_line_comment )
640 assert False, 'Comment regexp does not match'
645 ## Dumps an image-generating macro to the correct place. Returns a string with the image path,
646 # without the extension.
648 # @param infilename File name of the source file
649 # @param macro_lines Array of macro lines
650 def write_macro(infilename, macro_lines):
653 digh = hashlib.sha1()
654 for l in macro_lines:
657 short_digest = digh.hexdigest()[0:7]
659 outdir = '%s/imgdoc' % os.path.dirname(infilename)
660 outprefix = '%s/%s_%s' % (
662 os.path.basename(infilename).replace('.', '_'),
665 outmacro = '%s.C' % outprefix
668 if not os.path.isdir(outdir):
669 # do not catch: let everything die on error
670 logging.debug('Creating directory %s' % Colt(outdir).magenta())
673 # Create file (do not catch errors either)
674 with open(outmacro, 'w') as omfp:
675 logging.debug('Writing macro %s' % Colt(outmacro).magenta())
676 for l in macro_lines:
683 ## Rewrites all comments from the given file handler.
685 # @param fhin The file handler to read from
686 # @param fhout The file handler to write to
687 # @param comments Array of comments
688 def rewrite_comments(fhin, fhout, comments):
699 def dump_comment_block(cmt):
701 for i in range(0, cmt.indent):
702 text_indent = text_indent + ' '
705 fhout.write( "%s/// %s\n" % (text_indent, lc) );
711 line_num = line_num + 1
713 # Find current comment
717 if c.has_comment(line_num):
722 if isinstance(comm, MemberComment):
726 dump_comment_block(prev_comm)
729 non_comment = line[ 0:comm.first_col-1 ]
731 if comm.array_size is not None or comm.is_dontsplit() or comm.is_ptr():
733 # This is a special case: comment will be split in two lines: one before the comment for
734 # Doxygen as "member description", and the other right after the comment on the same line
735 # to be parsed by ROOT's C++ parser
737 # Keep indent on the generated line of comment before member definition
738 mindent = re.search(rindent, line)
740 # Get correct comment flag, if any
741 if comm.comment_flag is not None:
742 cflag = comm.comment_flag
746 # Get correct array size, if any
747 if comm.array_size is not None:
748 asize = '[%s]' % comm.array_size
753 fhout.write('%s/// %s\n%s//%s%s\n' % (
763 # Single-line comments with the "transient" flag can be kept on one line in a way that
764 # they are correctly interpreted by both ROOT and Doxygen
766 if comm.is_transient():
771 fhout.write('%s//%s< %s\n' % (
777 elif isinstance(comm, RemoveComment):
778 # End comment block and skip this line
780 dump_comment_block(prev_comm)
783 elif prev_comm is None:
785 # Beginning of a new comment block of type Comment
788 # Extract the non-comment part and print it if it exists
789 non_comment = line[ 0:comm.first_col-1 ].rstrip()
790 if non_comment != '':
791 fhout.write( non_comment + '\n' )
797 # We have just exited a comment block of type Comment
798 dump_comment_block(prev_comm)
802 line_out = line.rstrip('\n')
805 if line_out.strip() != '':
806 fhout.write( line_out + '\n' )
808 fhout.write( line_out + '\n' )
811 ## The main function.
813 # Return value is the executable's return value.
816 # Setup logging on stderr
817 log_level = logging.INFO
820 format='%(levelname)-8s %(funcName)-20s %(message)s',
824 # Parse command-line options
825 output_on_stdout = False
828 opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
831 log_level = getattr( logging, a.upper(), None )
832 if not isinstance(log_level, int):
833 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
835 log_level = logging.DEBUG
836 elif o == '-o' or o == '--stdout':
837 output_on_stdout = True
840 include_flags.extend( [ '-I', a ] )
842 logging.fatal('Include directory not found: %s' % Colt(a).magenta())
845 assert False, 'Unhandled argument'
846 except getopt.GetoptError as e:
847 logging.fatal('Invalid arguments: %s' % e)
850 logging.getLogger('').setLevel(log_level)
852 # Attempt to load libclang from a list of known locations
853 libclang_locations = [
854 '/usr/lib/llvm-3.5/lib/libclang.so.1',
855 '/usr/lib/libclang.so',
856 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
858 libclang_found = False
860 for lib in libclang_locations:
861 if os.path.isfile(lib):
862 clang.cindex.Config.set_library_file(lib)
863 libclang_found = True
866 if not libclang_found:
867 logging.fatal('Cannot find libclang')
870 # Loop over all files
873 logging.info('Input file: %s' % Colt(fn).magenta())
874 index = clang.cindex.Index.create()
875 clang_args = [ '-x', 'c++' ]
876 clang_args.extend( include_flags )
877 translation_unit = index.parse(fn, args=clang_args)
880 traverse_ast( translation_unit.cursor, fn, comments )
883 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
885 if isinstance(c, MemberComment):
888 flag_text = Colt('transient ').yellow()
889 elif c.is_dontsplit():
890 flag_text = Colt('dontsplit ').yellow()
892 flag_text = Colt('ptr ').yellow()
896 if c.array_size is not None:
897 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
903 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
906 Colt(c.lines[0]).cyan()
909 elif isinstance(c, RemoveComment):
911 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
916 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
917 "{%s}" % Colt(l).cyan()
923 with open(fn, 'r') as fhin:
924 rewrite_comments( fhin, sys.stdout, comments )
926 fn_back = fn + '.thtml2doxy_backup'
927 os.rename( fn, fn_back )
929 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
930 rewrite_comments( fhin, fhout, comments )
933 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
934 except (IOError,OSError) as e:
935 logging.error('File operation failed: %s' % e)
940 if __name__ == '__main__':
941 sys.exit( main( sys.argv[1:] ) )