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'
70 class Comment(object):
72 def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func, \
75 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
77 self.first_line = first_line
78 self.first_col = first_col
79 self.last_line = last_line
80 self.last_col = last_col
83 self.append_empty = append_empty
85 def has_comment(self, line):
86 return line >= self.first_line and line <= self.last_line
89 return "<%s for %s: [%d,%d:%d,%d] %s>" % ( \
90 self.__class__.__name__, self.func,
91 self.first_line, self.first_col, self.last_line, self.last_col,
96 class PrependComment(Comment):
98 def __init__(self, lines, first_line, first_col, last_line, last_col, indent, func, \
100 super(PrependComment, self).__init__( \
101 lines, first_line, first_col, last_line, last_col, indent, func, append_empty)
104 ## A data member comment.
107 def __init__(self, text, comment_flag, array_size, first_line, first_col, func):
108 assert first_line > 0, 'Wrong line number'
109 assert comment_flag is None or comment_flag == '!' or comment_flag in [ '!', '||', '->' ]
110 self.lines = [ text ]
111 self.comment_flag = comment_flag
112 self.array_size = array_size
113 self.first_line = first_line
114 self.first_col = first_col
117 def is_transient(self):
118 return self.comment_flag == '!'
120 def is_dontsplit(self):
121 return self.comment_flag == '||'
124 return self.comment_flag == '->'
126 def has_comment(self, line):
127 return line == self.first_line
131 if self.is_transient():
133 elif self.is_dontsplit():
140 if self.array_size is not None:
141 ars = '[%s] ' % self.array_size
145 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
148 ## A dummy comment that removes comment lines.
149 class RemoveComment(Comment):
151 def __init__(self, first_line, last_line):
152 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
153 self.first_line = first_line
154 self.last_line = last_line
155 self.func = '<remove>'
158 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
161 ## Parses method comments.
163 # @param cursor Current libclang parser cursor
164 # @param comments Array of comments: new ones will be appended there
165 def comment_method(cursor, comments):
167 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
168 # need to extract the first comment in the compound statement composing the method
170 in_compound_stmt = False
171 expect_comment = False
175 comment_function = cursor.spelling or cursor.displayname
176 comment_line_start = -1
177 comment_line_end = -1
178 comment_col_start = -1
182 for token in cursor.get_tokens():
184 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
185 if not in_compound_stmt:
186 in_compound_stmt = True
187 expect_comment = True
188 comment_line_end = -1
191 in_compound_stmt = False
194 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
195 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
201 extent = token.extent
202 line_start = extent.start.line
203 line_end = extent.end.line
205 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
208 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)):
209 comment_line_end = line_end
210 comment_col_end = extent.end.column
212 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
213 comment_indent = extent.start.column-1
215 if comment_line_start == -1:
216 comment_line_start = line_start
217 comment_col_start = extent.start.column
218 comment.extend( token.spelling.split('\n') )
220 # multiline comments are parsed in one go, therefore don't expect subsequent comments
221 if line_end - line_start > 0:
223 expect_comment = False
227 expect_comment = False
231 if comment_line_start > 0:
233 comment = refactor_comment( comment, infilename=str(cursor.location.file) )
236 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
237 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
239 logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
240 comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
241 #comments.append(RemoveComment(comment_line_start, comment_line_end))
244 logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
247 comment_line_start = -1
248 comment_line_end = -1
249 comment_col_start = -1
257 ## Parses comments to class data members.
259 # @param cursor Current libclang parser cursor
260 # @param comments Array of comments: new ones will be appended there
261 def comment_datamember(cursor, comments):
263 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
264 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
265 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
266 # definition is fully on one line, and we take the line number from cursor.location.
268 line_num = cursor.location.line
273 # Huge overkill: current line saved in "raw", previous in "prev"
274 with open(str(cursor.location.file)) as fp:
277 cur_line = cur_line + 1
278 if cur_line == line_num:
283 assert found, 'A line that should exist was not found in file' % cursor.location.file
285 recomm = r'(//(!|\|\||->)|///?)(\[(.+?)\])?<?\s*(.*?)\s*$'
286 recomm_prevline = r'^\s*///\s*(.*?)\s*$'
288 mcomm = re.search(recomm, raw)
290 # If it does not match, we do not have a comment
291 member_name = cursor.spelling;
292 comment_flag = mcomm.group(2)
293 array_size = mcomm.group(4)
294 text = mcomm.group(5)
296 col_num = mcomm.start()+1;
298 if array_size is not None and prev is not None:
299 # ROOT arrays with comments already converted to Doxygen have the member description on the
301 mcomm_prevline = re.search(recomm_prevline, prev)
303 text = mcomm_prevline.group(1)
304 comments.append(RemoveComment(line_num-1, line_num-1))
306 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
308 comments.append( MemberComment(
317 ## Parses class description (beginning of file).
319 # The clang parser does not work in this case so we do it manually, but it is very simple: we keep
320 # the first consecutive sequence of single-line comments (//) we find - provided that it occurs
321 # before any other comment found so far in the file (the comments array is inspected to ensure
324 # Multi-line comments (/* ... */) are not considered as they are commonly used to display
327 # @param filename Name of the current file
328 # @param comments Array of comments: new ones will be appended there
329 # @param look_no_further_than_line Stop before reaching this line when looking for class comment
330 def comment_classdesc(filename, comments, look_no_further_than_line):
332 recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
334 reclass_doxy = r'(?i)^\s*\\(class|file):?\s*([^.]*)'
335 class_name_doxy = None
337 reauthor = r'(?i)^\s*\\?(authors?|origin):?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
338 redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
339 rebrief = r'(?i)^\s*\\brief\s*(.*)\s*$'
343 brief_len_threshold = 80
352 is_macro = filename.endswith('.C')
354 with open(filename, 'r') as fp:
358 line_num = line_num + 1
360 if look_no_further_than_line is not None and line_num == look_no_further_than_line:
361 logging.debug('Stopping at line %d while looking for class/file description' % \
362 look_no_further_than_line)
365 if raw.strip() == '' and start_line > 0:
369 stripped = strip_html(raw)
370 mcomm = re.search(recomm, stripped)
375 # First line. Check that we do not overlap with other comments
376 comment_overlaps = False
378 if c.has_comment(line_num):
379 comment_overlaps = True
383 # No need to look for other comments
386 start_line = line_num
391 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
393 class_name_doxy = mclass_doxy.group(2)
396 mauthor = re.search(reauthor, mcomm.group(1))
398 author = mauthor.group(2)
400 # Date specified in the standalone \date field has priority
401 date = mauthor.group(4)
404 mdate = re.search(redate, mcomm.group(1))
406 date = mdate.group(1)
409 mbrief = re.search(rebrief, mcomm.group(1))
411 brief = mbrief.group(1)
415 comment_lines.append( mcomm.group(1) )
421 if class_name_doxy is None:
423 # No \class specified: guess it from file name
424 reclass = r'^(.*/)?(.*?)(\..*)?$'
425 mclass = re.search( reclass, filename )
427 class_name_doxy = mclass.group(2)
429 assert False, 'Regexp unable to extract classname from file'
433 file_class_line = '\\file ' + class_name_doxy + '.C'
435 file_class_line = '\\class ' + class_name_doxy
439 prepend_to_comment = []
441 # Prepend \class or \file specifier, then the \brief, then an empty line
442 prepend_to_comment.append( file_class_line )
444 if brief is not None:
445 prepend_to_comment.append( '\\brief ' + brief )
446 prepend_to_comment.append( '' )
448 comment_lines = prepend_to_comment + comment_lines # join lists
450 # Append author and date if they exist
451 if author is not None:
452 comment_lines.append( '\\author ' + author )
455 comment_lines.append( '\\date ' + date )
457 comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
459 # Now we look for a possible \brief
462 for comm in comment_lines:
463 if comm.startswith('\\class') or comm.startswith('\\file') or comm == '':
466 if len(comm) <= brief_len_threshold:
469 comm_idx = comm_idx + 1
470 if brief is not None:
471 comment_lines = refactor_comment(
472 [ comment_lines[0], '\\brief ' + brief ] + comment_lines[1:comm_idx] + comment_lines[comm_idx+1:],
473 do_strip_html=False, infilename=filename)
475 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
476 comments.append(Comment(
478 start_line, 1, end_line, 1,
484 logging.warning('No comment found for class %s: creating a dummy entry at the beginning' % \
485 Colt(class_name_doxy).magenta())
487 comments.append(PrependComment(
490 0, class_name_doxy, append_empty=True
494 ## Looks for a special ROOT ClassImp() entry.
496 # Doxygen might get confused by `ClassImp()` entries as they are macros normally written without
497 # the ending `;`: this function wraps the definition inside a condition in order to make Doxygen
500 # @param filename Name of the current file
501 # @param comments Array of comments: new ones will be appended there
502 def comment_classimp(filename, comments):
504 recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
507 reclassimp = r'^(\s*)Class(Imp|Def)\((.*?)\).*$'
509 in_classimp_cond = False
510 restartcond = r'^\s*///\s*\\cond\s+CLASSIMP\s*$'
511 reendcond = r'^\s*///\s*\\endcond\s*$'
513 with open(filename, 'r') as fp:
517 # Reset to nothing found
521 classimp_class = None
522 classimp_indent = None
524 line_num = line_num + 1
526 mclassimp = re.search(reclassimp, line)
530 classimp_indent = len( mclassimp.group(1) )
532 line_classimp = line_num
533 classimp_class = mclassimp.group(3)
534 imp_or_def = mclassimp.group(2)
536 'Comment found for ' +
537 Colt( 'Class%s(' % imp_or_def ).magenta() +
538 Colt( classimp_class ).cyan() +
539 Colt( ')' ).magenta() )
543 mstartcond = re.search(restartcond, line)
545 logging.debug('Found Doxygen opening condition for ClassImp in {%s}' % line)
546 in_classimp_cond = True
547 line_startcond = line_num
549 elif in_classimp_cond:
551 mendcond = re.search(reendcond, line)
553 logging.debug('Found Doxygen closing condition for ClassImp')
554 in_classimp_cond = False
555 line_endcond = line_num
557 # Did we find something?
558 if line_classimp != -1:
560 if line_startcond != -1:
561 comments.append(Comment(
563 line_startcond, 1, line_startcond, 1,
564 classimp_indent, 'ClassImp/Def(%s)' % classimp_class,
568 comments.append(PrependComment(
570 line_classimp, 1, line_classimp, 1,
571 classimp_indent, 'ClassImp/Def(%s)' % classimp_class
574 if line_endcond != -1:
575 comments.append(Comment(
577 line_endcond, 1, line_endcond, 1,
578 classimp_indent, 'ClassImp/Def(%s)' % classimp_class,
582 comments.append(PrependComment(
584 line_classimp+1, 1, line_classimp+1, 1,
585 classimp_indent, 'ClassImp/Def(%s)' % classimp_class
589 ## Traverse the AST recursively starting from the current cursor.
591 # @param cursor A Clang parser cursor
592 # @param filename Name of the current file
593 # @param comments Array of comments: new ones will be appended there
594 # @param recursion Current recursion depth
595 # @param in_func True if we are inside a function or method
596 # @param classdesc_line_limit Do not look for comments after this line
598 # @return A tuple containing the classdesc_line_limit as first item
599 def traverse_ast(cursor, filename, comments, recursion=0, in_func=False, classdesc_line_limit=None):
601 # libclang traverses included files as well: we do not want this behavior
602 if cursor.location.file is not None and str(cursor.location.file) != filename:
603 logging.debug("Skipping processing of included %s" % cursor.location.file)
606 text = cursor.spelling or cursor.displayname
607 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
609 is_macro = filename.endswith('.C')
612 for i in range(0, recursion):
613 indent = indent + ' '
615 if cursor.kind in [ clang.cindex.CursorKind.CXX_METHOD, clang.cindex.CursorKind.CONSTRUCTOR,
616 clang.cindex.CursorKind.DESTRUCTOR, clang.cindex.CursorKind.FUNCTION_DECL ]:
618 if classdesc_line_limit is None:
619 classdesc_line_limit = cursor.location.line
621 # cursor ran into a C++ method
622 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
623 comment_method(cursor, comments)
626 elif not is_macro and not in_func and \
627 cursor.kind in [ clang.cindex.CursorKind.FIELD_DECL, clang.cindex.CursorKind.VAR_DECL ]:
629 if classdesc_line_limit is None:
630 classdesc_line_limit = cursor.location.line
632 # cursor ran into a data member declaration
633 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
634 comment_datamember(cursor, comments)
638 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
640 for child_cursor in cursor.get_children():
641 classdesc_line_limit = traverse_ast(child_cursor, filename, comments, recursion+1, in_func, classdesc_line_limit)
644 comment_classimp(filename, comments)
645 comment_classdesc(filename, comments, classdesc_line_limit)
647 return classdesc_line_limit
650 ## Strip some HTML tags from the given string. Returns clean string.
652 # @param s Input string
654 rehtml = r'(?i)</?(P|BR)/?>'
655 return re.sub(rehtml, '', s)
658 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
660 # @param comment An array containing the lines of the original comment
661 def refactor_comment(comment, do_strip_html=True, infilename=None):
663 recomm = r'^(/{2,}|/\*)? ?(\s*)(.*?)\s*((/{2,})?\s*|\*/)$'
664 regarbage = r'^(?i)\s*([\s*=_#-]+|(Begin|End)_Html)\s*$'
666 # Support for LaTeX blocks spanning on multiple lines
667 relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
671 # Support for LaTeX blocks on a single line
672 reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
674 # Match <pre> (to turn it into the ~~~ Markdown syntax)
675 reblock = r'(?i)^(\s*)</?PRE>\s*$'
677 # Macro blocks for pictures generation
680 remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
682 # Minimum indent level: scale back everything
683 lowest_indent_level = None
685 # Indentation threshold: if too much indented, don't indent at all
686 indent_level_threshold = 7
690 wait_first_non_blank = True
691 for line_comment in comment:
693 # Check if we are in a macro block
694 mmacro = re.search(remacro, line_comment)
700 outimg = write_macro(infilename, current_macro) + '.png'
704 new_comment.append( '![Picture from ROOT macro](%s)' % (os.path.basename(outimg)) )
706 logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
713 current_macro.append( line_comment )
716 # Strip some HTML tags
718 line_comment = strip_html(line_comment)
720 mcomm = re.search( recomm, line_comment )
722 new_line_comment = mcomm.group(2) + mcomm.group(3) # indent + comm
724 mgarbage = re.search( regarbage, new_line_comment )
726 if mgarbage is None and not mcomm.group(3).startswith('\\') and mcomm.group(3) != '':
727 # not a special command line: count indent
728 indent_level = len( mcomm.group(2) )
729 if lowest_indent_level is None or indent_level < lowest_indent_level:
730 lowest_indent_level = indent_level
732 # if indentation level is too much, consider it zero
733 if indent_level > indent_level_threshold:
734 new_line_comment = mcomm.group(3) # remove ALL indentation
736 if new_line_comment == '' or mgarbage is not None:
739 if insert_blank and not wait_first_non_blank:
740 new_comment.append('')
742 wait_first_non_blank = False
744 # Postprocessing: LaTeX formulas in ROOT format
745 # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
746 # There can be several ROOT LaTeX forumlas per line
748 minline_latex = re.search( reinline_latex, new_line_comment )
750 new_line_comment = '%s\\f$%s\\f$%s' % \
751 ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
752 minline_latex.group(3) )
756 # ROOT LaTeX: do we have a Begin/End_LaTeX block?
757 # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
758 # block here left without a corresponding ending block
759 mlatex = re.search( relatex, new_line_comment )
762 # before and after parts have been already stripped
763 l_before = mlatex.group(2)
764 l_after = mlatex.group(4)
765 is_begin = mlatex.group(3).upper() == 'BEGIN' # if not, END
774 # Begin of LaTeX part
777 if l_before == '' and l_after == '':
779 # Opening tag alone: mark the beginning of a block: \f[ ... \f]
781 new_comment.append( '\\f[' )
784 # Mark the beginning of inline: \f$ ... \f$
787 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
797 # Closing a LaTeX block
799 new_comment.append( l_before.replace('#', '\\') )
800 new_comment.append( '\\f]' )
802 new_comment.append( l_after )
806 # Closing a LaTeX inline
808 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
811 # Prevent appending lines (we have already done that)
812 new_line_comment = None
814 # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
815 # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
816 if new_line_comment is not None and not in_latex:
818 mblock = re.search( reblock, new_line_comment )
820 new_comment.append( mblock.group(1)+'~~~' )
821 new_line_comment = None
823 if new_line_comment is not None:
825 new_line_comment = new_line_comment.replace('#', '\\')
826 new_comment.append( new_line_comment )
829 assert False, 'Comment regexp does not match'
831 # Fixing indentation level
832 if lowest_indent_level is not None:
833 logging.debug('Lowest indentation level found: %d' % lowest_indent_level)
835 new_comment_indent = []
836 reblankstart = r'^\s+'
837 for line in new_comment:
838 if re.search(reblankstart, line):
839 new_comment_indent.append( line[lowest_indent_level:] )
841 new_comment_indent.append( line )
843 new_comment = new_comment_indent
846 logging.debug('No indentation scaling applied')
851 ## Dumps an image-generating macro to the correct place. Returns a string with the image path,
852 # without the extension.
854 # @param infilename File name of the source file
855 # @param macro_lines Array of macro lines
856 def write_macro(infilename, macro_lines):
859 digh = hashlib.sha1()
860 for l in macro_lines:
863 short_digest = digh.hexdigest()[0:7]
865 outdir = '%s/imgdoc' % os.path.dirname(infilename)
866 outprefix = '%s/%s_%s' % (
868 os.path.basename(infilename).replace('.', '_'),
871 outmacro = '%s.C' % outprefix
874 if not os.path.isdir(outdir):
875 # do not catch: let everything die on error
876 logging.debug('Creating directory %s' % Colt(outdir).magenta())
879 # Create file (do not catch errors either)
880 with open(outmacro, 'w') as omfp:
881 logging.debug('Writing macro %s' % Colt(outmacro).magenta())
882 for l in macro_lines:
889 ## Rewrites all comments from the given file handler.
891 # @param fhin The file handler to read from
892 # @param fhout The file handler to write to
893 # @param comments Array of comments
894 def rewrite_comments(fhin, fhout, comments):
905 def dump_comment_block(cmt, restore=None):
907 ask_skip_empty = False
909 for i in range(0, cmt.indent):
910 text_indent = text_indent + ' '
913 fhout.write('%s///' % text_indent )
920 # Empty new line at the end of the comment
923 ask_skip_empty = True
925 # Restore lines if possible
931 # Tell the caller whether it should skip the next empty line found
932 return ask_skip_empty
937 line_num = line_num + 1
939 # Find current comment
944 if c.has_comment(line_num):
948 if len(comm_list) > 1:
952 if len(comm_list) == 2:
954 if isinstance(c1, Comment) and isinstance(c2, Comment):
955 c1.lines = c1.lines + c2.lines # list merge
957 logging.debug('Two adjacent comments merged. Result: {%s}' % Colt(comm).cyan())
964 logging.warning('Too many unmergeable comments on the same line (%d), picking the last one' % len(comm_list))
966 logging.warning('>> %s' % c)
967 comm = c # considering the last one
971 # First thing to check: are we in the same comment as before?
972 if comm is not prev_comm and \
973 isinstance(comm, Comment) and \
974 isinstance(prev_comm, Comment) and \
975 not isinstance(prev_comm, RemoveComment):
977 # We are NOT in the same comment as before, and this comment is dumpable
979 skip_empty = dump_comment_block(prev_comm, restore_lines)
982 prev_comm = None # we have just dumped it: pretend it never existed in this loop
985 # Check type of comment and react accordingly
988 if isinstance(comm, MemberComment):
992 skip_empty = dump_comment_block(prev_comm, restore_lines)
996 non_comment = line[ 0:comm.first_col-1 ]
998 if comm.array_size is not None or comm.is_dontsplit() or comm.is_ptr():
1000 # This is a special case: comment will be split in two lines: one before the comment for
1001 # Doxygen as "member description", and the other right after the comment on the same line
1002 # to be parsed by ROOT's C++ parser
1004 # Keep indent on the generated line of comment before member definition
1005 mindent = re.search(rindent, line)
1007 # Get correct comment flag, if any
1008 if comm.comment_flag is not None:
1009 cflag = comm.comment_flag
1013 # Get correct array size, if any
1014 if comm.array_size is not None:
1015 asize = '[%s]' % comm.array_size
1019 # Write on two lines
1020 fhout.write('%s/// %s\n%s//%s%s\n' % (
1030 # Single-line comments with the "transient" flag can be kept on one line in a way that
1031 # they are correctly interpreted by both ROOT and Doxygen
1033 if comm.is_transient():
1038 fhout.write('%s//%s< %s\n' % (
1044 elif isinstance(comm, RemoveComment):
1045 # End comment block and skip this line
1047 skip_empty = dump_comment_block(prev_comm, restore_lines)
1049 restore_lines = None
1051 elif restore_lines is None:
1053 # Beginning of a new comment block of type Comment or PrependComment
1056 if isinstance(comm, PrependComment):
1057 # Prepare array of lines to dump right after the comment
1058 restore_lines = [ line.rstrip('\n') ]
1059 logging.debug('Commencing lines to restore: {%s}' % Colt(restore_lines[0]).cyan())
1061 # Extract the non-comment part and print it if it exists
1062 non_comment = line[ 0:comm.first_col-1 ].rstrip()
1063 if non_comment != '':
1064 fhout.write( non_comment + '\n' )
1066 elif isinstance(comm, Comment):
1068 if restore_lines is not None:
1069 # From the 2nd line on of comment to prepend
1070 restore_lines.append( line.rstrip('\n') )
1071 logging.debug('Appending lines to restore. All lines: {%s}' % Colt(restore_lines).cyan())
1074 assert False, 'Unhandled parser state: line=%d comm={%s} prev_comm={%s}' % \
1075 (line_num, comm, prev_comm)
1079 # Not a comment line
1083 # We have just exited a comment block of type Comment
1084 skip_empty = dump_comment_block(prev_comm, restore_lines)
1086 restore_lines = None
1088 # Dump the non-comment line
1089 line_out = line.rstrip('\n')
1092 if line_out.strip() != '':
1093 fhout.write( line_out + '\n' )
1095 fhout.write( line_out + '\n' )
1097 # Is there some comment left here?
1098 if restore_lines is not None:
1099 dump_comment_block(comm, restore_lines)
1101 # Is there some other comment beyond the last line?
1103 if c.has_comment(line_num+1):
1104 dump_comment_block(c, None)
1108 ## The main function.
1110 # Return value is the executable's return value.
1113 # Setup logging on stderr
1114 log_level = logging.INFO
1115 logging.basicConfig(
1117 format='%(levelname)-8s %(funcName)-20s %(message)s',
1121 # Parse command-line options
1122 output_on_stdout = False
1125 opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
1128 log_level = getattr( logging, a.upper(), None )
1129 if not isinstance(log_level, int):
1130 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
1132 log_level = logging.DEBUG
1133 elif o == '-o' or o == '--stdout':
1134 output_on_stdout = True
1136 if os.path.isdir(a):
1137 include_flags.extend( [ '-I', a ] )
1139 logging.fatal('Include directory not found: %s' % Colt(a).magenta())
1142 assert False, 'Unhandled argument'
1143 except getopt.GetoptError as e:
1144 logging.fatal('Invalid arguments: %s' % e)
1147 logging.getLogger('').setLevel(log_level)
1149 # Attempt to load libclang from a list of known locations
1150 libclang_locations = [
1151 '/usr/lib/llvm-3.5/lib/libclang.so.1',
1152 '/usr/lib/libclang.so',
1153 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
1155 libclang_found = False
1157 for lib in libclang_locations:
1158 if os.path.isfile(lib):
1159 clang.cindex.Config.set_library_file(lib)
1160 libclang_found = True
1163 if not libclang_found:
1164 logging.fatal('Cannot find libclang')
1167 # Loop over all files
1170 logging.info('Input file: %s' % Colt(fn).magenta())
1171 index = clang.cindex.Index.create()
1172 clang_args = [ '-x', 'c++' ]
1173 clang_args.extend( include_flags )
1174 translation_unit = index.parse(fn, args=clang_args)
1177 traverse_ast( translation_unit.cursor, fn, comments )
1180 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
1182 if isinstance(c, MemberComment):
1184 if c.is_transient():
1185 flag_text = Colt('transient ').yellow()
1186 elif c.is_dontsplit():
1187 flag_text = Colt('dontsplit ').yellow()
1189 flag_text = Colt('ptr ').yellow()
1193 if c.array_size is not None:
1194 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
1200 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
1203 Colt(c.lines[0]).cyan()
1206 elif isinstance(c, RemoveComment):
1208 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
1213 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
1214 "{%s}" % Colt(l).cyan()
1219 if output_on_stdout:
1220 with open(fn, 'r') as fhin:
1221 rewrite_comments( fhin, sys.stdout, comments )
1223 fn_back = fn + '.thtml2doxy_backup'
1224 os.rename( fn, fn_back )
1226 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
1227 rewrite_comments( fhin, fhout, comments )
1229 os.remove( fn_back )
1230 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
1231 except (IOError,OSError) as e:
1232 logging.error('File operation failed: %s' % e)
1237 if __name__ == '__main__':
1238 sys.exit( main( sys.argv[1:] ) )