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, is_transient, array_size, first_line, first_col, func):
93 assert first_line > 0, 'Wrong line number'
95 self.is_transient = is_transient
96 self.array_size = array_size
97 self.first_line = first_line
98 self.first_col = first_col
101 def has_comment(self, line):
102 return line == self.first_line
106 if self.is_transient:
111 if self.array_size is not None:
112 ars = '[%s] ' % self.array_size
116 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
119 ## A dummy comment that removes comment lines.
120 class RemoveComment(Comment):
122 def __init__(self, first_line, last_line):
123 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
124 self.first_line = first_line
125 self.last_line = last_line
126 self.func = '<remove>'
129 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
132 ## Parses method comments.
134 # @param cursor Current libclang parser cursor
135 # @param comments Array of comments: new ones will be appended there
136 def comment_method(cursor, comments):
138 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
139 # need to extract the first comment in the compound statement composing the method
141 in_compound_stmt = False
142 expect_comment = False
146 comment_function = cursor.spelling or cursor.displayname
147 comment_line_start = -1
148 comment_line_end = -1
149 comment_col_start = -1
153 for token in cursor.get_tokens():
155 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
156 if not in_compound_stmt:
157 in_compound_stmt = True
158 expect_comment = True
159 comment_line_end = -1
162 in_compound_stmt = False
165 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
166 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
172 extent = token.extent
173 line_start = extent.start.line
174 line_end = extent.end.line
176 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
179 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)):
180 comment_line_end = line_end
181 comment_col_end = extent.end.column
183 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
184 comment_indent = extent.start.column-1
186 if comment_line_start == -1:
187 comment_line_start = line_start
188 comment_col_start = extent.start.column
189 comment.extend( token.spelling.split('\n') )
191 # multiline comments are parsed in one go, therefore don't expect subsequent comments
192 if line_end - line_start > 0:
194 expect_comment = False
198 expect_comment = False
202 if comment_line_start > 0:
204 comment = refactor_comment( comment, infilename=str(cursor.location.file) )
207 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
208 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
210 logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
211 comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
212 #comments.append(RemoveComment(comment_line_start, comment_line_end))
215 logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
218 comment_line_start = -1
219 comment_line_end = -1
220 comment_col_start = -1
228 ## Parses comments to class data members.
230 # @param cursor Current libclang parser cursor
231 # @param comments Array of comments: new ones will be appended there
232 def comment_datamember(cursor, comments):
234 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
235 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
236 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
237 # definition is fully on one line, and we take the line number from cursor.location.
239 line_num = cursor.location.line
245 with open(str(cursor.location.file)) as fp:
248 cur_line = cur_line + 1
249 if cur_line == line_num:
254 assert found, 'A line that should exist was not found in file' % cursor.location.file
256 recomm = r'(//(!)|///?)(\[(.*?)\])?<?\s*(.*?)\s*$'
257 recomm_doxyary = r'^\s*///\s*(.*?)\s*$'
259 mcomm = re.search(recomm, raw)
261 # If it does not match, we do not have a comment
262 member_name = cursor.spelling;
263 is_transient = mcomm.group(2) is not None
264 array_size = mcomm.group(4)
265 text = mcomm.group(5)
267 col_num = mcomm.start()+1;
269 if array_size is not None and prev is not None:
270 # ROOT arrays with comments already converted to Doxygen have the member description on the
272 mcomm_doxyary = re.search(recomm_doxyary, prev)
274 text = mcomm_doxyary.group(1)
275 comments.append(RemoveComment(line_num-1, line_num-1))
277 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
279 comments.append( MemberComment(
288 ## Parses class description (beginning of file).
290 # The clang parser does not work in this case so we do it manually, but it is very simple: we keep
291 # the first consecutive sequence of single-line comments (//) we find - provided that it occurs
292 # before any other comment found so far in the file (the comments array is inspected to ensure
295 # Multi-line comments (/* ... */) are not considered as they are commonly used to display
298 # @param filename Name of the current file
299 # @param comments Array of comments: new ones will be appended there
300 def comment_classdesc(filename, comments):
302 recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
304 reclass_doxy = r'(?i)^\s*\\class:?\s*(.*?)\s*$'
305 class_name_doxy = None
307 reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
308 redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
319 with open(filename, 'r') as fp:
323 line_num = line_num + 1
325 if raw.strip() == '' and start_line > 0:
329 stripped = strip_html(raw)
330 mcomm = re.search(recomm, stripped)
335 # First line. Check that we do not overlap with other comments
336 comment_overlaps = False
338 if c.has_comment(line_num):
339 comment_overlaps = True
343 # No need to look for other comments
346 start_line = line_num
351 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
353 class_name_doxy = mclass_doxy.group(1)
356 mauthor = re.search(reauthor, mcomm.group(1))
358 author = mauthor.group(1)
360 # Date specified in the standalone \date field has priority
361 date = mauthor.group(2)
364 mdate = re.search(redate, mcomm.group(1))
366 date = mdate.group(1)
370 comment_lines.append( mcomm.group(1) )
376 if class_name_doxy is None:
378 # No \class specified: guess it from file name
379 reclass = r'^(.*/)?(.*?)(\..*)?$'
380 mclass = re.search( reclass, filename )
382 class_name_doxy = mclass.group(2)
384 assert False, 'Regexp unable to extract classname from file'
388 # Prepend \class specifier (and an empty line)
389 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
391 # Append author and date if they exist
392 comment_lines.append('')
394 if author is not None:
395 comment_lines.append( '\\author ' + author )
398 comment_lines.append( '\\date ' + date )
400 comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
401 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
402 comments.append(Comment(
404 start_line, 1, end_line, 1,
410 logging.warning('No comment found for class %s' % Colt(class_name_doxy).magenta())
413 ## Traverse the AST recursively starting from the current cursor.
415 # @param cursor A Clang parser cursor
416 # @param filename Name of the current file
417 # @param comments Array of comments: new ones will be appended there
418 # @param recursion Current recursion depth
419 def traverse_ast(cursor, filename, comments, recursion=0):
421 # libclang traverses included files as well: we do not want this behavior
422 if cursor.location.file is not None and str(cursor.location.file) != filename:
423 logging.debug("Skipping processing of included %s" % cursor.location.file)
426 text = cursor.spelling or cursor.displayname
427 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
430 for i in range(0, recursion):
431 indent = indent + ' '
433 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD or cursor.kind == clang.cindex.CursorKind.CONSTRUCTOR or cursor.kind == clang.cindex.CursorKind.DESTRUCTOR:
435 # cursor ran into a C++ method
436 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
437 comment_method(cursor, comments)
439 elif cursor.kind == clang.cindex.CursorKind.FIELD_DECL:
441 # cursor ran into a data member declaration
442 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
443 comment_datamember(cursor, comments)
447 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
449 for child_cursor in cursor.get_children():
450 traverse_ast(child_cursor, filename, comments, recursion+1)
453 comment_classdesc(filename, comments)
456 ## Strip some HTML tags from the given string. Returns clean string.
458 # @param s Input string
460 rehtml = r'(?i)</?(P|BR)/?>'
461 return re.sub(rehtml, '', s)
464 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
466 # @param comment An array containing the lines of the original comment
467 def refactor_comment(comment, do_strip_html=True, infilename=None):
469 recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
470 regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
472 # Support for LaTeX blocks spanning on multiple lines
473 relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
477 # Support for LaTeX blocks on a single line
478 reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
480 # Match <pre> (to turn it into the ~~~ Markdown syntax)
481 reblock = r'(?i)^(\s*)</?PRE>\s*$'
483 # Macro blocks for pictures generation
486 remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
490 wait_first_non_blank = True
491 for line_comment in comment:
493 # Check if we are in a macro block
494 mmacro = re.search(remacro, line_comment)
500 outimg = write_macro(infilename, current_macro) + '.png'
504 new_comment.append( '![Picture from ROOT macro](%s)' % (outimg) )
506 logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
513 current_macro.append( line_comment )
516 # Strip some HTML tags
518 line_comment = strip_html(line_comment)
520 mcomm = re.search( recomm, line_comment )
522 new_line_comment = mcomm.group(2)
523 mgarbage = re.search( regarbage, new_line_comment )
525 if new_line_comment == '' or mgarbage is not None:
528 if insert_blank and not wait_first_non_blank:
529 new_comment.append('')
531 wait_first_non_blank = False
533 # Postprocessing: LaTeX formulas in ROOT format
534 # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
535 # There can be several ROOT LaTeX forumlas per line
537 minline_latex = re.search( reinline_latex, new_line_comment )
539 new_line_comment = '%s\\f$%s\\f$%s' % \
540 ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
541 minline_latex.group(3) )
545 # ROOT LaTeX: do we have a Begin/End_LaTeX block?
546 # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
547 # block here left without a corresponding ending block
548 mlatex = re.search( relatex, new_line_comment )
551 # before and after parts have been already stripped
552 l_before = mlatex.group(2)
553 l_after = mlatex.group(4)
554 is_begin = mlatex.group(3).upper() == 'BEGIN' # if not, END
563 # Begin of LaTeX part
566 if l_before == '' and l_after == '':
568 # Opening tag alone: mark the beginning of a block: \f[ ... \f]
570 new_comment.append( '\\f[' )
573 # Mark the beginning of inline: \f$ ... \f$
576 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
586 # Closing a LaTeX block
588 new_comment.append( l_before.replace('#', '\\') )
589 new_comment.append( '\\f]' )
591 new_comment.append( l_after )
595 # Closing a LaTeX inline
597 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
600 # Prevent appending lines (we have already done that)
601 new_line_comment = None
603 # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
604 # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
605 if new_line_comment is not None and not in_latex:
607 mblock = re.search( reblock, new_line_comment )
609 new_comment.append( mblock.group(1)+'~~~' )
610 new_line_comment = None
612 if new_line_comment is not None:
614 new_line_comment = new_line_comment.replace('#', '\\')
615 new_comment.append( new_line_comment )
618 assert False, 'Comment regexp does not match'
623 ## Dumps an image-generating macro to the correct place. Returns a string with the image path,
624 # without the extension.
626 # @param infilename File name of the source file
627 # @param macro_lines Array of macro lines
628 def write_macro(infilename, macro_lines):
631 digh = hashlib.sha1()
632 for l in macro_lines:
635 short_digest = digh.hexdigest()[0:7]
637 outdir = '%s/imgdoc' % os.path.dirname(infilename)
638 outprefix = '%s/%s_%s' % (
640 os.path.basename(infilename).replace('.', '_'),
643 outmacro = '%s.C' % outprefix
646 if not os.path.isdir(outdir):
647 # do not catch: let everything die on error
648 logging.debug('Creating directory %s' % Colt(outdir).magenta())
651 # Create file (do not catch errors either)
652 with open(outmacro, 'w') as omfp:
653 logging.debug('Writing macro %s' % Colt(outmacro).magenta())
654 for l in macro_lines:
661 ## Rewrites all comments from the given file handler.
663 # @param fhin The file handler to read from
664 # @param fhout The file handler to write to
665 # @param comments Array of comments
666 def rewrite_comments(fhin, fhout, comments):
678 line_num = line_num + 1
680 # Find current comment
684 if c.has_comment(line_num):
689 if isinstance(comm, MemberComment):
690 non_comment = line[ 0:comm.first_col-1 ]
692 if comm.array_size is not None:
694 mindent = re.search(rindent, line)
695 if comm.is_transient:
700 # Special case: we need multiple lines not to confuse ROOT's C++ parser
701 fhout.write('%s/// %s\n%s//%s[%s]\n' % (
711 if comm.is_transient:
716 fhout.write('%s//%s< %s\n' % (
722 elif isinstance(comm, RemoveComment):
723 # Do nothing: just skip line
726 elif prev_comm is None:
727 # Beginning of a new comment block of type Comment
730 # Extract the non-comment part and print it if it exists
731 non_comment = line[ 0:comm.first_col-1 ].rstrip()
732 if non_comment != '':
733 fhout.write( non_comment + '\n' )
739 # We have just exited a comment block of type Comment
742 # Dump revamped comment, if applicable
744 for i in range(0,prev_comm.indent):
745 text_indent = text_indent + ' '
747 for lc in prev_comm.lines:
748 fhout.write( "%s/// %s\n" % (text_indent, lc) );
752 line_out = line.rstrip('\n')
755 if line_out.strip() != '':
756 fhout.write( line_out + '\n' )
758 fhout.write( line_out + '\n' )
761 ## The main function.
763 # Return value is the executable's return value.
766 # Setup logging on stderr
767 log_level = logging.INFO
770 format='%(levelname)-8s %(funcName)-20s %(message)s',
774 # Parse command-line options
775 output_on_stdout = False
778 opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
781 log_level = getattr( logging, a.upper(), None )
782 if not isinstance(log_level, int):
783 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
785 log_level = logging.DEBUG
786 elif o == '-o' or o == '--stdout':
787 output_on_stdout = True
790 include_flags.extend( [ '-I', a ] )
792 logging.fatal('Include directory not found: %s' % Colt(a).magenta())
795 assert False, 'Unhandled argument'
796 except getopt.GetoptError as e:
797 logging.fatal('Invalid arguments: %s' % e)
800 logging.getLogger('').setLevel(log_level)
802 # Attempt to load libclang from a list of known locations
803 libclang_locations = [
804 '/usr/lib/llvm-3.5/lib/libclang.so.1',
805 '/usr/lib/libclang.so',
806 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
808 libclang_found = False
810 for lib in libclang_locations:
811 if os.path.isfile(lib):
812 clang.cindex.Config.set_library_file(lib)
813 libclang_found = True
816 if not libclang_found:
817 logging.fatal('Cannot find libclang')
820 # Loop over all files
823 logging.info('Input file: %s' % Colt(fn).magenta())
824 index = clang.cindex.Index.create()
825 clang_args = [ '-x', 'c++' ]
826 clang_args.extend( include_flags )
827 translation_unit = index.parse(fn, args=clang_args)
830 traverse_ast( translation_unit.cursor, fn, comments )
833 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
835 if isinstance(c, MemberComment):
838 transient_text = Colt('transient ').yellow()
842 if c.array_size is not None:
843 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
849 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
852 Colt(c.lines[0]).cyan()
855 elif isinstance(c, RemoveComment):
857 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
862 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
863 "{%s}" % Colt(l).cyan()
869 with open(fn, 'r') as fhin:
870 rewrite_comments( fhin, sys.stdout, comments )
872 fn_back = fn + '.thtml2doxy_backup'
873 os.rename( fn, fn_back )
875 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
876 rewrite_comments( fhin, fhout, comments )
879 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
880 except (IOError,OSError) as e:
881 logging.error('File operation failed: %s' % e)
886 if __name__ == '__main__':
887 sys.exit( main( sys.argv[1:] ) )