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):
99 super(PrependComment, self).__init__( \
100 lines, first_line, first_col, last_line, last_col, indent, func, False)
103 ## A data member comment.
106 def __init__(self, text, comment_flag, array_size, first_line, first_col, func):
107 assert first_line > 0, 'Wrong line number'
108 assert comment_flag is None or comment_flag == '!' or comment_flag in [ '!', '||', '->' ]
109 self.lines = [ text ]
110 self.comment_flag = comment_flag
111 self.array_size = array_size
112 self.first_line = first_line
113 self.first_col = first_col
116 def is_transient(self):
117 return self.comment_flag == '!'
119 def is_dontsplit(self):
120 return self.comment_flag == '||'
123 return self.comment_flag == '->'
125 def has_comment(self, line):
126 return line == self.first_line
130 if self.is_transient():
132 elif self.is_dontsplit():
139 if self.array_size is not None:
140 ars = '[%s] ' % self.array_size
144 return "<MemberComment for %s: [%d,%d] %s%s%s>" % (self.func, self.first_line, self.first_col, tt, ars, self.lines[0])
147 ## A dummy comment that removes comment lines.
148 class RemoveComment(Comment):
150 def __init__(self, first_line, last_line):
151 assert first_line > 0 and last_line >= first_line, 'Wrong line numbers'
152 self.first_line = first_line
153 self.last_line = last_line
154 self.func = '<remove>'
157 return "<RemoveComment: [%d,%d]>" % (self.first_line, self.last_line)
160 ## Parses method comments.
162 # @param cursor Current libclang parser cursor
163 # @param comments Array of comments: new ones will be appended there
164 def comment_method(cursor, comments):
166 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
167 # need to extract the first comment in the compound statement composing the method
169 in_compound_stmt = False
170 expect_comment = False
174 comment_function = cursor.spelling or cursor.displayname
175 comment_line_start = -1
176 comment_line_end = -1
177 comment_col_start = -1
181 for token in cursor.get_tokens():
183 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
184 if not in_compound_stmt:
185 in_compound_stmt = True
186 expect_comment = True
187 comment_line_end = -1
190 in_compound_stmt = False
193 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
194 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
200 extent = token.extent
201 line_start = extent.start.line
202 line_end = extent.end.line
204 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
207 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)):
208 comment_line_end = line_end
209 comment_col_end = extent.end.column
211 if comment_indent == -1 or (extent.start.column-1) < comment_indent:
212 comment_indent = extent.start.column-1
214 if comment_line_start == -1:
215 comment_line_start = line_start
216 comment_col_start = extent.start.column
217 comment.extend( token.spelling.split('\n') )
219 # multiline comments are parsed in one go, therefore don't expect subsequent comments
220 if line_end - line_start > 0:
222 expect_comment = False
226 expect_comment = False
230 if comment_line_start > 0:
232 comment = refactor_comment( comment, infilename=str(cursor.location.file) )
235 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
236 comments.append( Comment(comment, comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
238 logging.debug('Empty comment found for function %s: collapsing' % Colt(comment_function).magenta())
239 comments.append( Comment([''], comment_line_start, comment_col_start, comment_line_end, comment_col_end, comment_indent, comment_function) )
240 #comments.append(RemoveComment(comment_line_start, comment_line_end))
243 logging.warning('No comment found for function %s' % Colt(comment_function).magenta())
246 comment_line_start = -1
247 comment_line_end = -1
248 comment_col_start = -1
256 ## Parses comments to class data members.
258 # @param cursor Current libclang parser cursor
259 # @param comments Array of comments: new ones will be appended there
260 def comment_datamember(cursor, comments):
262 # Note: libclang 3.5 seems to have problems parsing a certain type of FIELD_DECL, so we revert
263 # to a partial manual parsing. When parsing fails, the cursor's "extent" is not set properly,
264 # returning a line range 0-0. We therefore make the not-so-absurd assumption that the datamember
265 # definition is fully on one line, and we take the line number from cursor.location.
267 line_num = cursor.location.line
272 # Huge overkill: current line saved in "raw", previous in "prev"
273 with open(str(cursor.location.file)) as fp:
276 cur_line = cur_line + 1
277 if cur_line == line_num:
282 assert found, 'A line that should exist was not found in file' % cursor.location.file
284 recomm = r'(//(!|\|\||->)|///?)(\[([0-9,]+)\])?<?\s*(.*?)\s*$'
285 recomm_prevline = r'^\s*///\s*(.*?)\s*$'
287 mcomm = re.search(recomm, raw)
289 # If it does not match, we do not have a comment
290 member_name = cursor.spelling;
291 comment_flag = mcomm.group(2)
292 array_size = mcomm.group(4)
293 text = mcomm.group(5)
295 col_num = mcomm.start()+1;
297 if array_size is not None and prev is not None:
298 # ROOT arrays with comments already converted to Doxygen have the member description on the
300 mcomm_prevline = re.search(recomm_prevline, prev)
302 text = mcomm_prevline.group(1)
303 comments.append(RemoveComment(line_num-1, line_num-1))
305 logging.debug('Comment found for member %s' % Colt(member_name).magenta())
307 comments.append( MemberComment(
316 ## Parses class description (beginning of file).
318 # The clang parser does not work in this case so we do it manually, but it is very simple: we keep
319 # the first consecutive sequence of single-line comments (//) we find - provided that it occurs
320 # before any other comment found so far in the file (the comments array is inspected to ensure
323 # Multi-line comments (/* ... */) are not considered as they are commonly used to display
326 # @param filename Name of the current file
327 # @param comments Array of comments: new ones will be appended there
328 def comment_classdesc(filename, comments):
330 recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
332 reclass_doxy = r'(?i)^\s*\\(class|file):?\s*([^.]*)'
333 class_name_doxy = None
335 reauthor = r'(?i)^\s*\\?authors?:?\s*(.*?)\s*(,?\s*([0-9./-]+))?\s*$'
336 redate = r'(?i)^\s*\\?date:?\s*([0-9./-]+)\s*$'
347 is_macro = filename.endswith('.C')
349 with open(filename, 'r') as fp:
353 line_num = line_num + 1
355 if raw.strip() == '' and start_line > 0:
359 stripped = strip_html(raw)
360 mcomm = re.search(recomm, stripped)
365 # First line. Check that we do not overlap with other comments
366 comment_overlaps = False
368 if c.has_comment(line_num):
369 comment_overlaps = True
373 # No need to look for other comments
376 start_line = line_num
381 mclass_doxy = re.search(reclass_doxy, mcomm.group(1))
383 class_name_doxy = mclass_doxy.group(2)
386 mauthor = re.search(reauthor, mcomm.group(1))
388 author = mauthor.group(1)
390 # Date specified in the standalone \date field has priority
391 date = mauthor.group(3)
394 mdate = re.search(redate, mcomm.group(1))
396 date = mdate.group(1)
400 comment_lines.append( mcomm.group(1) )
406 if class_name_doxy is None:
408 # No \class specified: guess it from file name
409 reclass = r'^(.*/)?(.*?)(\..*)?$'
410 mclass = re.search( reclass, filename )
412 class_name_doxy = mclass.group(2)
414 assert False, 'Regexp unable to extract classname from file'
418 # Prepend \class or \file specifier (and an empty line)
420 comment_lines[:0] = [ '\\file ' + class_name_doxy + '.C' ]
422 comment_lines[:0] = [ '\\class ' + class_name_doxy ]
423 comment_lines.append('')
425 # Append author and date if they exist
426 if author is not None:
427 comment_lines.append( '\\author ' + author )
430 comment_lines.append( '\\date ' + date )
432 comment_lines = refactor_comment(comment_lines, do_strip_html=False, infilename=filename)
433 logging.debug('Comment found for class %s' % Colt(class_name_doxy).magenta())
434 comments.append(Comment(
436 start_line, 1, end_line, 1,
442 logging.warning('No comment found for class %s' % Colt(class_name_doxy).magenta())
445 ## Looks for a special ROOT ClassImp() entry.
447 # Doxygen might get confused by `ClassImp()` entries as they are macros normally written without
448 # the ending `;`: this function wraps the definition inside a condition in order to make Doxygen
451 # @param filename Name of the current file
452 # @param comments Array of comments: new ones will be appended there
453 def comment_classimp(filename, comments):
455 recomm = r'^\s*///?(\s*.*?)\s*/*\s*$'
458 reclassimp = r'^(\s*)ClassImp\((.*?)\)\s*;?\s*$'
460 in_classimp_cond = False
461 restartcond = r'^\s*///\s*\\cond\s+CLASSIMP\s*$'
462 reendcond = r'^\s*///\s*\\endcond\s*$'
464 with open(filename, 'r') as fp:
469 classimp_class = None
470 classimp_indent = None
474 line_num = line_num + 1
476 mclassimp = re.search(reclassimp, line)
480 classimp_indent = len( mclassimp.group(1) )
482 line_classimp = line_num
483 classimp_class = mclassimp.group(2)
485 'Comment found for ' +
486 Colt( 'ClassImp(' ).magenta() +
487 Colt( classimp_class ).cyan() +
488 Colt( ')' ).magenta() )
492 mstartcond = re.search(restartcond, line)
494 logging.debug('Found Doxygen opening condition for ClassImp in {%s}' % line)
495 in_classimp_cond = True
496 line_startcond = line_num
498 elif in_classimp_cond:
500 mendcond = re.search(reendcond, line)
502 logging.debug('Found Doxygen closing condition for ClassImp')
503 in_classimp_cond = False
504 line_endcond = line_num
506 # Did we find something?
507 if line_classimp != -1:
509 if line_startcond != -1:
510 comments.append(Comment(
512 line_startcond, 1, line_startcond, 1,
513 classimp_indent, 'ClassImp(%s)' % classimp_class,
517 comments.append(PrependComment(
519 line_classimp, 1, line_classimp, 1,
520 classimp_indent, 'ClassImp(%s)' % classimp_class
523 if line_endcond != -1:
524 comments.append(Comment(
526 line_endcond, 1, line_endcond, 1,
527 classimp_indent, 'ClassImp(%s)' % classimp_class,
531 comments.append(PrependComment(
533 line_classimp+1, 1, line_classimp+1, 1,
534 classimp_indent, 'ClassImp(%s)' % classimp_class
538 ## Traverse the AST recursively starting from the current cursor.
540 # @param cursor A Clang parser cursor
541 # @param filename Name of the current file
542 # @param comments Array of comments: new ones will be appended there
543 # @param recursion Current recursion depth
544 # @param in_func True if we are inside a function or method
545 def traverse_ast(cursor, filename, comments, recursion=0, in_func=False):
547 # libclang traverses included files as well: we do not want this behavior
548 if cursor.location.file is not None and str(cursor.location.file) != filename:
549 logging.debug("Skipping processing of included %s" % cursor.location.file)
552 text = cursor.spelling or cursor.displayname
553 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
555 is_macro = filename.endswith('.C')
558 for i in range(0, recursion):
559 indent = indent + ' '
561 if cursor.kind in [ clang.cindex.CursorKind.CXX_METHOD, clang.cindex.CursorKind.CONSTRUCTOR,
562 clang.cindex.CursorKind.DESTRUCTOR, clang.cindex.CursorKind.FUNCTION_DECL ]:
564 # cursor ran into a C++ method
565 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
566 comment_method(cursor, comments)
569 elif not is_macro and not in_func and \
570 cursor.kind in [ clang.cindex.CursorKind.FIELD_DECL, clang.cindex.CursorKind.VAR_DECL ]:
572 # cursor ran into a data member declaration
573 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, Colt(kind).magenta(), Colt(text).blue()) )
574 comment_datamember(cursor, comments)
578 logging.debug( "%5d %s%s(%s)" % (cursor.location.line, indent, kind, text) )
580 for child_cursor in cursor.get_children():
581 traverse_ast(child_cursor, filename, comments, recursion+1, in_func)
584 comment_classimp(filename, comments)
585 comment_classdesc(filename, comments)
588 ## Strip some HTML tags from the given string. Returns clean string.
590 # @param s Input string
592 rehtml = r'(?i)</?(P|BR)/?>'
593 return re.sub(rehtml, '', s)
596 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
598 # @param comment An array containing the lines of the original comment
599 def refactor_comment(comment, do_strip_html=True, infilename=None):
601 recomm = r'^(/{2,}|/\*)? ?(\s*.*?)\s*((/{2,})?\s*|\*/)$'
602 regarbage = r'^(?i)\s*([\s*=-_#]+|(Begin|End)_Html)\s*$'
604 # Support for LaTeX blocks spanning on multiple lines
605 relatex = r'(?i)^((.*?)\s+)?(BEGIN|END)_LATEX([.,;:\s]+.*)?$'
609 # Support for LaTeX blocks on a single line
610 reinline_latex = r'(?i)(.*)BEGIN_LATEX\s+(.*?)\s+END_LATEX(.*)$'
612 # Match <pre> (to turn it into the ~~~ Markdown syntax)
613 reblock = r'(?i)^(\s*)</?PRE>\s*$'
615 # Macro blocks for pictures generation
618 remacro = r'(?i)^\s*(BEGIN|END)_MACRO(\((.*?)\))?\s*$'
622 wait_first_non_blank = True
623 for line_comment in comment:
625 # Check if we are in a macro block
626 mmacro = re.search(remacro, line_comment)
632 outimg = write_macro(infilename, current_macro) + '.png'
636 new_comment.append( '![Picture from ROOT macro](%s)' % (outimg) )
638 logging.debug( 'Found macro for generating image %s' % Colt(outimg).magenta() )
645 current_macro.append( line_comment )
648 # Strip some HTML tags
650 line_comment = strip_html(line_comment)
652 mcomm = re.search( recomm, line_comment )
654 new_line_comment = mcomm.group(2)
655 mgarbage = re.search( regarbage, new_line_comment )
657 if new_line_comment == '' or mgarbage is not None:
660 if insert_blank and not wait_first_non_blank:
661 new_comment.append('')
663 wait_first_non_blank = False
665 # Postprocessing: LaTeX formulas in ROOT format
666 # Marked by BEGIN_LATEX ... END_LATEX and they use # in place of \
667 # There can be several ROOT LaTeX forumlas per line
669 minline_latex = re.search( reinline_latex, new_line_comment )
671 new_line_comment = '%s\\f$%s\\f$%s' % \
672 ( minline_latex.group(1), minline_latex.group(2).replace('#', '\\'),
673 minline_latex.group(3) )
677 # ROOT LaTeX: do we have a Begin/End_LaTeX block?
678 # Note: the presence of LaTeX "closures" does not exclude the possibility to have a begin
679 # block here left without a corresponding ending block
680 mlatex = re.search( relatex, new_line_comment )
683 # before and after parts have been already stripped
684 l_before = mlatex.group(2)
685 l_after = mlatex.group(4)
686 is_begin = mlatex.group(3).upper() == 'BEGIN' # if not, END
695 # Begin of LaTeX part
698 if l_before == '' and l_after == '':
700 # Opening tag alone: mark the beginning of a block: \f[ ... \f]
702 new_comment.append( '\\f[' )
705 # Mark the beginning of inline: \f$ ... \f$
708 '%s \\f$%s' % ( l_before, l_after.replace('#', '\\') )
718 # Closing a LaTeX block
720 new_comment.append( l_before.replace('#', '\\') )
721 new_comment.append( '\\f]' )
723 new_comment.append( l_after )
727 # Closing a LaTeX inline
729 '%s\\f$%s' % ( l_before.replace('#', '\\'), l_after )
732 # Prevent appending lines (we have already done that)
733 new_line_comment = None
735 # If we are not in a LaTeX block, look for <pre> tags and transform them into Doxygen code
736 # blocks (using ~~~ ... ~~~). Only <pre> tags on a single line are supported
737 if new_line_comment is not None and not in_latex:
739 mblock = re.search( reblock, new_line_comment )
741 new_comment.append( mblock.group(1)+'~~~' )
742 new_line_comment = None
744 if new_line_comment is not None:
746 new_line_comment = new_line_comment.replace('#', '\\')
747 new_comment.append( new_line_comment )
750 assert False, 'Comment regexp does not match'
755 ## Dumps an image-generating macro to the correct place. Returns a string with the image path,
756 # without the extension.
758 # @param infilename File name of the source file
759 # @param macro_lines Array of macro lines
760 def write_macro(infilename, macro_lines):
763 digh = hashlib.sha1()
764 for l in macro_lines:
767 short_digest = digh.hexdigest()[0:7]
769 outdir = '%s/imgdoc' % os.path.dirname(infilename)
770 outprefix = '%s/%s_%s' % (
772 os.path.basename(infilename).replace('.', '_'),
775 outmacro = '%s.C' % outprefix
778 if not os.path.isdir(outdir):
779 # do not catch: let everything die on error
780 logging.debug('Creating directory %s' % Colt(outdir).magenta())
783 # Create file (do not catch errors either)
784 with open(outmacro, 'w') as omfp:
785 logging.debug('Writing macro %s' % Colt(outmacro).magenta())
786 for l in macro_lines:
793 ## Rewrites all comments from the given file handler.
795 # @param fhin The file handler to read from
796 # @param fhout The file handler to write to
797 # @param comments Array of comments
798 def rewrite_comments(fhin, fhout, comments):
809 def dump_comment_block(cmt, restore=None):
811 ask_skip_empty = False
813 for i in range(0, cmt.indent):
814 text_indent = text_indent + ' '
817 fhout.write('%s///' % text_indent )
824 # Empty new line at the end of the comment
827 ask_skip_empty = True
829 # Restore lines if possible
835 # Tell the caller whether it should skip the next empty line found
836 return ask_skip_empty
841 line_num = line_num + 1
843 # Find current comment
847 if c.has_comment(line_num):
852 # First thing to check: are we in the same comment as before?
853 if comm is not prev_comm and isinstance(comm, Comment) and isinstance(prev_comm, Comment) \
854 and not isinstance(prev_comm, RemoveComment):
856 skip_empty = dump_comment_block(prev_comm, restore_lines)
859 prev_comm = None # we have just dumped it: pretend it never existed in this loop
862 # Check type of comment and react accordingly
865 if isinstance(comm, MemberComment):
869 skip_empty = dump_comment_block(prev_comm, restore_lines)
873 non_comment = line[ 0:comm.first_col-1 ]
875 if comm.array_size is not None or comm.is_dontsplit() or comm.is_ptr():
877 # This is a special case: comment will be split in two lines: one before the comment for
878 # Doxygen as "member description", and the other right after the comment on the same line
879 # to be parsed by ROOT's C++ parser
881 # Keep indent on the generated line of comment before member definition
882 mindent = re.search(rindent, line)
884 # Get correct comment flag, if any
885 if comm.comment_flag is not None:
886 cflag = comm.comment_flag
890 # Get correct array size, if any
891 if comm.array_size is not None:
892 asize = '[%s]' % comm.array_size
897 fhout.write('%s/// %s\n%s//%s%s\n' % (
907 # Single-line comments with the "transient" flag can be kept on one line in a way that
908 # they are correctly interpreted by both ROOT and Doxygen
910 if comm.is_transient():
915 fhout.write('%s//%s< %s\n' % (
921 elif isinstance(comm, RemoveComment):
922 # End comment block and skip this line
924 skip_empty = dump_comment_block(prev_comm, restore_lines)
928 elif prev_comm is None:
930 # Beginning of a new comment block of type Comment or PrependComment
933 if isinstance(comm, PrependComment):
934 # Prepare array of lines to dump right after the comment
935 restore_lines = [ line.rstrip('\n') ]
937 # Extract the non-comment part and print it if it exists
938 non_comment = line[ 0:comm.first_col-1 ].rstrip()
939 if non_comment != '':
940 fhout.write( non_comment + '\n' )
942 elif isinstance(comm, Comment):
944 if restore_lines is not None:
945 # From the 2nd line on of comment to prepend
946 restore_lines.append( line.rstrip('\n') )
949 assert False, 'Unhandled parser state. line=%d comm=%s prev_comm=%s' % \
950 (line_num, comm, prev_comm)
958 # We have just exited a comment block of type Comment
959 skip_empty = dump_comment_block(prev_comm, restore_lines)
963 # Dump the non-comment line
964 line_out = line.rstrip('\n')
967 if line_out.strip() != '':
968 fhout.write( line_out + '\n' )
970 fhout.write( line_out + '\n' )
973 ## The main function.
975 # Return value is the executable's return value.
978 # Setup logging on stderr
979 log_level = logging.INFO
982 format='%(levelname)-8s %(funcName)-20s %(message)s',
986 # Parse command-line options
987 output_on_stdout = False
990 opts, args = getopt.getopt( argv, 'odI:', [ 'debug=', 'stdout' ] )
993 log_level = getattr( logging, a.upper(), None )
994 if not isinstance(log_level, int):
995 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
997 log_level = logging.DEBUG
998 elif o == '-o' or o == '--stdout':
999 output_on_stdout = True
1001 if os.path.isdir(a):
1002 include_flags.extend( [ '-I', a ] )
1004 logging.fatal('Include directory not found: %s' % Colt(a).magenta())
1007 assert False, 'Unhandled argument'
1008 except getopt.GetoptError as e:
1009 logging.fatal('Invalid arguments: %s' % e)
1012 logging.getLogger('').setLevel(log_level)
1014 # Attempt to load libclang from a list of known locations
1015 libclang_locations = [
1016 '/usr/lib/llvm-3.5/lib/libclang.so.1',
1017 '/usr/lib/libclang.so',
1018 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
1020 libclang_found = False
1022 for lib in libclang_locations:
1023 if os.path.isfile(lib):
1024 clang.cindex.Config.set_library_file(lib)
1025 libclang_found = True
1028 if not libclang_found:
1029 logging.fatal('Cannot find libclang')
1032 # Loop over all files
1035 logging.info('Input file: %s' % Colt(fn).magenta())
1036 index = clang.cindex.Index.create()
1037 clang_args = [ '-x', 'c++' ]
1038 clang_args.extend( include_flags )
1039 translation_unit = index.parse(fn, args=clang_args)
1042 traverse_ast( translation_unit.cursor, fn, comments )
1045 logging.debug("Comment found for entity %s:" % Colt(c.func).magenta())
1047 if isinstance(c, MemberComment):
1049 if c.is_transient():
1050 flag_text = Colt('transient ').yellow()
1051 elif c.is_dontsplit():
1052 flag_text = Colt('dontsplit ').yellow()
1054 flag_text = Colt('ptr ').yellow()
1058 if c.array_size is not None:
1059 array_text = Colt('arraysize=%s ' % c.array_size).yellow()
1065 Colt("[%d,%d]" % (c.first_line, c.first_col)).green(),
1068 Colt(c.lines[0]).cyan()
1071 elif isinstance(c, RemoveComment):
1073 logging.debug( Colt('[%d,%d]' % (c.first_line, c.last_line)).green() )
1078 Colt("[%d,%d:%d,%d] " % (c.first_line, c.first_col, c.last_line, c.last_col)).green() +
1079 "{%s}" % Colt(l).cyan()
1084 if output_on_stdout:
1085 with open(fn, 'r') as fhin:
1086 rewrite_comments( fhin, sys.stdout, comments )
1088 fn_back = fn + '.thtml2doxy_backup'
1089 os.rename( fn, fn_back )
1091 with open(fn_back, 'r') as fhin, open(fn, 'w') as fhout:
1092 rewrite_comments( fhin, fhout, comments )
1094 os.remove( fn_back )
1095 logging.info("File %s converted to Doxygen: check differences before committing!" % Colt(fn).magenta())
1096 except (IOError,OSError) as e:
1097 logging.error('File operation failed: %s' % e)
1102 if __name__ == '__main__':
1103 sys.exit( main( sys.argv[1:] ) )