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 file1 [file2 [file3...]]`
24 # @author Dario Berzano <dario.berzano@cern.ch>
36 ## Brain-dead color output for terminal.
40 return self.color('\033[31m')
43 return self.color('\033[32m')
46 return self.color('\033[33m')
49 return self.color('\033[34m')
52 return self.color('\033[35m')
55 return self.color('\033[36m')
58 return c + self + '\033[m'
64 def __init__(self, lines, first_line, last_line, func):
66 self.first_line = first_line
67 self.last_line = last_line
71 return "<Comment for %s: [%d:%d] %s>" % (self.func, self.first_line, self.last_line, self.lines)
74 ## Traverse the AST recursively starting from the current cursor.
76 # @param cursor A Clang parser cursor
77 # @param comments Array of comments found (of class Comment)
78 # @param recursion Current recursion depth
79 def traverse_ast(cursor, comments, recursion=0):
81 text = cursor.spelling or cursor.displayname
82 kind = str(cursor.kind)[str(cursor.kind).index('.')+1:]
85 for i in range(0, recursion):
88 if cursor.kind == clang.cindex.CursorKind.CXX_METHOD:
90 # cursor ran into a C++ method
91 logging.debug( "%s%s(%s)" % (indent, Colt(kind).magenta(), Colt(text).blue()) )
93 # we are looking for the following structure: method -> compound statement -> comment, i.e. we
94 # need to extract the first comment in the compound statement composing the method
96 in_compound_stmt = False
97 expect_comment = False
101 comment_function = text
102 comment_line_start = -1
103 comment_line_end = -1
105 for token in cursor.get_tokens():
107 if token.cursor.kind == clang.cindex.CursorKind.COMPOUND_STMT:
108 if not in_compound_stmt:
109 in_compound_stmt = True
110 expect_comment = True
111 comment_line_end = -1
114 in_compound_stmt = False
117 # tkind = str(token.kind)[str(token.kind).index('.')+1:]
118 # ckind = str(token.cursor.kind)[str(token.cursor.kind).index('.')+1:]
124 extent = token.extent
125 line_start = extent.start.line
126 line_end = extent.end.line
128 if token.kind == clang.cindex.TokenKind.PUNCTUATION and token.spelling == '{':
131 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)):
132 comment_line_end = line_end
134 if comment_line_start == -1:
135 comment_line_start = line_start
136 comment.extend( token.spelling.split('\n') )
138 # multiline comments are parsed in one go, therefore don't expect subsequent comments
139 if line_end - line_start > 0:
141 expect_comment = False
145 expect_comment = False
149 comment = refactor_comment( comment )
152 logging.debug("Comment found for function %s" % Colt(comment_function).magenta())
153 comments.append( Comment(comment, comment_line_start, comment_line_end, comment_function) )
156 comment_line_start = -1
157 comment_line_end = -1
164 logging.debug( "%s%s(%s)" % (indent, kind, text) )
166 for child_cursor in cursor.get_children():
167 traverse_ast(child_cursor, comments, recursion+1)
170 ## Remove garbage from comments and convert special tags from THtml to Doxygen.
172 # @param comment An array containing the lines of the original comment
173 def refactor_comment(comment):
175 recomm = r'^(/{2,}|/\*)?\s*(.*?)\s*((/{2,})?\s*|\*/)$'
179 wait_first_non_blank = True
180 for line_comment in comment:
181 mcomm = re.search( recomm, line_comment )
183 new_line_comment = mcomm.group(2)
184 if new_line_comment == '':
187 if insert_blank and not wait_first_non_blank:
188 new_comment.append('')
190 wait_first_non_blank = False
191 new_comment.append( new_line_comment )
193 assert False, 'Comment regexp does not match'
198 ## The main function.
200 # Return value is the executable's return value.
203 # Setup logging on stderr
204 log_level = logging.WARNING
207 format='%(levelname)-8s %(funcName)-20s %(message)s',
211 # Parse command-line options
213 opts, args = getopt.getopt( argv, 'd', [ 'debug=' ] )
216 log_level = getattr( logging, a.upper(), None )
217 if not isinstance(log_level, int):
218 raise getopt.GetoptError('log level must be one of: DEBUG, INFO, WARNING, ERROR, CRITICAL')
220 log_level = logging.DEBUG
222 assert False, 'Unhandled argument'
223 except getopt.GetoptError as e:
224 logging.fatal('Invalid arguments: %s' % e)
227 logging.getLogger('').setLevel(log_level)
229 # Attempt to load libclang from a list of known locations
230 libclang_locations = [
231 '/usr/lib/llvm-3.5/lib/libclang.so.1',
232 '/usr/lib/libclang.so',
233 '/Library/Developer/CommandLineTools/usr/lib/libclang.dylib'
235 libclang_found = False
237 for lib in libclang_locations:
238 if os.path.isfile(lib):
239 clang.cindex.Config.set_library_file(lib)
240 libclang_found = True
243 if not libclang_found:
244 logging.fatal('Cannot find libclang')
247 # Loop over all files
250 logging.info('Input file: %s' % Colt(fn).magenta())
251 index = clang.cindex.Index.create()
252 translation_unit = index.parse(fn, args=['-x', 'c++'])
255 traverse_ast( translation_unit.cursor, comments )
257 logging.info("Comment found for %s:" % Colt(c.func).magenta())
260 Colt("[%d:%d] " % (c.first_line, c.last_line)).green() +
261 "{%s}" % Colt(l).cyan()
267 if __name__ == '__main__':
268 sys.exit( main( sys.argv[1:] ) )